PageRenderTime 41ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/recursivity/commons/StringEncrypter.java

https://github.com/bowler-framework/recursivity-commons
Java | 240 lines | 125 code | 45 blank | 70 comment | 0 complexity | bc1645598a394800f71b021d7af0102f MD5 | raw file
  1. package com.recursivity.commons;
  2. // CIPHER / GENERATORS
  3. import javax.crypto.Cipher;
  4. import javax.crypto.SecretKey;
  5. import javax.crypto.KeyGenerator;
  6. // KEY SPECIFICATIONS
  7. import java.security.spec.KeySpec;
  8. import java.security.spec.AlgorithmParameterSpec;
  9. import javax.crypto.spec.PBEKeySpec;
  10. import javax.crypto.SecretKeyFactory;
  11. import javax.crypto.spec.PBEParameterSpec;
  12. // EXCEPTIONS
  13. import java.security.InvalidAlgorithmParameterException;
  14. import java.security.NoSuchAlgorithmException;
  15. import java.security.InvalidKeyException;
  16. import java.security.spec.InvalidKeySpecException;
  17. import javax.crypto.NoSuchPaddingException;
  18. import javax.crypto.BadPaddingException;
  19. import javax.crypto.IllegalBlockSizeException;
  20. import java.io.UnsupportedEncodingException;
  21. import java.io.IOException;
  22. /**
  23. * -----------------------------------------------------------------------------
  24. * The following example implements a class for encrypting and decrypting
  25. * strings using several Cipher algorithms. The class is created with a key and
  26. * can be used repeatedly to encrypt and decrypt strings using that key.
  27. * Some of the more popular algorithms are:
  28. * Blowfish
  29. * DES
  30. * DESede
  31. * PBEWithMD5AndDES
  32. * PBEWithMD5AndTripleDES
  33. * TripleDES
  34. *
  35. * @version 1.0
  36. * @author Jeffrey M. Hunter (jhunter@idevelopment.info)
  37. * @author http://www.idevelopment.info
  38. * -----------------------------------------------------------------------------
  39. */
  40. public class StringEncrypter {
  41. Cipher ecipher;
  42. Cipher dcipher;
  43. /**
  44. * Constructor used to create this object. Responsible for setting
  45. * and initializing this object's encrypter and decrypter Chipher instances
  46. * given a Secret Key and algorithm.
  47. * @param key Secret Key used to initialize both the encrypter and
  48. * decrypter instances.
  49. * @param algorithm Which algorithm to use for creating the encrypter and
  50. * decrypter instances.
  51. */
  52. StringEncrypter(SecretKey key, String algorithm) {
  53. try {
  54. ecipher = Cipher.getInstance(algorithm);
  55. dcipher = Cipher.getInstance(algorithm);
  56. ecipher.init(Cipher.ENCRYPT_MODE, key);
  57. dcipher.init(Cipher.DECRYPT_MODE, key);
  58. } catch (NoSuchPaddingException e) {
  59. System.out.println("EXCEPTION: NoSuchPaddingException");
  60. } catch (NoSuchAlgorithmException e) {
  61. System.out.println("EXCEPTION: NoSuchAlgorithmException");
  62. } catch (InvalidKeyException e) {
  63. System.out.println("EXCEPTION: InvalidKeyException");
  64. }
  65. }
  66. /**
  67. * Constructor used to create this object. Responsible for setting
  68. * and initializing this object's encrypter and decrypter Chipher instances
  69. * given a Pass Phrase and algorithm.
  70. * @param passPhrase Pass Phrase used to initialize both the encrypter and
  71. * decrypter instances.
  72. */
  73. StringEncrypter(String passPhrase) {
  74. // 8-bytes Salt
  75. byte[] salt = {
  76. (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
  77. (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
  78. };
  79. // Iteration count
  80. int iterationCount = 19;
  81. try {
  82. KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
  83. SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
  84. ecipher = Cipher.getInstance(key.getAlgorithm());
  85. dcipher = Cipher.getInstance(key.getAlgorithm());
  86. // Prepare the parameters to the cipthers
  87. AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
  88. ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
  89. dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
  90. } catch (InvalidAlgorithmParameterException e) {
  91. System.out.println("EXCEPTION: InvalidAlgorithmParameterException");
  92. } catch (InvalidKeySpecException e) {
  93. System.out.println("EXCEPTION: InvalidKeySpecException");
  94. } catch (NoSuchPaddingException e) {
  95. System.out.println("EXCEPTION: NoSuchPaddingException");
  96. } catch (NoSuchAlgorithmException e) {
  97. System.out.println("EXCEPTION: NoSuchAlgorithmException");
  98. } catch (InvalidKeyException e) {
  99. System.out.println("EXCEPTION: InvalidKeyException");
  100. }
  101. }
  102. /**
  103. * Takes a single String as an argument and returns an Encrypted version
  104. * of that String.
  105. * @param str String to be encrypted
  106. * @return <code>String</code> Encrypted version of the provided String
  107. */
  108. public String encrypt(String str) {
  109. try {
  110. // Encode the string into bytes using utf-8
  111. byte[] utf8 = str.getBytes("UTF8");
  112. // Encrypt
  113. byte[] enc = ecipher.doFinal(utf8);
  114. // Encode bytes to base64 to get a string
  115. return new sun.misc.BASE64Encoder().encode(enc);
  116. } catch (BadPaddingException e) {
  117. } catch (IllegalBlockSizeException e) {
  118. } catch (UnsupportedEncodingException e) {
  119. } catch (IOException e) {
  120. }
  121. return null;
  122. }
  123. /**
  124. * Takes a encrypted String as an argument, decrypts and returns the
  125. * decrypted String.
  126. * @param str Encrypted String to be decrypted
  127. * @return <code>String</code> Decrypted version of the provided String
  128. */
  129. public String decrypt(String str) {
  130. try {
  131. // Decode base64 to get bytes
  132. byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
  133. // Decrypt
  134. byte[] utf8 = dcipher.doFinal(dec);
  135. // Decode using utf-8
  136. return new String(utf8, "UTF8");
  137. } catch (BadPaddingException e) {
  138. } catch (IllegalBlockSizeException e) {
  139. } catch (UnsupportedEncodingException e) {
  140. } catch (IOException e) {
  141. }
  142. return null;
  143. }
  144. /**
  145. * The following method is used for testing the String Encrypter class.
  146. * This method is responsible for encrypting and decrypting a sample
  147. * String using several symmetric temporary Secret Keys.
  148. */
  149. public static void testUsingSecretKey() {
  150. try {
  151. System.out.println();
  152. System.out.println("+----------------------------------------+");
  153. System.out.println("| -- Test Using Secret Key Method -- |");
  154. System.out.println("+----------------------------------------+");
  155. System.out.println();
  156. String secretString = "Attack at dawn!";
  157. // Generate a temporary key for this example. In practice, you would
  158. // save this key somewhere. Keep in mind that you can also use a
  159. // Pass Phrase.
  160. SecretKey desKey = KeyGenerator.getInstance("DES").generateKey();
  161. SecretKey blowfishKey = KeyGenerator.getInstance("Blowfish").generateKey();
  162. SecretKey desedeKey = KeyGenerator.getInstance("DESede").generateKey();
  163. // Create encrypter/decrypter class
  164. StringEncrypter desEncrypter = new StringEncrypter(desKey, desKey.getAlgorithm());
  165. StringEncrypter blowfishEncrypter = new StringEncrypter(blowfishKey, blowfishKey.getAlgorithm());
  166. StringEncrypter desedeEncrypter = new StringEncrypter(desedeKey, desedeKey.getAlgorithm());
  167. // Encrypt the string
  168. String desEncrypted = desEncrypter.encrypt(secretString);
  169. String blowfishEncrypted = blowfishEncrypter.encrypt(secretString);
  170. String desedeEncrypted = desedeEncrypter.encrypt(secretString);
  171. // Decrypt the string
  172. String desDecrypted = desEncrypter.decrypt(desEncrypted);
  173. String blowfishDecrypted = blowfishEncrypter.decrypt(blowfishEncrypted);
  174. String desedeDecrypted = desedeEncrypter.decrypt(desedeEncrypted);
  175. // Print out values
  176. System.out.println(desKey.getAlgorithm() + " Encryption algorithm");
  177. System.out.println(" Original String : " + secretString);
  178. System.out.println(" Encrypted String : " + desEncrypted);
  179. System.out.println(" Decrypted String : " + desDecrypted);
  180. System.out.println();
  181. System.out.println(blowfishKey.getAlgorithm() + " Encryption algorithm");
  182. System.out.println(" Original String : " + secretString);
  183. System.out.println(" Encrypted String : " + blowfishEncrypted);
  184. System.out.println(" Decrypted String : " + blowfishDecrypted);
  185. System.out.println();
  186. System.out.println(desedeKey.getAlgorithm() + " Encryption algorithm");
  187. System.out.println(" Original String : " + secretString);
  188. System.out.println(" Encrypted String : " + desedeEncrypted);
  189. System.out.println(" Decrypted String : " + desedeDecrypted);
  190. System.out.println();
  191. } catch (NoSuchAlgorithmException e) {
  192. }
  193. }
  194. private static String passPhrase = "F7UkoExKPvsCeIQqRdKiQ3oEMoImKnHPtOlfcPCNg";
  195. }