Requirement: I am developing a service that calls an API which has a parameter named token. Token message needs to be signed using digital certificate .pfx file. The digital signature algorithm will be SHA256withRSA, then convert the signed token to base64 encoding and at last pass the signature string to the token field of request message.
Issue : In my console/service application code, it throws an error at line 7: Unable to cast object of type System.Security.Cryptography.RSACng to type System.Security.Cryptography.RSACryptoServiceProvider
public string HBLTxnToken()
{
string contentToEncode = "HBL -531,0701,1,01900099870014,1,NPR,HBL-531,2101,1,0830122854100011,1,HBL@999";
X509Certificate2 certificate = new X509Certificate2(@"C://Users//nabinpr//Desktop//Code//Test File//HBL.pfx", "123"); //first parameter is path of certificate and second is password.
if (certificate.HasPrivateKey)
{
RSACryptoServiceProvider privateKey = (RSACryptoServiceProvider)certificate.PrivateKey; // Error : System.InvalidCastException: 'Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.'
byte[] utf8Data = Encoding.UTF8.GetBytes(contentToEncode);
byte[] signature = privateKey.SignData(utf8Data, "sha256");
return Convert.ToBase64String(signature);
}
else
{
return "0";
}
}
I have been stuck in this from two days, I am getting different token value, valid token is given below. If the token generated from my code matched with below value then we can assume its correct. seek experts help.
Resulting token value should be : LmvlZkZW1K/DPtBZ0d9UIVwByXVPWoApOZsnJFfLw+pD+5Fknt+t9aNkaNUjcNlYdctyTwr+EZ/ZI7IXPr/UQQVinZHiLowHqn9TykRWlDRSQLdoOrYxEMVApk7EzbT49s77FW2WX1IJV7L/Xmti5PZxjkedfDcHBVATyxjH/IE=