這是我的代碼,仍然有一些缺陷,但在大多數情況下工作。 我通過Java獲得modulusString
。
public static string Decrypt(string text, string modulusString)
{
var modulus = BigInteger.Parse(modulusString);
var exponent = BigInteger.Parse("65537");
var encryptBytes = Convert.FromBase64String(text);
if (publicKey.Modulus.Length > 309) // long enough key to decrypt short message
{
return Decrypt(encryptBytes, exponent, modulus);
}
string result = string.Empty;
int i = 0;
while (i < encryptBytes.Length) // for short key, must decrypt section-by-section
{
var temp = new byte[Math.Min(encryptBytes.Length, 128)];
Array.Copy(encryptBytes, i, temp, 0, temp.Length);
result += Decrypt(temp, exponent, modulus);
i += 128;
}
return result;
}
private static string Decrypt(byte[] encryptBytes, BigInteger exponent, BigInteger modulus)
{
Array.Reverse(encryptBytes); // BigIntenger need little-endian
if ((encryptBytes[encryptBytes.Length - 1] & 0x80) > 0) // make positive
{
var temp = new byte[encryptBytes.Length];
Array.Copy(encryptBytes, temp, encryptBytes.Length);
encryptBytes = new byte[temp.Length + 1];
Array.Copy(temp, encryptBytes, temp.Length);
}
var value = new BigInteger(encryptBytes);
var result = BigInteger.ModPow(value, exponent, modulus);
byte[] resultBytes = result.ToByteArray();
Array.Reverse(resultBytes);
int index = Array.FindIndex(resultBytes, b => b == 0) + 1;
return Encoding.UTF8.GetString(resultBytes, index, resultBytes.Length - index);
}
我假設你檢查了這一點完全http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx – Venki 2011-03-14 18:11:23