So, my situation is similar with this title: Sign data with MD5WithRSA from .Pem/.Pkcs8 keyfile in C# I need to use PKCS8EncodedKeySpec and generate a sign data using SHA1withRSA.
Firstly, i had a sample code in Java and I had to convert it to C#. However, the link above had a solution for C#. And all i have to do is just to install the Security.Cryptography.Cng package. But the problem is that my solutions target NETFramework Version v4.5.2, which the Security.Cryptography package does not contain any assembly reference for it.
Is there any other way for me to convert the following sample code to C# without having to change my solution target framework version? Appreciate the help.
Sign function in java code
public static String sign(String info, String priKey) {
try {
byte[] keyBytes = Base64.decode(priKey);
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyf = KeyFactory.getInstance("RSA");
PrivateKey myprikey = keyf.generatePrivate(priPKCS8);
Signature signet = Signature.getInstance("SHA1withRSA");
signet.initSign(myprikey);
byte[] infoByte = info.getBytes("UTF-8");
signet.update(infoByte);
byte[] signed = signet.sign();
String sign = Base64.encode(signed);
System.out.println("sign = " + sign);
return sign;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Sign function in C# code
private AsymmetricKeyParameter CreateKEY(bool isPrivate, string key)
{
byte[] keyInfoByte = Convert.FromBase64String(key);
if (isPrivate)
return PrivateKeyFactory.CreateKey(keyInfoByte);
else
return PublicKeyFactory.CreateKey(keyInfoByte);
}
public string Sign(string content, string privatekey)
{
ISigner sig = SignerUtilities.GetSigner("SHA1withRSA");
sig.Init(true, CreateKEY(true, privatekey));
var bytes = Encoding.UTF8.GetBytes(content);
sig.BlockUpdate(bytes, 0, bytes.Length);
byte[] signature = sig.GenerateSignature();
/* Base 64 encode the sig so its 8-bit clean */
var signedString = Convert.ToBase64String(signature);
return signedString;
}
My Sign function stops when running PrivateKeyFactory.CreateKey(keyInfoByte). There is an error message of Unable to cast object of type 'Org.BouncyCastle.Asn1.DerSequence' to type 'Org.BouncyCastle.Asn1.DerInteger'.