C# 无法使用我自己的 RSA 实现正确解密消息
C# can't properly decrypt message using my own RSA implementation
我正在尝试实现我自己的 RSA 实现。假设 public 键是:
BigInteger e = 5;
BiInteger n = 14;
私钥是:
BigInteger d = 11;
我想加密字符串 "B"
并稍后解密。问题是我的解密消息没有意义。这是我的功能。
public static void EncryptMessage(string message, BigInteger e, BigInteger n,BigInteger d)
{
byte[] ascii = System.Text.Encoding.ASCII.GetBytes(message);
var m = new BigInteger(ascii);
var c= Encrypt(m, e, n);
var cipherText = c.ToByteArray();
DecryptMessage(cipherText,d,n);
}
private static BigInteger Encrypt(BigInteger m ,BigInteger e, BigInteger n)
{
return BigInteger.ModPow(m, e, n);
}
public static void DecryptMessage(byte[] c,BigInteger d,BigInteger n)
{
var cipherText = new BigInteger(c);
Decrypt(cipherText,d,n);
}
private static void Decrypt(BigInteger c, BigInteger d, BigInteger n)
{
var decryptedNumber = BigInteger.ModPow(c, d, n);
var decryptedMessage = decryptedNumber.ToByteArray();
string S = Encoding.ASCII.GetString(decryptedMessage);
Console.WriteLine("Decrypted message: "+ S);
}
解密消息后,我将光标放在第二个新行中,但那里没有打印任何内容。没有性格,什么都没有。我认为这与从 bytes
转换为 BigInteger
和反之亦然有关,但我无法完成这项工作。
您的 n
14 太小,无法表示任何有用的值。 ASCII中的"B"字节值为66,所以解密时应该返回10(66mod14)或0x0A。使用更大的素数来加密更大的消息。
请记住,此 "textbook" RSA 不安全。您还需要实施填充方案,例如 OAEP 或 PKCS#1 v1.5 填充。
我正在尝试实现我自己的 RSA 实现。假设 public 键是:
BigInteger e = 5;
BiInteger n = 14;
私钥是:
BigInteger d = 11;
我想加密字符串 "B"
并稍后解密。问题是我的解密消息没有意义。这是我的功能。
public static void EncryptMessage(string message, BigInteger e, BigInteger n,BigInteger d)
{
byte[] ascii = System.Text.Encoding.ASCII.GetBytes(message);
var m = new BigInteger(ascii);
var c= Encrypt(m, e, n);
var cipherText = c.ToByteArray();
DecryptMessage(cipherText,d,n);
}
private static BigInteger Encrypt(BigInteger m ,BigInteger e, BigInteger n)
{
return BigInteger.ModPow(m, e, n);
}
public static void DecryptMessage(byte[] c,BigInteger d,BigInteger n)
{
var cipherText = new BigInteger(c);
Decrypt(cipherText,d,n);
}
private static void Decrypt(BigInteger c, BigInteger d, BigInteger n)
{
var decryptedNumber = BigInteger.ModPow(c, d, n);
var decryptedMessage = decryptedNumber.ToByteArray();
string S = Encoding.ASCII.GetString(decryptedMessage);
Console.WriteLine("Decrypted message: "+ S);
}
解密消息后,我将光标放在第二个新行中,但那里没有打印任何内容。没有性格,什么都没有。我认为这与从 bytes
转换为 BigInteger
和反之亦然有关,但我无法完成这项工作。
您的 n
14 太小,无法表示任何有用的值。 ASCII中的"B"字节值为66,所以解密时应该返回10(66mod14)或0x0A。使用更大的素数来加密更大的消息。
请记住,此 "textbook" RSA 不安全。您还需要实施填充方案,例如 OAEP 或 PKCS#1 v1.5 填充。