EncryptionUtil.java 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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.KeyPair;
  9. import java.security.KeyPairGenerator;
  10. import java.security.NoSuchAlgorithmException;
  11. import java.security.PrivateKey;
  12. import java.security.PublicKey;
  13. import javax.crypto.Cipher;
  14. import javax.xml.bind.DatatypeConverter;
  15. /**
  16. * @author JavaDigest
  17. *
  18. */
  19. public class EncryptionUtil {
  20. /**
  21. * String to hold name of the encryption algorithm.
  22. */
  23. public static final String ALGORITHM = "RSA";
  24. /**
  25. * String to hold the name of the private key file.
  26. */
  27. public static final String PRIVATE_KEY_FILE = "C:/keys/private.key";
  28. /**
  29. * String to hold name of the public key file.
  30. */
  31. public static final String PUBLIC_KEY_FILE = "C:/keys/public.key";
  32. /**
  33. * Generate key which contains a pair of private and public key using 1024
  34. * bytes. Store the set of keys in Prvate.key and Public.key files.
  35. *
  36. * @throws NoSuchAlgorithmException
  37. * @throws IOException
  38. * @throws FileNotFoundException
  39. */
  40. public static void generateKey() {
  41. try {
  42. final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
  43. keyGen.initialize(1024);
  44. final KeyPair key = keyGen.generateKeyPair();
  45. File privateKeyFile = new File(PRIVATE_KEY_FILE);
  46. File publicKeyFile = new File(PUBLIC_KEY_FILE);
  47. // Create files to store public and private key
  48. if (privateKeyFile.getParentFile() != null) {
  49. privateKeyFile.getParentFile().mkdirs();
  50. }
  51. privateKeyFile.createNewFile();
  52. if (publicKeyFile.getParentFile() != null) {
  53. publicKeyFile.getParentFile().mkdirs();
  54. }
  55. publicKeyFile.createNewFile();
  56. // Saving the Public key in a file
  57. ObjectOutputStream publicKeyOS = new ObjectOutputStream(
  58. new FileOutputStream(publicKeyFile));
  59. publicKeyOS.writeObject(key.getPublic());
  60. publicKeyOS.close();
  61. // Saving the Private key in a file
  62. ObjectOutputStream privateKeyOS = new ObjectOutputStream(
  63. new FileOutputStream(privateKeyFile));
  64. privateKeyOS.writeObject(key.getPrivate());
  65. privateKeyOS.close();
  66. } catch (Exception e) {
  67. e.printStackTrace();
  68. }
  69. }
  70. /**
  71. * The method checks if the pair of public and private key has been generated.
  72. *
  73. * @return flag indicating if the pair of keys were generated.
  74. */
  75. public static boolean areKeysPresent() {
  76. File privateKey = new File(PRIVATE_KEY_FILE);
  77. File publicKey = new File(PUBLIC_KEY_FILE);
  78. if (privateKey.exists() && publicKey.exists()) {
  79. return true;
  80. }
  81. return false;
  82. }
  83. /**
  84. * Encrypt the plain text using public key.
  85. *
  86. * @param text
  87. * : original plain text
  88. * @param key
  89. * :The public key
  90. * @return Encrypted text
  91. * @throws java.lang.Exception
  92. */
  93. public static byte[] encrypt(String text, PublicKey key) {
  94. byte[] cipherText = null;
  95. try {
  96. // get an RSA cipher object and print the provider
  97. final Cipher cipher = Cipher.getInstance(ALGORITHM);
  98. // encrypt the plain text using the public key
  99. cipher.init(Cipher.ENCRYPT_MODE, key);
  100. cipherText = cipher.doFinal(text.getBytes());
  101. } catch (Exception e) {
  102. e.printStackTrace();
  103. }
  104. return cipherText;
  105. }
  106. /**
  107. * Decrypt text using private key.
  108. *
  109. * @param text
  110. * :encrypted text
  111. * @param key
  112. * :The private key
  113. * @return plain text
  114. * @throws java.lang.Exception
  115. */
  116. public static String decrypt(byte[] text, PrivateKey key) {
  117. byte[] dectyptedText = null;
  118. try {
  119. // get an RSA cipher object and print the provider
  120. final Cipher cipher = Cipher.getInstance(ALGORITHM);
  121. // decrypt the text using the private key
  122. cipher.init(Cipher.DECRYPT_MODE, key);
  123. dectyptedText = cipher.doFinal(text);
  124. } catch (Exception ex) {
  125. ex.printStackTrace();
  126. }
  127. return new String(dectyptedText);
  128. }
  129. /**
  130. * Test the EncryptionUtil
  131. */
  132. public static void main(String[] args) {
  133. try {
  134. // Check if the pair of keys are present else generate those.
  135. if (!areKeysPresent()) {
  136. // Method generates a pair of keys using the RSA algorithm and stores it
  137. // in their respective files
  138. generateKey();
  139. }
  140. final String originalText = "Text to be encrypted ";
  141. ObjectInputStream inputStream = null;
  142. // Encrypt the string using the public key
  143. inputStream = new ObjectInputStream(new FileInputStream(PUBLIC_KEY_FILE));
  144. final PublicKey publicKey = (PublicKey) inputStream.readObject();
  145. final byte[] cipherText = encrypt(originalText, publicKey);
  146. // Decrypt the cipher text using the private key.
  147. inputStream = new ObjectInputStream(new FileInputStream(PRIVATE_KEY_FILE));
  148. final PrivateKey privateKey = (PrivateKey) inputStream.readObject();
  149. final String plainText = decrypt(cipherText, privateKey);
  150. // Printing the Original, Encrypted and Decrypted Text
  151. System.out.println("Original: " + originalText);
  152. System.out.println("Encrypted: " +cipherText.toString());
  153. System.out.println("Encrypted: " +DatatypeConverter.printBase64Binary(cipherText));
  154. System.out.println("Decrypted: " + plainText);
  155. } catch (Exception e) {
  156. e.printStackTrace();
  157. }
  158. }
  159. }