Encrypt RSA Java


SUBMITTED BY: almon

DATE: Dec. 18, 2015, 5:47 p.m.

FORMAT: Java

SIZE: 6.0 kB

HITS: 860

  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.ObjectInputStream;
  7. import java.io.ObjectOutputStream;
  8. import java.security.InvalidKeyException;
  9. import java.security.KeyPair;
  10. import java.security.KeyPairGenerator;
  11. import java.security.NoSuchAlgorithmException;
  12. import java.security.PrivateKey;
  13. import java.security.PublicKey;
  14. import javax.crypto.BadPaddingException;
  15. import javax.crypto.Cipher;
  16. import javax.crypto.IllegalBlockSizeException;
  17. import javax.crypto.NoSuchPaddingException;
  18. public class RSA {
  19. /**
  20. * String to hold name of the encryption algorithm.
  21. */
  22. public static final String ALGORITHM = "RSA";
  23. /**
  24. * String to hold the name of the private key file.
  25. */
  26. public static final String PRIVATE_KEY_FILE = "private.key";
  27. /**
  28. * String to hold name of the public key file.
  29. */
  30. public static final String PUBLIC_KEY_FILE = "public.key";
  31. /**
  32. * Generate key which contains a pair of private and public key using 2048
  33. * bytes. Store the set of keys in Prvate.key and Public.key files.
  34. *
  35. */
  36. public static void generateKey() {
  37. try {
  38. final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
  39. keyGen.initialize(2048);
  40. final KeyPair key = keyGen.generateKeyPair();
  41. File privateKeyFile = new File(PRIVATE_KEY_FILE);
  42. File publicKeyFile = new File(PUBLIC_KEY_FILE);
  43. // Create files to store public and private key
  44. if (privateKeyFile.getParentFile() != null) {
  45. privateKeyFile.getParentFile().mkdirs();
  46. }
  47. privateKeyFile.createNewFile();
  48. if (publicKeyFile.getParentFile() != null) {
  49. publicKeyFile.getParentFile().mkdirs();
  50. }
  51. publicKeyFile.createNewFile();
  52. try ( // Saving the Public key in a file
  53. ObjectOutputStream publicKeyOS = new ObjectOutputStream(
  54. new FileOutputStream(publicKeyFile))) {
  55. publicKeyOS.writeObject(key.getPublic());
  56. }
  57. try ( // Saving the Private key in a file
  58. ObjectOutputStream privateKeyOS = new ObjectOutputStream(
  59. new FileOutputStream(privateKeyFile))) {
  60. privateKeyOS.writeObject(key.getPrivate());
  61. }
  62. } catch (NoSuchAlgorithmException | IOException e) {
  63. System.out.println(e.getMessage());
  64. }
  65. }
  66. /**
  67. * The method checks if the pair of public and private key has been
  68. * generated.
  69. *
  70. * @return flag indicating if the pair of keys were generated.
  71. */
  72. public static boolean areKeysPresent() {
  73. File privateKey = new File(PRIVATE_KEY_FILE);
  74. File publicKey = new File(PUBLIC_KEY_FILE);
  75. return privateKey.exists() && publicKey.exists();
  76. }
  77. /**
  78. * Encrypt the plain text using public key.
  79. *
  80. * @param text : original plain text
  81. * @param key :The public key
  82. * @return Encrypted text
  83. */
  84. public static byte[] encrypt(String text, PublicKey key) {
  85. byte[] cipherText = null;
  86. try {
  87. // get an RSA cipher object and print the provider
  88. final Cipher cipher = Cipher.getInstance(ALGORITHM);
  89. // encrypt the plain text using the public key
  90. cipher.init(Cipher.ENCRYPT_MODE, key);
  91. cipherText = cipher.doFinal(text.getBytes());
  92. } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
  93. System.out.println(e.getMessage());
  94. }
  95. return cipherText;
  96. }
  97. public static byte[] encrypt(String message) throws FileNotFoundException, IOException, ClassNotFoundException {
  98. if (!areKeysPresent()) {
  99. // Method generates a pair of keys using the RSA algorithm and stores it
  100. // in their respective files
  101. generateKey();
  102. }
  103. // Encrypt the string using the public key
  104. ObjectInputStream inputStream = null;
  105. inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
  106. final PublicKey publicKey = (PublicKey) inputStream.readObject();
  107. final byte[] cipherText = encrypt(message, publicKey);
  108. return cipherText;
  109. }
  110. public static String decrypt(byte[] message) throws FileNotFoundException, IOException, ClassNotFoundException {
  111. // Decrypt the cipher text using the private key.
  112. ObjectInputStream inputStream = null;
  113. inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
  114. final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
  115. final String plainText = decrypt(message, privateKey);
  116. return plainText;
  117. }
  118. /**
  119. * Decrypt text using private key.
  120. *
  121. * @param text :encrypted text
  122. * @param key :The private key
  123. * @return plain text
  124. */
  125. public static String decrypt(byte[] text, PrivateKey key) {
  126. byte[] dectyptedText = null;
  127. try {
  128. // get an RSA cipher object and print the provider
  129. final Cipher cipher = Cipher.getInstance(ALGORITHM);
  130. // decrypt the text using the private key
  131. cipher.init(Cipher.DECRYPT_MODE, key);
  132. dectyptedText = cipher.doFinal(text);
  133. } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
  134. System.out.println(ex.getMessage());
  135. }
  136. return new String(dectyptedText);
  137. }
  138. }

comments powered by Disqus