how to sign the message with the private key of the signer using openssl command line tool to get the same result as the code below?

using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

static public byte[] SignMe(X509Certificate2 rsa_cert, Byte[] message)
    ContentInfo ci = new ContentInfo(message);
    SignedCms scms = new SignedCms(ci, true);
    CmsSigner signer = new CmsSigner(rsa_cert);
    scms.ComputeSignature(signer, false);
    return Convert.ToBase64String(scms.Encode());

The following should perform the same effect for you, where rsa_cert_private.key is the private key in your keypair, and sign.txt is the message you wish to sign. The result will be a new file sign.txt.sha256 that is the signature based upon the sha256 digest of the original message.

openssl dgst -sha256 -sign rsa_cert_private.key" -out sign.txt.sha256 sign.txt

but at this point the signature is in binary form, to get that over to base64 you'll then want to

base64 sign.txt.sha256 > sign.txt.sha256.txt

which will create a 2nd new file (sign.txt.sha256.txt) that is the exact same signature content but in b64.

To verify the signature you would first need to get it back into a binary sig

base64 -d sign.txt.sha256.txt > sign.txt.sha256

but it is easier just to leave it in binary the whole time instead of taking the extra steps and (admittedly minuscule) extra space to store it in base64.

  • 1
    I wouldn't call a 33% size increase "minuscule". I also expect this is likely wrong, and OP will want to use openssl cms. – AndrolGenhald Jan 15 '19 at 22:29
  • @AndrolGenhald+ noting that cms defaults to SMIME format (!) and you need to specify -outform der or -outform pem for actual CMS -- and neither of those is quite the same as the Q's base64-of-DER. (PEM includes base64-of-DER, but is not identical to it.) – dave_thompson_085 Jan 16 '19 at 3:41
  • Considering that a SHA-256 hash is 256 bits in size then that extra is pretty miniscule. Heck, depending on your file system's block size there is a strong chance they're both 1-block files (in which case I guess it doesn't matter). Androl & Dave also point out a difference in my reading of the question. If you are asking for "same result" to mean "same effect" then this works. If you are asking for "same result" to mean "identical bits returned by SignMe() and OpenSSL" then this isn't the right answer. In which case I'd ask for clarity on which way you're leaning with your question. – Ruscal Jan 16 '19 at 14:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.