Ruby OpenSSL, print issuer and subject of pem file - ruby

How do I print (or save to variable) the Issuer and Subject from a .pem certificate using the OpenSSL module ?
(This is after trying to understand the ruby-docs)

I used this System-depended and ugly code, but I'm sure there is a much nicer thing to do
pfxsubject = %x(openssl x509 -in '/root/cert.pem' -noout -subject | cut -c 10-).to_s.chomp

Related

ruby openssl smime encryption

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

Dart HTTP Server and importing a SSL Certificate

I have create a Dart HTTP(s) server for deploying files. I can have it run the https with a self signed cert. But how do you import a .crt properly from someone for example GoDaddy properly?
So after a long struggle I have finally succeeded in importing a certificate from GoDaddy properly into Darts HttpServer bindSecure.
In order to pull this off, first you must merge your key and the certificate from GoDaddy together.
This can be done using a variation of this:
openssl pkcs12 -export -in website_cert.crt -inkey website_key.key -out website.p12 -name Name-Of-Cert -passout pass:SECRET
After...
pk12util -i website.p12 -d 'sql:./' -W SECRET
You should now see the cert with the Name-Of-Cert value, (If you have a password on the db, apply the appropriate flags)
certutil -L -d 'sql:./'
Now, verify
certutil -V -u V -d 'sql:./' -n "Name-Of-Cert"
Credit to: https://stomp.colorado.edu/blog/blog/2010/06/04/on-setting-up-mod_nss/

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.

How to specify passphrases for P12 to PEM file conversion without interaction.

I'm trying to convert a P12 file to a PEM file. When I execute the command, the terminal asks me for three things:
P12 passphrase (I type it in, hit enter)
PEM passphrase (type it in, hit enter)
PEM passphrase confirm (type it in, hit enter)
I know I can execute a sudo command all in one shot by using the following:
echo sudopassword | sudo rm -rf /file.p12;
How can I add all three values in one shot? Thanks
Can you explain what these P12 files are? I found this link which deals with the conversion of pkcs12 Cert/key files to .PEM format using openssl. (http://gridsite.org)
Key to the answer is:
Use -passin file:... and -passout file:... for unattended processing
It's my guess that you will have to specify the -passin file:P12passphrase and -passout file PEMpassphrase options for this case.
This little test confirms how an input passphrase can be specified through a file:<...> parameter. This helps to hide such phrases from any over the shoulder attacks. Don't forget to restrict access to such files. Even though it's a common feature of most openssl commands, it's not explicitly mentioned and it is key to the original question. The full list of options is below.
$ openssl pkcs12 -passin file:P12phrase
Can't open file P12phrase
Error getting passwords
(I leave it to the OP to construct the full command.)
Below are all supported options for the pkcs12 subcommand:
$ openssl pkcs12 help
Usage: pkcs12 [options]
where options are
-export output PKCS12 file
-chain add certificate chain
-inkey file private key if not infile
-certfile f add all certs in f
-CApath arg - PEM format directory of CA's
-CAfile arg - PEM format file of CA's
-name "name" use name as friendly name
-caname "nm" use nm as CA friendly name (can be used more than once).
-in infile input filename
-out outfile output filename
-noout don't output anything, just verify.
-nomacver don't verify MAC.
-nocerts don't output certificates.
-clcerts only output client certificates.
-cacerts only output CA certificates.
-nokeys don't output private keys.
-info give info about PKCS#12 structure.
-des encrypt private keys with DES
-des3 encrypt private keys with triple DES (default)
-aes128, -aes192, -aes256
encrypt PEM output with cbc aes
-nodes don't encrypt private keys
-noiter don't use encryption iteration
-maciter use MAC iteration
-twopass separate MAC, encryption passwords
-descert encrypt PKCS#12 certificates with triple DES (default RC2-40)
-certpbe alg specify certificate PBE algorithm (default RC2-40)
-keypbe alg specify private key PBE algorithm (default 3DES)
-keyex set MS key exchange type
-keysig set MS key signature type
-password p set import/export password source
-passin p input file pass phrase source
-passout p output file pass phrase source
-engine e use engine e, possibly a hardware device.
-rand file:file:...
load the file (or the files in the directory) into
the random number generator
-CSP name Microsoft CSP name
-LMK Add local machine keyset attribute to private key
It's unlikely that these commands are reading from stdin. It's more likely that they're reading directly from the terminal. This allows them to set a mode that doesn't echo the password to the screen. Try echoing your input to /dev/tty.
Beyond that, you'll need to use something like expect / pexect to control these. Those projects were build specifically for this purpose.
Openssl has a -stdin optoin to read its input from stdin. This works:
tmp=`mktemp`
cat > $tmp <<EOF
$1
EOF
cat $tmp | openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key
I've used cat and a here-document to avoid putting the password on the commandline.
I used openssl pkcs12 -in Certificates.p12 -out sampleCore.pem -nodes and it was working for me.
Have you tried just echoing three lines? It would probably work
echo $'P12 passphrase\nPEM passphrase\nPEM passphrase confirm' | cmd
Although I feel I must point out that echoing passwords like this is highly insecure. Not only does the password end up in your bash history file, but it's also visible to anyone else on the system who runs ps.

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