【问题标题】:RSA algorithm implementation not working properly in javaRSA算法实现在java中无法正常工作
【发布时间】:2014-06-17 14:02:01
【问题描述】:

理论上我知道如果n=33e(public key)=3d(private key)=7 我可以使用BigInteger 类和modPow(e, n) 加密plaintext,并使用modPow(d,n) 解密,但在解密plaintext 之后和第一个不一样。

这是我的代码:

  public class KeyTest {
private BigInteger n = new BigInteger("33");
private BigInteger e = new BigInteger("3");
private BigInteger d = new BigInteger("7");

public static void main(String[] args) {
    KeyTest test = new KeyTest();

    BigInteger plaintext = new BigInteger("55");
    System.out.println("Plain text: " + plaintext);

    BigInteger ciphertext = test.encrypt(plaintext);
    System.out.println("Ciphertext: " + ciphertext);

    BigInteger decrypted = test.decrypt(ciphertext);
    System.out.println("Plain text after decryption: " + decrypted);
}

public BigInteger encrypt(BigInteger plaintext) {

    return plaintext.modPow(e, n);
}

public BigInteger decrypt(BigInteger ciphertext) {

    return ciphertext.modPow(d, n);
}
}

输出是:

Plain text: 55 Ciphertext: 22 Plain text after decryption: 22

【问题讨论】:

  • 您的“plaintext=55”大于“modulus=n=33”,因此实际加密的是数字 22(55 mod 33)。也发生了这样的情况,然后在模数 33 下加密的 22 又是 22。
  • 算法应该是(pow(plaintext, pubKey) mod n),第一个操作应该是pow然后mod操作是不是我不对?

标签: java encryption rsa biginteger public-key-encryption


【解决方案1】:

您的明文 (55) 大于模数 (33),因此您实际上无法加密消息。考虑以下稍微不同的示例:

  • p = 11
  • q = 17
  • n = 187
  • phi(n) = 160
  • 选择e = 3
  • 如果d = 107 那么e * d = 321 = 1 mod phi(n)

所以把你的代码改成:

  private BigInteger n = new BigInteger("187");
  private BigInteger e = new BigInteger("3");
  private BigInteger d = new BigInteger("107");

  public static void main(String[] args) {
    KeyTest test = new KeyTest();

    BigInteger plaintext = new BigInteger("55");
    System.out.println("Plain text: " + plaintext);

    BigInteger ciphertext = test.encrypt(plaintext);
    System.out.println("Ciphertext: " + ciphertext);

    BigInteger decrypted = test.decrypt(ciphertext);
    System.out.println("Plain text after decryption: " + decrypted);
  }

  public BigInteger encrypt(BigInteger plaintext) {

    return plaintext.modPow(e, n);
  }

  public BigInteger decrypt(BigInteger ciphertext) {

    return ciphertext.modPow(d, n);
  }
}

输出:

Plain text: 55
Ciphertext: 132
Plain text after decryption: 55

【讨论】:

  • 我现在明白为什么在我的代码中解密后我得到“错误”的答案,因为在 mod 33 操作后不可能计算出大于 33 的数字。
猜你喜欢
  • 2011-02-12
  • 1970-01-01
  • 2018-09-05
  • 2013-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多