How to Decode/extract smime.p7m file contents of SMIME signed email using Ruby OpenSSL library

petRUShka picture petRUShka · Sep 7, 2011 · Viewed 11.7k times · Source

I have a signed email message as string. And I want to get string with whole unsigned message with attachments and body that I can parse with, for example, Mail gem.

I found question: Decode/extract smime.p7m file contents (email with embedded files) with OpenSSL? and now I know how to do it via command line.

I can dump my string to temp file, decrypt via command line and then parse it. But this is not so good idea. I want to use OpenSSL library for Ruby.

Answer

herrherr picture herrherr · Aug 24, 2018

I thought I'd write up a solution, because it took me quite some time to figure this out. Also see my comment above on where this was taken from:

include OpenSSL

# assuming that mail contains the message that you have likely fetched with the mail gem
data = mail.to_s

# load your certificate and key
# if you need to convert from a .p12 file for example 
# check this https://stackoverflow.com/questions/13732826/convert-pem-to-crt-and-key
cert = X509::Certificate.new(File::read("your_cert.cer"))
key = PKey::RSA.new(File::read("your.key"))

# load the encrypted mail
p7enc = PKCS7::read_smime(data)

# this is the plain email that you can read back into the mail gem and extract the required data
Mail.read_from_string(p7enc.decrypt(key, cert))