I've been since yesterday trying a lot of the "solutions" on StackOverflow, but none seems to work. Given a .pfx certificate with a private key I need to sign a byte array (firmware version of the tracking unit we use). Here are the things I've tried:
private byte[] generateSignature(byte[] data, X509Certificate2 certificate)
{
RSACryptoServiceProvider key = new RSACryptoServiceProvider();
key.FromXmlString(certificate.PrivateKey.ToXmlString(true));
return key.SignData(data, CryptoConfig.MapNameToOID("SHA256"));
}
And also:
private byte[] generateSignature(byte[] data, X509Certificate2 certificate)
{
string alg = CryptoConfig.MapNameToOID("SHA256");
RSACryptoServiceProvider rsaProvider = (RSACryptoServiceProvider)certificate.PrivateKey;
return rsaProvider.SignData(orig, alg);
}
And also:
private byte[] generateSignature(byte[] data, X509Certificate2 certificate)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
byte[] hash;
using (SHA256 sha256 = SHA256.Create())
{
hash = sha256.ComputeHash(data);
}
RSAPKCS1SignatureFormatter RSAFormatter = new RSAPKCS1SignatureFormatter(rsa);
RSAFormatter.SetKey(certificate.PrivateKey);
RSAFormatter.SetHashAlgorithm("SHA256");
return RSAFormatter.CreateSignature(hash);
}
And finally:
private byte[] generateSignature(byte[] data, X509Certificate2 certificate)
{
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)certificate.PrivateKey;
SHA1Managed sha1 = new SHA1Managed();
SHA256Managed sha256 = new SHA256Managed();
byte[] hash = sha256.ComputeHash(data);
csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA256"));
}
On all of these I get the error:
System.Security.Cryptography.CryptographicException: 'Invalid algorithm specified.'
I know my key is 256hash compatible because I've used the command:
openssl x509 -in C:\cert.pfx -text -noout
And the Signature Algorithm was sha256WithRSAEncryption.