RSA非对称解密多出"\0"的求教!
超级路灯 2017-06-21 10:37:06 因为项目须要,客户端有两种方式,一个是WebForm 的,一个是WinForm.通信时要求通信数据RSA加密.
服务端生成一对密钥。
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters parameter = RSA.ExportParameters(false);
string privateKey = RSA.ToXmlString(true);
string publicKey = BytesToHexString(parameter.Exponent) + "," + BytesToHexString(parameter.Modulus);
Web端 加密码后,提交到服务端,解密正常
Win端 加密后,提交到服务端,解密结果多出了“\0”
比如,提交数据,"admin" 解密后为 "a\0d\0m\0i\0n\0"
web端加密参考的
http://www.cnblogs.com/csqb-511612371/p/4898437.html
winForm加密的代码
public static string EncryptByRSA(string plaintext, string publicKey)
{
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
{
RSAParameters rparam = new RSAParameters();
rparam.Exponent = HexStringToBytes(publicKey.Split(',')[0]);
rparam.Modulus = HexStringToBytes(publicKey.Split(',')[1]);
RSA.ImportParameters(rparam);
byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
return BytesToHexString(encryptedData);
}
}
统一用的解密:
public static string DecryptByRSA(string ciphertext, string privateKey)
{
string decryptData = "";
try
{
var provider = new RSACryptoServiceProvider();
provider.FromXmlString(privateKey);
ASCIIEncoding enc = new ASCIIEncoding();
byte[] result = provider.Decrypt(HexStringToBytes(ciphertext), false);
decryptData = enc.GetString(result);
}
catch (Exception e)
{
throw new Exception("RSA解密出错!", e);
}
return decryptData;
}
请哪位大神来指点下迷津!
补充: 如果win端return时,用Convert.ToBase64String(encryptedData); //encryptedData为加密后的bytes
解密的时候用RSA.Decrypt(Convert.FromBase64String(ciphertext), false); //ciphertext为加密后base64字符
解密正常,要求加密“admin”,解密后还是“admin”
估计是转换成16进制处出错,但查了好久都没有找个问题。望大神指点,