C#无法使用我自己的RSA实现正确解密消息

时间:2015-11-29 20:28:25

标签: c# arrays encoding bytearray rsa

我正在尝试实现自己的RSA实现。我们说公钥是:

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反之亦然,但我无法做到这一点。

1 个答案:

答案 0 :(得分:1)

您的n 14太小,无法代表任何有用的值。 ASCII中的“B”的字节值为66.因此,当您解密它时,应该返回10(66 mod 14)或0x0A。使用更大的素数来加密更大的消息。

请记住,这个“教科书”RSA并不安全。您还需要实现填充方案,例如OAEP或PKCS#1 v1.5填充。