ruby openssl smime encryption - ruby

I am looking for ruby code to mimic below openssl smime encryption. I looked up other related topics but mostly were around signing. In snippet below cert.pem is a PEM-encoded X.509 certificate containing the PEM public key. token.txt file is the file to be encrypted.
openssl smime -encrypt -out encrypted.p7m -in token.txt cert.pem

Figured it.
token_plain_text = File.read("/path/to/token.txt")
cert = X509::Certificate.new("/path/to/cert.pem")
encrypted_object = OpenSSL::PKCS7.encrypt([cert], token_plain_text)
Got the encrypted string by outputting above object to string.
encrypted_str = encrypted_object.to_str

Related

How do I convert a SSH2 PUBLIC KEY (rsa-key file) to PEM? (Base-64 encoded public key of X.509 certificate)

I have a private/public key that was generated by Putty in the following format:
SSH2 PUBLIC KEY rsa-key
However, I am trying to get it to work with Docebo API using the JWT Grant Type, which requires a different format (according to this post).
How would I convert my key(s) to work with that format? Is there a way within Putty?
I figured out the steps to take to get the proper format of key using OpenSSL:
openssl genrsa -out private.key 1024
openssl req -new -x509 -key private.key -out publickey.cer
openssl x509 -in publickey.cer -out publickey.pem

Ruby OpenSSL pkcs8 .key to .pem

We run this command via Gem.
openssl pkcs8 -inform DER -in file_init.key -passin pass:secret -out file_key.pem
All works fine on shell, we wanna convert this line to openssl with ruby, we tried:
key_file = OpenSSL::PKey::RSA.new File.read('file_init'), 'secret'
puts key_file.to_pem_pkcs8
But we get:
`initialize': Neither PUB key nor PRIV key: nested asn1 error (OpenSSL::PKey::RSAError)
Any advice?
Ruby's openssl implementation doesn't handle pkcs8 encrypted der key-file.
There is a workaround (converting the der to PEM by base64 encoding the der + adding correct headers) here:
Load PKCS#8 binary key into Ruby

How do I convert a pem to pfx file?

This has me confused:
Convert pfx to PEM:
openssl pkcs12 -in certificatename.pfx -out certificatename.pem
Do this dumps out a single plain text file.
Now how do I convert this plain text pem back to pfx?
The only commands I see to convert to pfx require the cer and private keys in separate files:
Convert CER and Private Key to PFX:
openssl pkcs12 -export -in certificatename.cer -inkey privateKey.key -out certificatename.pfx -certfile cacert.cer
Although I concur this is not really programming and arguably offtopic, numerous similar Qs about commandline tools (openssl, keytool, certutil etc) for (crypto) keys and certs are apparently accepted by the community (upvoted) -- but none I've seen directly addresses this point.
The different options on openssl pkcs12 -export allow you to provide the pieces in different files, but that is not required. If you do have the privatekey and chain of certs in one PEM file, as output by default by pkcs12 [not -export], you can let everything be read from that one file:
openssl pkcs12 -export -in file -out p12
# or ONLY IF the privatekey is first in the file
openssl pkcs12 -export <file -out p12
and you can even combine the pieces 'on the fly' as long as you put privatekey first:
cat privkey.pem mycert.pem chain.pem | openssl pkcs12 -export -out p12
You can use the command below to convert PEM (.pem, .crt, .cer) to PFX:
openssl pkcs12 -export -out **<your_new_file_name>**.pfx -inkey **<private_key_of_your_existing_certificate>**.key -in **<your_existing_certificate_file>**.crt
This will be very generic for all above mentioned files.

Ruby code for openssl to generate fingerprint

I need the ruby equivalent of the following:
openssl x509 -sha1 -fingerprint -noout -in cert.pem
The code that I wrote is:
data = File.read("cert.pem")
data["-----BEGIN CERTIFICATE-----\n"]=""
data["-----END CERTIFICATE-----\n"]=""
OpenSSL::Digest::SHA1.new(Base64.encode64(data))
This code does not generate the same fingerprint as the openssl cli command does.
Any idea what I may be doing wrong?
As gtrig mentions, the OpenSSL command line builds the fingerprint by hashing the DER encoding of the certificate, not the Base64 PEM representation. You can parse this using pure OpenSSL:
file_data = File.read("cert.pem")
cert = OpenSSL::X509::Certificate.new(file_data)
puts OpenSSL::Digest::SHA1.new(cert.to_der).to_s
Shameless plug: r509 can also do this like so:
cert = R509::Cert.load_from_file("cert.pem")
puts cert.fingerprint('sha1')
If you need it to be in colon separated form you can just take the hash and do something like "fingerprint".scan(/../).map{ |s| s.upcase }.join(":")
Try Base64.decode64.
OpenSSL::Digest::SHA1.new(Base64.decode64(data))
Certificates in PEM format are Base 64 encoded versions of a binary DER format, so they need to be DEcoded before the SHA1 hash is taken.
Alternatively, you could convert the PEM file to DER format with OpenSSL like this:
openssl x509 -in cert.pem -out cert.der -outform der
Then your Ruby code would look like this:
data2 = File.read("cert.der")
print OpenSSL::Digest::SHA1.new(data2)
Either way works.

Digitally sign email in Ruby with S/MIME

Is there a way in Ruby to digitally sign email messages with S/MIME? Our group uses PKI and our users are conditioned to expect digital signatures for important messages.
I know I can invoke the openssl command line tool:
openssl smime -sign -signer $CERT_FILE -passin pass:$CERT_PASS
-in $UNSIGNED_MAIL -out $SIGNED_MAIL -certfile $CERT_CA_FILE
-from 'your ' -to 'recipients <email#address>'
-subject 'The Subject'
but I am hoping to utilize a Ruby solution.
I ended up using the above solution, but for those in a similar situation, you have to convert the PKI key (in .p12 file format) first: openssl pkcs12 -in #{#cert_file} -passin pass:#{#pass_phrase} -passout pass:#{#pass_phrase} -out #{out_file}

Resources