/study-cryption/src/main/java/com/bage/study/cryption/github/lugeek/AES.java

https://github.com/bage2014/study · Java · 76 lines · 48 code · 19 blank · 9 comment · 3 complexity · eccaf8ca729bc08b51bb634569e714b3 MD5 · raw file

  1. package com.bage.study.cryption.github.lugeek;
  2. import java.security.Key;
  3. import java.security.SecureRandom;
  4. import java.util.Base64;
  5. import javax.crypto.Cipher;
  6. import javax.crypto.KeyGenerator;
  7. import javax.crypto.SecretKey;
  8. import javax.crypto.spec.SecretKeySpec;
  9. /**
  10. * 来自:https://github.com/lugeek/Encryption/
  11. * @author bage
  12. *
  13. */
  14. public class AES {
  15. public static final String ALGORITHM = "AES";
  16. public static byte[] decryptBASE64(String key) throws Exception {
  17. return Base64.getDecoder().decode(key);
  18. }
  19. public static String encryptBASE64(byte[] key) throws Exception {
  20. return Base64.getEncoder().encodeToString(key);
  21. }
  22. private static Key toKey(byte[] key) throws Exception {
  23. //DESKeySpec dks = new DESKeySpec(key);
  24. //SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
  25. //SecretKey secretKey = keyFactory.generateSecret(dks);
  26. // 当使用其他对称加密算法时,如AES、Blowfish等算法时,用下述代码替换上述三行代码
  27. SecretKey secretKey = new SecretKeySpec(key, ALGORITHM);
  28. return secretKey;
  29. }
  30. public static byte[] decrypt(byte[] data, String key) throws Exception {
  31. Key k = toKey(decryptBASE64(key));
  32. Cipher cipher = Cipher.getInstance(ALGORITHM);
  33. cipher.init(Cipher.DECRYPT_MODE, k);
  34. return cipher.doFinal(data);
  35. }
  36. public static byte[] encrypt(byte[] data, String key) throws Exception {
  37. Key k = toKey(decryptBASE64(key));
  38. Cipher cipher = Cipher.getInstance(ALGORITHM);
  39. cipher.init(Cipher.ENCRYPT_MODE, k);
  40. return cipher.doFinal(data);
  41. }
  42. public static String initKey() throws Exception {
  43. return initKey(null);
  44. }
  45. public static String initKey(String seed) throws Exception {
  46. SecureRandom secureRandom = null;
  47. if (seed != null) {
  48. secureRandom = new SecureRandom(decryptBASE64(seed));
  49. } else {
  50. secureRandom = new SecureRandom();
  51. }
  52. KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM);
  53. kg.init(secureRandom);
  54. SecretKey secretKey = kg.generateKey();
  55. return encryptBASE64(secretKey.getEncoded());
  56. }
  57. }