7

I need make pksc#7 signature. It's my working (time to time) code with SignedCms:

public static string SignSignedCms(string data)
{
    byte[] bData = Encoding.UTF8.GetBytes(data);

    X509Certificate2 certificate = new X509Certificate2();

    certificate.Import(@"D:\...file.pfx", "pwd", X509KeyStorageFlags.DefaultKeySet);

    ContentInfo content = new ContentInfo(bData);
    SignedCms signedCms = new SignedCms(content);

    CmsSigner signer = new CmsSigner(certificate);
    signer.DigestAlgorithm = new Oid("SHA256");

    signedCms.ComputeSignature(signer, true);
    return Convert.ToBase64String(signedCms.Encode()).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}

if data="asdfghjkl" result is: MIIFbAYJKoZIhvcNAQcCoIIFXTCCBVkCAQExDzANBglghkg...IRmmg0beHTRwKd - 1857 sybols

In this case I have same result every time.

Now I need different way for making same thing (why? - it's other question)

I found BouncyCastle CmsSignedDataGenerator and I have this:

public static string SignBouncyCastle(string data)
{
    byte[] bData = Encoding.UTF8.GetBytes(data);

    X509Certificate2 certificate = new X509Certificate2();

    certificate.Import(@"D:\...file.pfx", "pwd", 509KeyStorageFlags.Exportable);

    AsymmetricKeyParameter key = DotNetUtilities.GetKeyPair(certificate.PrivateKey).Private;

    CmsSignedDataGenerator gen = new CmsSignedDataGenerator();

    gen.AddSigner(key, DotNetUtilities.FromX509Certificate(certificate), CmsSignedGenerator.DigestSha256);

    CmsSignedData cmsSignedData = gen.Generate(new CmsProcessableByteArray(bData));

    return Convert.ToBase64String(cmsSignedData.GetEncoded()).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}

In this case (data="asdfghjkl") I always have different results, something like this: MIAGCSqGSIb3DQEHAqCAMIACAQExDzANB...egV70FgAAAAAAAA - 811 symbols!

Both methods should make "detached pkcs7-signature message", but BouncyCastle makes something different.

I'm sure that SignedCms makes right signature, but I can't use it.

What should I change in my second method to have the same result like in SignedCms?

SignedCms - https://msdn.microsoft.com/en-us/library/8412wc31%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396

CMSSignedDataGenerator - https://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/cms/CMSSignedDataGenerator.html

I don't see difference!

  • Did you solve it? Same problem here. – Gonzalo Gallotti Jan 23 '18 at 19:22
  • 1
    Hello! I couldn't use X509Certificate2, because of "An unhandled exception is occured" which happend time to time. It was because of I set up my certificate to wrong place. After adding sertificate to correct place it (X509Certificate2) started working without any complaints. Problem with sertificate was found by system administrator, he noticed wrong exclamation sign in certificate description. – Alexandr Evstafiev Jan 25 '18 at 09:07

0 Answers0