如何使用Ruby OpenSSL库解码/提取SMIME签名电子邮件的smime.p7m文件内容

时间:2011-09-07 11:12:08

标签: ruby openssl signed smime

我有一个签名的电子邮件消息作为字符串。我希望得到带有附件和整体的无符号消息的字符串,我可以解析它,例如,Mail gem。

我发现问题:Decode/extract smime.p7m file contents (email with embedded files) with OpenSSL?现在我知道如何通过命令行来完成。

我可以将我的字符串转储到临时文件,通过命令行解密然后解析它。但这不是一个好主意。我想为Ruby使用OpenSSL库。

1 个答案:

答案 0 :(得分:0)

我认为我会写出一个解决方案,因为这花了我很多时间才能解决。另请参阅我的评论,该评论来自何处:

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))