I get an error when trying to sign data with .NET Core using CMS with certificate
X509Store st = new X509Store(StoreName.My, StoreLocation.LocalMachine);
st.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certSelected = st.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
st.Close();
var signerCert = certSelected[0];
ContentInfo contentInfo = new ContentInfo(msg);
SignedCms signedCms = new SignedCms(contentInfo, true);
CmsSigner cmsSigner = new CmsSigner(signerCert);
cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;
signedCms.ComputeSignature(cmsSigner, false);
I get the error below when computing the signature
Error occurred during a cryptographic operation.
at Internal.Cryptography.Pal.Windows.HelpersWindows.GetProvParameters(SafeProvOrNCryptKeyHandle handle)
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKey[T](X509Certificate2 certificate, Boolean silent, Boolean preferNCrypt)
at Internal.Cryptography.Pal.Windows.PkcsPalWindows.GetPrivateKeyForSigning[T](X509Certificate2 certificate, Boolean silent)
at System.Security.Cryptography.Pkcs.CmsSignature.RSAPkcs1CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, String& signatureAlgorithm, Byte[]& signatureValue)
at System.Security.Cryptography.Pkcs.CmsSignature.Sign(ReadOnlySpan`1 dataHash, HashAlgorithmName hashAlgorithmName, X509Certificate2 certificate, AsymmetricAlgorithm key, Boolean silent, String& oid, ReadOnlyMemory`1& signatureValue)
at System.Security.Cryptography.Pkcs.CmsSigner.Sign(ReadOnlyMemory`1 data, String contentTypeOid, Boolean silent, X509Certificate2Collection& chainCerts)
at System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature(CmsSigner signer, Boolean silent)
The same code works in .NET Framework 4.5.2
Any idea what could be wrong here and how to fix it in .NET Core?
I've managed to get this working by:
New code below with the changes
X509Store st = new X509Store(StoreName.My, StoreLocation.LocalMachine);
st.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certSelected = st.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
st.Close();
var signerCert = certSelected[0];
Oid dstOid = new Oid("1.2.840.113549.1.7.2"); // PKCS#7
ContentInfo contentInfo = new ContentInfo(dstOid, msg);
SignedCms signedCms = new SignedCms(contentInfo, true);
CmsSigner signerWindowStore = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signerCert, signerCert.GetRSAPrivateKey());
signerWindowStore.DigestAlgorithm = new Oid("1.3.14.3.2.26"); // SHA1
signerWindowStore.IncludeOption = X509IncludeOption.EndCertOnly;
signedCms.ComputeSignature(signerWindowStore, false);