C#实现SHA256WithRSA加密用于Java的秘钥私钥
首先要把Java秘钥进行转换,然后再进行加密
转制秘钥的方法
public static string RSAPrivateKeyJava2DotNet(string privateKey) { RsaPrivateCrtKeyParameters privateKeyParam = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(privateKey)); return string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>", Convert.ToBase64String(privateKeyParam.Modulus.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.PublicExponent.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.P.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.Q.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.DP.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.DQ.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.QInv.ToByteArrayUnsigned()), Convert.ToBase64String(privateKeyParam.Exponent.ToByteArrayUnsigned())); }
加密的方法
public static string Sign(string contentForSign, string privateKey) { //转换成适用于.Net的秘钥 var netKey = RSAPrivateKeyJava2DotNet(privateKey); var rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(netKey); //创建一个空对象 var rsaClear = new RSACryptoServiceProvider(); var paras = rsa.ExportParameters(true); rsaClear.ImportParameters(paras); //签名返回 using (var sha256 = new SHA256CryptoServiceProvider()) { var signData = rsa.SignData(Encoding.UTF8.GetBytes(contentForSign), sha256); return BytesToHex(signData); } } public static string BytesToHex(byte[] data) { StringBuilder sbRet = new StringBuilder(data.Length * 2); for (int i = 0; i < data.Length; i++) { sbRet.Append(Convert.ToString(data[i], 16).PadLeft(2, '0')); } return sbRet.ToString(); }
调用:
string rsaSecret = @"MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAjdAhDuqzKCzaYyrrxFLdWVoR7wwmSdbVHBSZ/lpILvN/vPaohbi0NChwAEXYbvIXrFQ7zQyuqKazoEbvvXRNKQ......."; string signDataString = Sign("Hello World!", rsaSecret);