在使用C#的不对称加密
RSACryptoServiceProvider
类的时候,会遇到异常:System.Security.Cryptography.CryptographicException: The data to be decrypted exceeds the maximum for this modulus of 128 bytes.
异常详细信息: System.Security.Cryptography.CryptographicException: 要解密的数据超过此模块的最大值 128 字节。
错误发生在
rsa.Decrypt
这一行。通常不对称加密的过程:1. A端数据用公钥加密,通过网络传输 2. B端用私钥解密这些数据。但.net中的rsa加密最多只能对117字节数据进行操作(128位减去随机数),导致128位数据不得不分两部分进行处理,于是加密数据不断膨胀。更多详细讨论参考
StackOverflow这
个帖子。
解决办法
在CodeProject上有一篇 文章 , 可以很好的解决这个问题,先下载BigInteger class。
{
/// <summary>
/// RSAs the encrypt.
/// </summary>
/// <param name="datatoencrypt"> The datatoencrypt. </param>
/// <param name="exponent"> The exponent. </param>
/// <param name="modulus"> The modulus. </param>
/// <returns></returns>
public static byte [] RsaEncrypt( byte [] datatoencrypt, byte [] exponent, byte [] modulus)
{
var original = new BigInteger(datatoencrypt);
var e = new BigInteger(exponent);
var n = new BigInteger(modulus);
var encrypted = original.modPow(e, n);
return HexstringTobyte(encrypted.ToHexString());
}
/// <summary>
/// RSAs the decrypt.
/// </summary>
/// <param name="encrypteddata"> The encrypteddata. </param>
/// <param name="d"> The d. </param>
/// <param name="modulus"> The modulus. </param>
/// <returns></returns>
public static byte [] RsaDecrypt( byte [] encrypteddata, byte [] d, byte [] modulus)
{
var encrypted = new BigInteger(encrypteddata);
var dd = new BigInteger(d);
var n = new BigInteger(modulus);
var decrypted = encrypted.modPow(dd, n);
return HexstringTobyte(decrypted.ToHexString());
}
/// <summary>
/// Generate random bytes with given length
/// </summary>
/// <param name="bytelength"></param>
/// <returns></returns>
public static byte [] GenerateRandomBytes( int bytelength)
{
var buff = new byte [bytelength];
var rng = new RNGCryptoServiceProvider();
rng.GetBytes(buff);
return buff;
}
}
var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(_publicKey /* Type: RSAParameters */ );
byte [] encryptedData = RSAHelper.RsaEncrypt(Encoding.Unicode.GetBytes(stringDataToEncrypt /* Type: string */ ), data.parameters.Exponent, data.parameters.Modulus);
return Convert.ToBase64String(encryptedData);
var rsa = new RSACryptoServiceProvider();
// Import private key
rsa.ImportParameters(_privateKey /* Type: RSAParameters */ );
byte [] encryptedData = RSAHelper.RsaDecrypt(Convert.FromBase64String(encryptedBase64String /* Type: string, but base64 format */ ), _privateKey.D, _privateKey.Modulus);
return Encoding.Unicode.GetString(encryptedData);
更多讨论