RSA算法实现在java中无法正常工作

时间:2014-06-17 14:02:02

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

从理论上讲,我知道如果n=33e(public key)=3d(private key)=7我可以使用plaintextBigInteger来加密modPow(e, n),并且使用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

1 个答案:

答案 0 :(得分:3)

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

  • p = 11
  • q = 17
  • n = 187
  • phi(n) = 160
  • 选择e = 3
  • 如果d = 107e * 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