Can RSACryptoServiceProvider (.NET's RSA) use SHA256 for encryption (not signing) instead of SHA1?

前端 未结 6 1567
渐次进展
渐次进展 2020-12-15 08:11

When encrypting, can RSACryptoServiceProvider (or any other RSA encryptor available from .NET) use SHA256 instead of SHA1?

SHA1 appears to be hard coded with no way

6条回答
  •  轮回少年
    2020-12-15 08:59

    RSACryptoServiceProvider does work with SHA2-based signatures, but you have to invest some effort into it.

    When you use a certificate to get your RSACryptoServiceProvider it really matters what's the underlying CryptoAPI provider. By default, when you create a certificate with 'makecert', it's "RSA-FULL" which only supports SHA1 hashes for signature. You need the new "RSA-AES" one that supports SHA2.

    So, you can create your certificate with an additional option: -sp "Microsoft Enhanced RSA and AES Cryptographic Provider" (or an equivalent -sy 24) and then your code would look like (in .NET 4.0):

    var rsa = signerCertificate.PrivateKey as RSACryptoServiceProvider;
    //
    byte[] signature = rsa.SignData(data, CryptoConfig.CreateFromName("SHA256"));
    

    If you are unable to change the way your certificate is issued, there is a semi-ligitimate workaround that is based on the fact that by default RSACryptoServiceProvider is created with support for SHA2. So, the following code would also work, but it is a bit uglier: (what this code does is it creates a new RSACryptoServiceProvider and imports the keys from the one we got from the certificate)

    var rsa = signerCertificate.PrivateKey as RSACryptoServiceProvider;
    // Create a new RSACryptoServiceProvider
    RSACryptoServiceProvider rsaClear = new RSACryptoServiceProvider();
    // Export RSA parameters from 'rsa' and import them into 'rsaClear'
    rsaClear.ImportParameters(rsa.ExportParameters(true));
    byte[] signature = rsaClear.SignData(data, CryptoConfig.CreateFromName("SHA256"));
    

提交回复
热议问题