fork download
  1. import java.io.DataInputStream;
  2. import java.io.IOException;
  3. import java.math.BigInteger;
  4. //import java.util.Base64;
  5.  
  6. // P = 137
  7. // Q = 131
  8. // E = 3
  9. // Public keys (n,e) = (17947, 3) and private keys (n, d) = (17947, 11787).
  10.  
  11. public class RSAMoreTest {
  12.  
  13. private BigInteger p;
  14. private BigInteger q;
  15. private BigInteger n;
  16. private BigInteger phi;
  17. private BigInteger e;
  18. private BigInteger d;
  19. //private int bitlength = 1024;
  20. //private SecureRandom r;
  21.  
  22. private RSAMoreTest()
  23. {
  24. p = BigInteger.valueOf(137);
  25. q = BigInteger.valueOf(131); // some value q
  26. n = p.multiply(q); // modulus, n = pq
  27. e = BigInteger.valueOf(3); // public key
  28. d = BigInteger.valueOf(11787); // private key
  29. phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
  30.  
  31. while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)
  32. {
  33. e.add(BigInteger.ONE);
  34. }
  35. d = e.modInverse(phi);
  36. }
  37.  
  38. @SuppressWarnings("deprecation")
  39. public static void main(String[] args) throws IOException
  40. {
  41. RSAMoreTest rsa = new RSAMoreTest();
  42. String teststring;
  43.  
  44. System.out.println("Enter the plain text:");
  45. teststring = in.readLine();
  46. System.out.println("Encrypting String: " + teststring);
  47. System.out.println("String in Bytes: "
  48. + bytesToString(teststring.getBytes()));
  49. //Encrypt
  50. byte[] encrypted = rsa.encrypt(teststring.getBytes());
  51. //Decryption
  52. byte[] decrypted = rsa.decrypt(encrypted);
  53.  
  54. System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
  55. System.out.println("Decrypting String: " + new String(decrypted));
  56.  
  57. //System.out.println("Encrypting Numbers: " + rsa.e.toString() + ", " + rsa.n.toString());
  58. //System.out.println("Decrypting Numbers: " + rsa.d.toString() + ", " + rsa.n.toString());
  59. }
  60.  
  61. private static String bytesToString(byte[] encrypted)
  62. {
  63. String test = "";
  64. for (byte b : encrypted)
  65. {
  66. test += Byte.toString(b);
  67. }
  68. return test;
  69. }
  70.  
  71. // Encrypt message
  72. private byte[] encrypt(byte[] message)
  73. {
  74. return (new BigInteger(message)).modPow(e, n).toByteArray();
  75. }
  76.  
  77. // Decrypt message
  78. private byte[] decrypt(byte[] message)
  79. {
  80. return (new BigInteger(message)).modPow(d, n).toByteArray();
  81. }
  82. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:11: error: class RSAMoreTest is public, should be declared in a file named RSAMoreTest.java
public class RSAMoreTest {
       ^
1 error
stdout
Standard output is empty