openssl smime in ruby/rails

2020-07-26 11:04发布

问题:

So, i have this application that creates a zip file with images and stuff

and i want to sign it using smime.

if i use the terminal command:

openssl smime -binary -sign -passin "pass:MYPASS" -signer ./MyCertificate.pem -inkey ./MyKey.pem -in ./manifest.in -out ./signature.out -outform DER

Formated:

openssl smime -binary -sign -passin "pass:MYPASS"             \
         -signer ./MyCertificate.pem -inkey ./MyKey.pem       \
         -in ./manifest.in -out ./signature.out -outform DER

the manifest.in is the file witch contains the text to be signed and signature.out is the output file.

i don't know a lot about signing but i believe this code is signing my file using PKCS7

how can i recreate the same result with ruby/rails?

i have tried to look in the documentation of OpenSSL but i couldn't find anything usefull for me

EDIT

if this helps someone, this is what the documentation says

i need to build a:

A detached PKCS#7 signature of the manifest

回答1:

Found a way.

like this:

  require 'secure_digest'

  def sign_manifest(manifest = {})
    manifest_str = manifest.to_json

    key4_pem = File.read Rails.root.join("lib", "keys", "key.pem")
    pass_phrase = "supera"

    key = OpenSSL::PKey::RSA.new key4_pem, pass_phrase
    cert = OpenSSL::X509::Certificate.new File.read Rails.root.join("lib", "keys", "certificate.pem")

    sign = OpenSSL::PKCS7.sign(cert, key, manifest_str, nil, OpenSSL::PKCS7::BINARY | OpenSSL::PKCS7::NOATTR | OpenSSL::PKCS7::DETACHED).to_der

    sign
  end

Just to clarify my code, manifest param is a hash witch i want to sign it using this code. if i want another item, like a image, string or file i just need do read it as string