tags:

views:

77

answers:

1

Hi everyone,

For an application I'm developing I need to create a signature file before I can upload files. The documentation of it explains how to do this with openssl:

First you need to prepare your key:

$ openssl pkcs12 -in certificate.pfx -passin pass:xxxxxxxxxx -out pem -clcerts -nokeys
$ openssl pkcs12 -in certificate.pfx -passin pass:xxxxxxxxxx -passout pass:xxxxxx -out key

After which you can sign any file using the following syntax:

$ openssl smime -sign -in inputfile -signer pem -inkey key -passin pass:xxxxxx -outform PEM -out signaturefile

This works, but I'd rather avoid having to run an external program just to create signature files if it's possible to do it with native .NET code.

I've tried to code this in vb.net and got the following:

Public Shared Sub SignFile(ByVal theFilename As String, ByVal theCertFile As String, ByVal thePassword As String, ByVal theDestination As String)
    Dim aCertificate = New X509Certificates.X509Certificate2(theCertFile, thePassword)
    Dim aByteArray = IO.File.ReadAllBytes(theFilename)
    Dim anOid = New System.Security.Cryptography.Oid("1.2.840.113549.1.7.2")
    Dim aContentInfo = New Pkcs.ContentInfo(anOid, aByteArray)
    Dim aSignedCms = New Pkcs.SignedCms(aContentInfo, True)
    Dim aCmsSigner = New Pkcs.CmsSigner(Pkcs.SubjectIdentifierType.IssuerAndSerialNumber, aCertificate)

    aSignedCms.ComputeSignature(aCmsSigner)
    Dim aSignature = Convert.ToBase64String(aSignedCms.Encode())
    IO.File.WriteAllText(theDestination, Convert.ToBase64String(anOutput.ToArray()))
End Sub

The file it makes isn't exactly what openssl expects: I still need to insert the -----BEGIN PKCS7----- and -----END PKCS7----- and add in line breaks so that lines aren't longer than 65 characters. But, even after doing that, the signature I made this way isn't valid, when I check with openssl I get the following error:

5768:error:21071065:PKCS7 routines:PKCS7_signatureVerify:digest failure:.\crypto\pkcs7\pk7_doit.c:1051:
5768:error:21075069:PKCS7 routines:PKCS7_verify:signature failure:.\crypto\pkcs7\pk7_smime.c:410:

I think I'm forgetting a small detail somewhere, but I can't just figure out what.

Can anyone help me out make that code work? And if not, point to a .NET library that has such functionality with possibly an example of how to do it?

A: 

What exact line breaks do you add? CRLF or just LF?

I have similar problem verifying smime message. And I find the cause. OpenSSL changes line breaks to CRLF (my message use only LF) so content become different from original and digest check fails. May be it is you case too? Unfortunately I can't find solution.

Donz
I've found the problem I had now: was something similar to this. I didn't specify the encoding when I read the file. If I use ASCII encoding then it works.