I need to make pksc # 7 signature for authorization in the ESIA system.
I have working code at times:
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", then I get the following: MIIFbAYJKoZIhvcNAQcCoIIFXTCCBVkCAQExDzANBglghkg ... IRmmg0beHTRwKd - 1857 characters
The result is the same every time .
I need to do the same thing in a different way (every time after restarting the server, I start to get An internal error occured)
I found the BouncyCastle and the CmsSignedDataGenerator class in it and wrote the following code:
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('/', '_'); } This code generates each time a different result like this:
MIAGCSqGSIb3DQEHAqCAMIACAQExDzANB ... egV70FgAAAAAAAA - 811 characters !
Both methods should generate a “detached pkcs7-signature message”, but BouncyCastle does something else.
SignedCms exactly works correctly (ESIA accepts the signature), but CmsSignedDataGenerator does not.
What do I need to change in the version with BouncyCastle to get the correct signature?
SignedCms - https://msdn.microsoft.com/en-us/library/8412wc31%28v=vs.110%29.aspx?f=255&MSPPE rror=-2147217396
CMSSignedDataGenerator - https://www.bouncycastle.org/docs/pkixdocs1.5on/org/bouncycastle/cms/CMSSignedDataGenerator.html
I look at the class descriptions and I do not see a fundamental difference!