[关闭]
@File 2020-04-10T03:41:29.000000Z 字数 1829 阅读 62

java-AES加密

骚操作


  1. public class AES {
  2. /**
  3. * 模式 ECB/CBC
  4. */
  5. private static String MODE = "ECB";
  6. /**
  7. * 算法
  8. */
  9. private static String RIJNDAEL = "PKCS5Padding";
  10. /**
  11. * key 长度(不能改)
  12. */
  13. private static int KEY_LENGTH = 16;
  14. /**
  15. * 加密
  16. * @param sSrc 需要加密字符串
  17. * @param sKey 秘钥
  18. * @return 加密的结果字符串
  19. * @throws Exception
  20. */
  21. public static String encrypt(String sSrc, String sKey) throws Exception {
  22. if (sKey == null) {
  23. System.out.print("Key为空null");
  24. return null;
  25. }
  26. // 判断Key是否为16位
  27. if (sKey.length() != KEY_LENGTH) {
  28. sKey = resetKey(sKey);
  29. }
  30. byte[] raw = sKey.getBytes("utf-8");
  31. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  32. //"算法/模式/补码方式"
  33. Cipher cipher = Cipher.getInstance("AES/"+MODE+"/"+RIJNDAEL);
  34. cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
  35. byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
  36. //此处使用BASE64做转码功能,同时能起到2次加密的作用。
  37. return new BASE64Encoder().encode(encrypted);
  38. }
  39. /**
  40. * 解密
  41. * @param sSrc 被加密的字符串
  42. * @param sKey 秘钥
  43. * @return 源字符串
  44. * @throws Exception
  45. */
  46. public static String decrypt(String sSrc, String sKey) throws Exception {
  47. try {
  48. // 判断Key是否正确
  49. if (sKey == null) {
  50. System.out.print("Key为空null");
  51. return null;
  52. }
  53. // 判断Key是否为16位
  54. if (sKey.length() != KEY_LENGTH) {
  55. sKey = resetKey(sKey);
  56. }
  57. byte[] raw = sKey.getBytes("utf-8");
  58. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
  59. Cipher cipher = Cipher.getInstance("AES/"+MODE+"/"+RIJNDAEL);
  60. cipher.init(Cipher.DECRYPT_MODE, skeySpec);
  61. //先用base64解密
  62. byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
  63. try {
  64. byte[] original = cipher.doFinal(encrypted1);
  65. String originalString = new String(original,"utf-8");
  66. return originalString;
  67. } catch (Exception e) {
  68. System.out.println(e.toString());
  69. return null;
  70. }
  71. } catch (Exception ex) {
  72. System.out.println(ex.toString());
  73. return null;
  74. }
  75. }
  76. /**
  77. * 秘钥补位和消位逻辑
  78. * @param key 秘钥
  79. * @return 16位长度的字符
  80. */
  81. private static String resetKey(String key){
  82. String newKey;
  83. int len = key.length();
  84. // 多于16位
  85. if(len > KEY_LENGTH){
  86. newKey = key.substring(len-KEY_LENGTH);
  87. }
  88. // 小于16位
  89. else{
  90. char[] tmpArr = new char[KEY_LENGTH-len];
  91. Arrays.fill(tmpArr,'0');
  92. newKey = key + new String(tmpArr);
  93. }
  94. return newKey;
  95. }
  96. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注