RSA algorithm implementation does not work properly in java

Theoretically, I know that if n=33, e(public key)=3and d(private key)=7, I can encrypt plaintextusing class BigIntegerc modPow(e, n)and decrypt using modPow(d,n), but after decryption plaintextdoes not match the first.

Here is my code:

  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);
}
}

Conclusion:

Plain text: 55 Ciphertext: 22 Plain text after decryption: 22
+4
source share
1 answer

Your plain text ( 55) is larger than module ( 33), so you cannot actually encrypt the message. Consider the following slightly different example:

  • p = 11
  • q = 17
  • n = 187
  • phi(n) = 160
  • Select e = 3
  • If d = 107, then e * d = 321=1 mod phi(n)

So change your code to:

  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);
  }
}

Conclusion:

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

Source: https://habr.com/ru/post/1544924/


All Articles