Search code examples
c#.netcryptographysignrsacryptoserviceprovider

.net RSA sign data error with PSS padding


I have a question re. the use of Crypto in .net as follows. I have a .pem file which I am able to parse to a private key and would like to sign some data bytes. The code I'm using is below:

byte[] pemkey = Convert.FromBase64String(privateKeyString);

RSACryptoServiceProvider RSA = DecodeRSAPrivateKey(pemkey);//function to parse .pem file

byte[] fileBytes = File.ReadAllBytes(@"C:\...");

byte[] signature = RSA.SignData(fileBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);

When running this, at the last statement (RSA.SignData), I've got an exception CryptographicException is not handled: Specified padding mode is not valid for this algorithm.

I'm not sure what is missing from my code as my search on Google did not return much result.

Any help is appreciated. Many thanks


Solution

  • I have never seen PSS padding working with RSACryptoServiceProvider but I have seen it working fine with RSACng. You can try it quickly with following modification of your code:

    byte[] pemkey = Convert.FromBase64String(privateKeyString);
    
    RSACryptoServiceProvider RSA = DecodeRSAPrivateKey(pemkey);//function to parse .pem file
    
    RSAParameters rsaParams = RSA.ExportParameters(true);
    RSACng RSACng = new RSACng();
    RSACng.ImportParameters(rsaParams);
    
    byte[] fileBytes = File.ReadAllBytes(@"C:\...");
    
    byte[] signature = RSACng.SignData(fileBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pss);