/src/main/java/com/basinc/golfminus/util/EncryptionUtils.java

https://github.com/sbasinge/golfplus · Java · 236 lines · 143 code · 33 blank · 60 comment · 29 complexity · 14695a7f403f2717630949b2ec951f41 MD5 · raw file

  1. package com.basinc.golfminus.util;
  2. import java.io.ByteArrayOutputStream;
  3. import java.security.Provider;
  4. import java.security.Security;
  5. import java.util.StringTokenizer;
  6. import javax.crypto.Cipher;
  7. import javax.crypto.KeyGenerator;
  8. import javax.crypto.SecretKey;
  9. import javax.crypto.spec.SecretKeySpec;
  10. import org.apache.log4j.Logger;
  11. /**
  12. * Utility class for encrypting and decrypting data using currently the AES
  13. * routines.
  14. *
  15. */
  16. public class EncryptionUtils {
  17. private static Logger log = Logger.getLogger(EncryptionUtils.class);
  18. private static final String ALGORITHM = "AES";
  19. private static final String AES_KEY = "138-250-228-149-209-13-189-103-145-215-42-99-30-105-7-59";
  20. public static String encrypt(String source) {
  21. // Check for null
  22. if (source == null || "".equalsIgnoreCase(source.trim())) {
  23. return "";
  24. }
  25. if (isEncrypted(source)) {
  26. return source;
  27. }
  28. try {
  29. // Get our secret key
  30. // Key key = getKey();
  31. // KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
  32. // SecretKey key = keyGen.generateKey();
  33. SecretKey key = new SecretKeySpec(getBytes(AES_KEY), ALGORITHM);
  34. // Create the cipher
  35. Cipher cipher = Cipher.getInstance(ALGORITHM);
  36. // Initialize the cipher for encryption
  37. cipher.init(Cipher.ENCRYPT_MODE, key);
  38. // Our cleartext as bytes
  39. byte[] cleartext = source.getBytes();
  40. // Encrypt the cleartext
  41. byte[] ciphertext = cipher.doFinal(cleartext);
  42. // Return a String representation of the cipher text
  43. return getString(ciphertext);
  44. } catch (Exception e) {
  45. log.error("Error encrypting data.", e);
  46. return null;
  47. }
  48. }
  49. public static String generateKey() {
  50. try {
  51. KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
  52. SecretKey key = keyGen.generateKey();
  53. byte[] bytes = key.getEncoded();
  54. return getString(bytes);
  55. } catch (Exception e) {
  56. log.error("Error generating encryption key.", e);
  57. return null;
  58. }
  59. }
  60. public static String decrypt(String source) {
  61. try {
  62. if (source == null || "".equalsIgnoreCase(source.trim())) {
  63. return "";
  64. }
  65. // If the source is not encrypted, simply return it.
  66. if (!isEncrypted(source)) {
  67. return source;
  68. }
  69. // Get our secret key
  70. // Key key = getKey();
  71. // KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
  72. // SecretKey key = keyGen.generateKey();
  73. SecretKey key = new SecretKeySpec(getBytes(AES_KEY), ALGORITHM);
  74. // Create the cipher
  75. Cipher cipher = Cipher.getInstance(ALGORITHM);
  76. // Encrypt the cleartext
  77. byte[] ciphertext = getBytes(source);
  78. // Initialize the same cipher for decryption
  79. cipher.init(Cipher.DECRYPT_MODE, key);
  80. // Decrypt the ciphertext
  81. byte[] cleartext = cipher.doFinal(ciphertext);
  82. // Return the clear text
  83. return new String(cleartext);
  84. } catch (Exception e) {
  85. log.error("Error decrypting data.", e);
  86. return null;
  87. }
  88. }
  89. // private static Key getKey()
  90. // {
  91. // try
  92. // {
  93. // byte[] bytes = getBytes(KEY_STRING);
  94. // DESKeySpec pass = new DESKeySpec(bytes);
  95. // SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM);
  96. // SecretKey s = skf.generateSecret(pass);
  97. // return s;
  98. // }
  99. // catch (Exception e)
  100. // {
  101. // e.printStackTrace();
  102. // }
  103. // return null;
  104. // }
  105. /**
  106. * Returns true if the specified text is encrypted, false otherwise
  107. *
  108. * @param text
  109. * @return boolean
  110. */
  111. public static boolean isEncrypted(String text) {
  112. // Check for null
  113. if (text == null) {
  114. return false;
  115. }
  116. // If the string does not have any separators then it is not encrypted
  117. if (text.indexOf('-') == -1) {
  118. return false;
  119. }
  120. StringTokenizer st = new StringTokenizer(text, "-", false);
  121. while (st.hasMoreTokens()) {
  122. String token = st.nextToken();
  123. if (token.length() > 3) {
  124. return false;
  125. }
  126. for (int i = 0; i < token.length(); i++) {
  127. if (!Character.isDigit(token.charAt(i))) {
  128. return false;
  129. }
  130. }
  131. }
  132. return true;
  133. }
  134. private static String getString(byte[] bytes) {
  135. StringBuffer sb = new StringBuffer();
  136. for (int i = 0; i < bytes.length; i++) {
  137. byte b = bytes[i];
  138. sb.append((int) (0x00FF & b));
  139. if (i + 1 < bytes.length) {
  140. sb.append("-");
  141. }
  142. }
  143. return sb.toString();
  144. }
  145. private static byte[] getBytes(String str) {
  146. if (str == null) {
  147. return null;
  148. }
  149. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  150. StringTokenizer st = new StringTokenizer(str, "-", false);
  151. while (st.hasMoreTokens()) {
  152. int i = Integer.parseInt(st.nextToken());
  153. bos.write((byte) i);
  154. }
  155. return bos.toByteArray();
  156. }
  157. // private static String generateBlowfishKey() {
  158. // try {
  159. // KeyGenerator kgen = KeyGenerator.getInstance("Blowfish");
  160. // SecretKey skey = kgen.generateKey();
  161. // byte[] raw = skey.getEncoded();
  162. // return getString(raw);
  163. // } catch (Exception e) {
  164. // log.error("Error generating encryption key.", e);
  165. // return null;
  166. // }
  167. // }
  168. public static void main(String[] args) {
  169. showProviders();
  170. if (args.length < 1) {
  171. System.out.println("Usage: EncryptionUtils <command> < args > ");
  172. System.out.println("\t<command>: encrypt, decrypt, generate - key");
  173. System.exit(0);
  174. }
  175. String command = args[0];
  176. if (command.equalsIgnoreCase("generate-key")) {
  177. System.out.println("New key: " + generateKey());
  178. } else if (command.equalsIgnoreCase("encrypt")) {
  179. String plaintext = args[1];
  180. String cipherText = encrypt(plaintext);
  181. System.out.println(plaintext + " = " + cipherText);
  182. System.out.println(cipherText + " = " + decrypt(cipherText));
  183. } else if (command.equalsIgnoreCase("decrypt")) {
  184. String ciphertext = args[1];
  185. System.out.println(ciphertext + " = " + decrypt(ciphertext));
  186. }
  187. }
  188. public static void showProviders() {
  189. try {
  190. Provider[] providers = Security.getProviders();
  191. for (int i = 0; i < providers.length; i++) {
  192. System.out.println("Provider: " + providers[i].getName() + ", " + providers[i].getInfo());
  193. for (Object o : providers[i].keySet()) {
  194. String key = (String) o;
  195. String value = (String) providers[i].get(key);
  196. System.out.println("\t" + key + " = " + value);
  197. }
  198. }
  199. } catch (Exception e) {
  200. log.error("Error listing security providers.", e);
  201. }
  202. }
  203. }