AES加密与解密(秘钥)

待我称王封你为后i 2023-10-09 10:26 77阅读 0赞

转载地址:https://blog.csdn.net/lichuangcsdn/article/details/80842338

  1. 1 package com.snsoft.modules.biz.test;
  2. 2
  3. 3 import org.slf4j.Logger;
  4. 4 import org.slf4j.LoggerFactory;
  5. 5 import sun.misc.BASE64Decoder;
  6. 6 import sun.misc.BASE64Encoder;
  7. 7 import tk.mybatis.mapper.util.StringUtil;
  8. 8
  9. 9 import javax.crypto.Cipher;
  10. 10 import javax.crypto.KeyGenerator;
  11. 11 import javax.crypto.SecretKey;
  12. 12 import javax.crypto.spec.SecretKeySpec;
  13. 13 import java.io.IOException;
  14. 14 import java.security.SecureRandom;
  15. 15
  16. 16 /**
  17. 17 * AES加密解密
  18. 18 *
  19. 19 * @author lichuang
  20. 20 * @since 2018-03-23
  21. 21 */
  22. 22 public class SecurityUtil {
  23. 23
  24. 24 private static final Logger logger = LoggerFactory.getLogger(SecurityUtil.class);
  25. 25
  26. 26 private static final String ENCODING = "UTF-8";
  27. 27
  28. 28 private static final String PASSWORD = "46EBA22EF5204DD5B110A1F730513965"; // 加密秘钥
  29. 29
  30. 30 /**
  31. 31 * AES加密
  32. 32 *
  33. 33 * @param content
  34. 34 * 明文
  35. 35 * @return 密文
  36. 36 */
  37. 37 public static String encryptAES(String content) {
  38. 38 if (StringUtil.isEmpty(content)) {
  39. 39 throw new RuntimeException("明文不能为空!");
  40. 40 }
  41. 41 byte[] encryptResult = encrypt(content, PASSWORD);
  42. 42 String encryptResultStr = parseByte2HexStr(encryptResult);
  43. 43 // BASE64位加密
  44. 44 encryptResultStr = ebotongEncrypto(encryptResultStr);
  45. 45 return encryptResultStr;
  46. 46 }
  47. 47
  48. 48 /**
  49. 49 * AES解密
  50. 50 *
  51. 51 * @param encryptResultStr
  52. 52 * 密文
  53. 53 * @return 明文
  54. 54 */
  55. 55 public static String decryptAES(String encryptResultStr) {
  56. 56 if (StringUtil.isEmpty(encryptResultStr)) {
  57. 57 throw new RuntimeException("密文不能为空");
  58. 58 }
  59. 59 // BASE64位解密
  60. 60 try {
  61. 61 String decrpt = ebotongDecrypto(encryptResultStr);
  62. 62 byte[] decryptFrom = parseHexStr2Byte(decrpt);
  63. 63 byte[] decryptResult = decrypt(decryptFrom, PASSWORD);
  64. 64 return new String(decryptResult);
  65. 65 } catch (Exception e) { // 当密文不规范时会报错,可忽略,但调用的地方需要考虑
  66. 66 return null;
  67. 67 }
  68. 68 }
  69. 69
  70. 70 /**
  71. 71 * 加密字符串
  72. 72 */
  73. 73 private static String ebotongEncrypto(String str) {
  74. 74 BASE64Encoder base64encoder = new BASE64Encoder();
  75. 75 String result = str;
  76. 76 if (str != null && str.length() > 0) {
  77. 77 try {
  78. 78 byte[] encodeByte = str.getBytes(ENCODING);
  79. 79 result = base64encoder.encode(encodeByte);
  80. 80 } catch (Exception e) {
  81. 81 e.printStackTrace();
  82. 82 }
  83. 83 }
  84. 84 // base64加密超过一定长度会自动换行 需要去除换行符
  85. 85 return result.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");
  86. 86 }
  87. 87
  88. 88 /**
  89. 89 * 解密字符串
  90. 90 */
  91. 91 private static String ebotongDecrypto(String str) {
  92. 92 BASE64Decoder base64decoder = new BASE64Decoder();
  93. 93 try {
  94. 94 byte[] encodeByte = base64decoder.decodeBuffer(str);
  95. 95 return new String(encodeByte);
  96. 96 } catch (IOException e) {
  97. 97 logger.error("IO 异常",e);
  98. 98 return str;
  99. 99 }
  100. 100 }
  101. 101
  102. 102 /**
  103. 103 * 加密
  104. 104 *
  105. 105 * @param content
  106. 106 * 需要加密的内容
  107. 107 * @param password
  108. 108 * 加密密码
  109. 109 * @return
  110. 110 */
  111. 111 private static byte[] encrypt(String content, String password) {
  112. 112 try {
  113. 113 KeyGenerator kgen = KeyGenerator.getInstance("AES");
  114. 114 // 注意这句是关键,防止linux下 随机生成key。用其他方式在Windows上正常,但Linux上会有问题
  115. 115 SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
  116. 116 secureRandom.setSeed(password.getBytes());
  117. 117 kgen.init(128, secureRandom);
  118. 118 // kgen.init(128, new SecureRandom(password.getBytes()));
  119. 119 SecretKey secretKey = kgen.generateKey();
  120. 120 byte[] enCodeFormat = secretKey.getEncoded();
  121. 121 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  122. 122 Cipher cipher = Cipher.getInstance("AES");// 创建密码器
  123. 123 byte[] byteContent = content.getBytes("utf-8");
  124. 124 cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
  125. 125 byte[] result = cipher.doFinal(byteContent);
  126. 126 return result; // 加密
  127. 127 } catch (Exception e) {
  128. 128 logger.error("加密异常", e);
  129. 129 }
  130. 130 return null;
  131. 131 }
  132. 132
  133. 133 /**
  134. 134 * 解密
  135. 135 *
  136. 136 * @param content
  137. 137 * 待解密内容
  138. 138 * @param password
  139. 139 * 解密密钥
  140. 140 * @return
  141. 141 */
  142. 142 private static byte[] decrypt(byte[] content, String password) {
  143. 143 try {
  144. 144 KeyGenerator kgen = KeyGenerator.getInstance("AES");
  145. 145 // 防止linux下 随机生成key
  146. 146 SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
  147. 147 secureRandom.setSeed(password.getBytes());
  148. 148 kgen.init(128, secureRandom);
  149. 149 // kgen.init(128, new SecureRandom(password.getBytes()));
  150. 150 SecretKey secretKey = kgen.generateKey();
  151. 151 byte[] enCodeFormat = secretKey.getEncoded();
  152. 152 SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
  153. 153 Cipher cipher = Cipher.getInstance("AES");// 创建密码器
  154. 154 cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
  155. 155 byte[] result = cipher.doFinal(content);
  156. 156 return result; // 加密
  157. 157 } catch (Exception e) {
  158. 158 logger.error("解密异常", e);
  159. 159 }
  160. 160 return null;
  161. 161 }
  162. 162
  163. 163 /**
  164. 164 * 将二进制转换成16进制
  165. 165 *
  166. 166 * @param buf
  167. 167 * @return
  168. 168 */
  169. 169 private static String parseByte2HexStr(byte buf[]) {
  170. 170 StringBuffer sb = new StringBuffer();
  171. 171 for (int i = 0; i < buf.length; i++) {
  172. 172 String hex = Integer.toHexString(buf[i] & 0xFF);
  173. 173 if (hex.length() == 1) {
  174. 174 hex = '0' + hex;
  175. 175 }
  176. 176 sb.append(hex.toUpperCase());
  177. 177 }
  178. 178 return sb.toString();
  179. 179 }
  180. 180
  181. 181 /**
  182. 182 * 将16进制转换为二进制
  183. 183 *
  184. 184 * @param hexStr
  185. 185 * @return
  186. 186 */
  187. 187 private static byte[] parseHexStr2Byte(String hexStr) {
  188. 188 if (hexStr.length() < 1)
  189. 189 return null;
  190. 190 byte[] result = new byte[hexStr.length() / 2];
  191. 191 for (int i = 0; i < hexStr.length() / 2; i++) {
  192. 192 int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
  193. 193 int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
  194. 194 result[i] = (byte) (high * 16 + low);
  195. 195 }
  196. 196 return result;
  197. 197 }
  198. 198
  199. 199 public static void main(String[] args) {
  200. 200 express();
  201. 201 }
  202. 202
  203. 203 /**
  204. 204 * 测试
  205. 205 */
  206. 206 private static void express() {
  207. 207 System.out.println("加密解密试试:");
  208. 208 String content = "你好北京";
  209. 209 System.out.println("原内容为:" + content);
  210. 210 String encryContent = encryptAES(content);
  211. 211 System.out.println("加密后的内容为:" + encryContent);
  212. 212 String decryContent = decryptAES(encryContent);
  213. 213 System.out.println("解密后的内容为:" + decryContent);
  214. 214 }
  215. 215
  216. 216 }

转载于:https://www.cnblogs.com/lidar/p/11558450.html

发表评论

表情:
评论列表 (有 0 条评论,77人围观)

还没有评论,来说两句吧...

相关阅读

    相关 AES 加密解密

    java AES 加密与解密 近些年DES使用越来越少,原因就在于其使用56位密钥,比较容易被破解,近些年来逐渐被AES替代,AES已经变成目前对称加密中最流行算法之一;A