Sign file using .NET OpenSSL wrapper

久未见 提交于 2019-12-11 02:07:35

问题


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:


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.



来源:https://stackoverflow.com/questions/21849460/sign-file-using-net-openssl-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!