2
votes

I was trying to copy this line

openssl smime -sign -signer <chain_crt_file> -in <infile> -out <outfile> -inkey <privatekey> -outform der

into C# However it didn't turn out to be as easy as I thought. So far I came only this point

OpenSSL.Core.BIO crtBio = OpenSSL.Core.BIO.File("C:/asl/chain.crt", "r");
OpenSSL.Core.BIO keyBio = OpenSSL.Core.BIO.File("C:/asl/keydec.txt", "r");
OpenSSL.X509.X509Chain crt = new OpenSSL.X509.X509Chain(crtBio);
OpenSSL.Crypto.RSA key = OpenSSL.Crypto.RSA.FromPrivateKey(keyBio);

String str = "test";
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);

Where (hopefully) I'm importing chain certificate and decoded private key. Now the thing is how to sign a file and export is as DER. OpenSSL.NET wrapper lacks documentation and examples I found on the internet are 'how to encrypt and decrypt messages using public/private key' which is not a case here.

To get started I tried to sign this "test" string (as file in/out should be pretty straightfoward) but I have no clue where to start.

The thing is that I need to sign this string thus I will need both key and certificates chain.

Thanks a lot for your help.

1
Is OpenSSL wrapper required? You can sign any data using x509 cert with private key and SignedCms .Net class Have you read "7.12 Signing Data Using an RSA Private Key" on etutorials.org ?oleksa
Thank you for the reference. Apparently wrapper was no needed as I followed your suggestion and used PKCS12 file as this is fully supported by .NET Cryptography class. Solution I found is pretty easy, stackoverflow.com/questions/11526572/…Mike

1 Answers

0
votes

To get started I tried to sign this "test" string (as file in/out should be pretty straightfoward) but I have no clue where to start.

The OpenSSL source is probably a good place to start. OpenSSL provides the source for smime in <openssl dir>/apps/smime.c.

OpenSSL's smime utility just calls PKCS7_sign with the appropriate parameters. From around line 688:

else if (operation & SMIME_SIGNERS)
    {
    int i;
    /* If detached data content we only enable streaming if
     * S/MIME output format.
     */
    if (operation == SMIME_SIGN)
        {
        if (flags & PKCS7_DETACHED)
            {
            if (outformat == FORMAT_SMIME)
                flags |= PKCS7_STREAM;
            }
            else if (indef)
                flags |= PKCS7_STREAM;

           flags |= PKCS7_PARTIAL;
           p7 = PKCS7_sign(NULL, NULL, other, in, flags);
           if (!p7)
               goto end;
        }
        ...

With knowledge of PKCS7_sign, you can visit OpenSSL's docs at PKCS7_sign(3). Or, you can hunt for an example.

I don't know about the wrapper you are using.