当前位置:   article > 正文

AES加密解密(附源码操作)

AES加密解密(附源码操作)
  1. public class AESutil2
  2. {
  3. public static String encrypt(String content, String secureKey)
  4. {
  5. try
  6. {
  7. if ((StringUtils.isEmpty(content)) ||
  8. (StringUtils.isEmpty(secureKey))) {
  9. return null;
  10. }
  11. KeyGenerator kgen = KeyGenerator.getInstance("AES");
  12. SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
  13. secureRandom.setSeed(secureKey.getBytes());
  14. kgen.init(128, secureRandom);
  15. SecretKey secretKey = kgen.generateKey();
  16. byte[] enCodeFormat = secretKey.getEncoded();
  17. SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  18. Cipher cipher = Cipher.getInstance("AES");
  19. byte[] byteContent = content.getBytes("utf-8");
  20. cipher.init(1, key);
  21. byte[] result = cipher.doFinal(byteContent);
  22. return encodeBASE64(result);
  23. }
  24. catch (Exception e) {
  25. }
  26. return null;
  27. }
  28. public static String decrypt(String content, String secureKey)
  29. {
  30. try
  31. {
  32. if ((StringUtils.isEmpty(content)) || (StringUtils.isEmpty(secureKey))) {
  33. return null;
  34. }
  35. KeyGenerator kgen = KeyGenerator.getInstance("AES");
  36. SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
  37. secureRandom.setSeed(secureKey.getBytes());
  38. kgen.init(128, secureRandom);
  39. SecretKey secretKey = kgen.generateKey();
  40. byte[] enCodeFormat = secretKey.getEncoded();
  41. SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  42. Cipher cipher = Cipher.getInstance("AES");
  43. cipher.init(2, key);
  44. byte[] base64Dec = Base64.decode(content);
  45. byte[] result = cipher.doFinal(base64Dec);
  46. return new String(result);
  47. }
  48. catch (Exception e)
  49. {
  50. }
  51. return null;
  52. }
  53. public static String encodeBASE64(byte[] content)
  54. throws Exception
  55. {
  56. if ((content == null) || (content.length == 0)) {
  57. return null;
  58. }
  59. try
  60. {
  61. return Base64.encode(content);
  62. }
  63. catch (Exception e)
  64. {
  65. }
  66. return null;
  67. }
  68. public static void main(String[] args) {
  69. String content = "5f3a87d591fa51720261e0b7e4e14c33";
  70. String password = "123456a";
  71. //加密
  72. System.out.println("加密前:" + content);
  73. String encryptResultStr = encrypt(content, password);
  74. System.out.println("加密后:" + encryptResultStr);
  75. //解密
  76. String decryptFrom = decrypt(encryptResultStr,password);
  77. System.out.println("解密后:" + decryptFrom);
  78. }
  79. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/413332
推荐阅读
相关标签
  

闽ICP备14008679号