AesUtil.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. //package com.ylzb.fjsdermyy.modules.settleaccounts.util;
  2. //
  3. //import sun.misc.BASE64Decoder;
  4. //import sun.misc.BASE64Encoder;
  5. //
  6. //import javax.crypto.BadPaddingException;
  7. //import javax.crypto.Cipher;
  8. //import javax.crypto.IllegalBlockSizeException;
  9. //import javax.crypto.NoSuchPaddingException;
  10. //import javax.crypto.spec.SecretKeySpec;
  11. //import java.io.IOException;
  12. //import java.io.UnsupportedEncodingException;
  13. //import java.security.InvalidKeyException;
  14. //import java.security.NoSuchAlgorithmException;
  15. //
  16. ///**
  17. // * @Description: AES算法封装
  18. // */
  19. //public class AesUtil {
  20. //
  21. // /**
  22. // * 加密算法
  23. // */
  24. // private static final String ENCRY_ALGORITHM = "AES";
  25. //
  26. // /**
  27. // * 加密算法/加密模式/填充类型
  28. // * 本例采用AES加密,ECB加密模式,PKCS5Padding填充
  29. // */
  30. // private static final String CIPHER_MODE = "AES/CBC/PKCS5Padding";
  31. //
  32. // /**
  33. // * 设置iv偏移量
  34. // * 本例采用ECB加密模式,不需要设置iv偏移量
  35. // */
  36. // private static final String IV_ = "0102030405060708";
  37. //
  38. // /**
  39. // * 设置加密字符集
  40. // * 本例采用 UTF-8 字符集
  41. // */
  42. // private static final String CHARACTER = "UTF-8";
  43. //
  44. // /**
  45. // * 设置加密密码处理长度。
  46. // * 不足此长度补0;
  47. // */
  48. // private static final int PWD_SIZE = 16;
  49. //
  50. // /**
  51. // * 密码处理方法
  52. // * 如果加解密出问题,
  53. // * 请先查看本方法,排除密码长度不足填充0字节,导致密码不一致
  54. // * @param password 待处理的密码
  55. // * @return
  56. // * @throws UnsupportedEncodingException
  57. // */
  58. // private static byte[] pwdHandler(String password) throws UnsupportedEncodingException {
  59. // byte[] data = null;
  60. // if (password != null) {
  61. // byte[] bytes = password.getBytes(CHARACTER);
  62. // if (password.length() < PWD_SIZE) {
  63. // System.arraycopy(bytes, 0, data = new byte[PWD_SIZE], 0, bytes.length);
  64. // } else {
  65. // data = bytes;
  66. // }
  67. // }
  68. // return data;
  69. // }
  70. //
  71. // //======================>原始加密<======================
  72. //
  73. // /**
  74. // * 原始加密
  75. // * @param clearTextBytes 明文字节数组,待加密的字节数组
  76. // * @param pwdBytes 加密密码字节数组
  77. // * @return 返回加密后的密文字节数组,加密错误返回null
  78. // */
  79. // public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) {
  80. // try {
  81. // // 1 获取加密密钥
  82. // SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);
  83. //
  84. // // 2 获取Cipher实例
  85. // Cipher cipher = Cipher.getInstance(CIPHER_MODE);
  86. //
  87. // // 查看数据块位数 默认为16(byte) * 8 =128 bit
  88. //// System.out.println("数据块位数(byte):" + cipher.getBlockSize());
  89. //
  90. // // 3 初始化Cipher实例。设置执行模式以及加密密钥
  91. // cipher.init(Cipher.ENCRYPT_MODE, keySpec);
  92. //
  93. // // 4 执行
  94. // byte[] cipherTextBytes = cipher.doFinal(clearTextBytes);
  95. //
  96. // // 5 返回密文字符集
  97. // return cipherTextBytes;
  98. //
  99. // } catch (NoSuchPaddingException e) {
  100. // e.printStackTrace();
  101. // } catch (NoSuchAlgorithmException e) {
  102. // e.printStackTrace();
  103. // } catch (BadPaddingException e) {
  104. // e.printStackTrace();
  105. // } catch (IllegalBlockSizeException e) {
  106. // e.printStackTrace();
  107. // } catch (InvalidKeyException e) {
  108. // e.printStackTrace();
  109. // } catch (Exception e) {
  110. // e.printStackTrace();
  111. // }
  112. // return null;
  113. // }
  114. //
  115. // /**
  116. // * 原始解密
  117. // * @param cipherTextBytes 密文字节数组,待解密的字节数组
  118. // * @param pwdBytes 解密密码字节数组
  119. // * @return 返回解密后的明文字节数组,解密错误返回null
  120. // */
  121. // public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) {
  122. //
  123. // try {
  124. // // 1 获取解密密钥
  125. // SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);
  126. //
  127. // // 2 获取Cipher实例
  128. // Cipher cipher = Cipher.getInstance(CIPHER_MODE);
  129. //
  130. // // 查看数据块位数 默认为16(byte) * 8 =128 bit
  131. //// System.out.println("数据块位数(byte):" + cipher.getBlockSize());
  132. //
  133. // // 3 初始化Cipher实例。设置执行模式以及加密密钥
  134. // cipher.init(Cipher.DECRYPT_MODE, keySpec);
  135. //
  136. // // 4 执行
  137. // byte[] clearTextBytes = cipher.doFinal(cipherTextBytes);
  138. //
  139. // // 5 返回明文字符集
  140. // return clearTextBytes;
  141. //
  142. // } catch (NoSuchAlgorithmException e) {
  143. // e.printStackTrace();
  144. // } catch (InvalidKeyException e) {
  145. // e.printStackTrace();
  146. // } catch (NoSuchPaddingException e) {
  147. // e.printStackTrace();
  148. // } catch (BadPaddingException e) {
  149. // e.printStackTrace();
  150. // } catch (IllegalBlockSizeException e) {
  151. // e.printStackTrace();
  152. // } catch (Exception e) {
  153. // e.printStackTrace();
  154. // }
  155. // // 解密错误 返回null
  156. // return null;
  157. // }
  158. //
  159. // //======================>BASE64<======================
  160. //
  161. // /**
  162. // * BASE64加密
  163. // * @param clearText 明文,待加密的内容
  164. // * @param password 密码,加密的密码
  165. // * @return 返回密文,加密后得到的内容。加密错误返回null
  166. // */
  167. // public static String encryptBase64(String clearText, String password) {
  168. // try {
  169. // // 1 获取加密密文字节数组
  170. // byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));
  171. //
  172. // // 2 对密文字节数组进行BASE64 encoder 得到 BASE6输出的密文
  173. // BASE64Encoder base64Encoder = new BASE64Encoder();
  174. // String cipherText = base64Encoder.encode(cipherTextBytes);
  175. //
  176. // // 3 返回BASE64输出的密文
  177. // return cipherText;
  178. // } catch (UnsupportedEncodingException e) {
  179. // e.printStackTrace();
  180. // } catch (Exception e) {
  181. // e.printStackTrace();
  182. // }
  183. // // 加密错误 返回null
  184. // return null;
  185. // }
  186. //
  187. // /**
  188. // * BASE64解密
  189. // * @param cipherText 密文,带解密的内容
  190. // * @param password 密码,解密的密码
  191. // * @return 返回明文,解密后得到的内容。解密错误返回null
  192. // */
  193. // public static String decryptBase64(String cipherText, String password) {
  194. // try {
  195. // // 1 对 BASE64输出的密文进行BASE64 decodebuffer 得到密文字节数组
  196. // BASE64Decoder base64Decoder = new BASE64Decoder();
  197. // byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText);
  198. //
  199. // // 2 对密文字节数组进行解密 得到明文字节数组
  200. // byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));
  201. //
  202. // // 3 根据 CHARACTER 转码,返回明文字符串
  203. // return new String(clearTextBytes, CHARACTER);
  204. // } catch (UnsupportedEncodingException e) {
  205. // e.printStackTrace();
  206. // } catch (IOException e) {
  207. // e.printStackTrace();
  208. // } catch (Exception e) {
  209. // e.printStackTrace();
  210. // }
  211. // // 解密错误返回null
  212. // return null;
  213. // }
  214. //
  215. // //======================>HEX<======================
  216. //
  217. // /**
  218. // * HEX加密
  219. // * @param clearText 明文,待加密的内容
  220. // * @param password 密码,加密的密码
  221. // * @return 返回密文,加密后得到的内容。加密错误返回null
  222. // */
  223. // public static String encryptHex(String clearText, String password) {
  224. // try {
  225. // // 1 获取加密密文字节数组
  226. // byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));
  227. //
  228. // // 2 对密文字节数组进行 转换为 HEX输出密文
  229. // String cipherText = byte2hex(cipherTextBytes);
  230. //
  231. // // 3 返回 HEX输出密文
  232. // return cipherText;
  233. // } catch (UnsupportedEncodingException e) {
  234. // e.printStackTrace();
  235. // } catch (Exception e) {
  236. // e.printStackTrace();
  237. // }
  238. // // 加密错误返回null
  239. // return null;
  240. // }
  241. //
  242. // /**
  243. // * HEX解密
  244. // * @param cipherText 密文,带解密的内容
  245. // * @param password 密码,解密的密码
  246. // * @return 返回明文,解密后得到的内容。解密错误返回null
  247. // */
  248. // public static String decryptHex(String cipherText, String password) {
  249. // try {
  250. // // 1 将HEX输出密文 转为密文字节数组
  251. // byte[] cipherTextBytes = hex2byte(cipherText);
  252. //
  253. // // 2 将密文字节数组进行解密 得到明文字节数组
  254. // byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));
  255. //
  256. // // 3 根据 CHARACTER 转码,返回明文字符串
  257. // return new String(clearTextBytes, CHARACTER);
  258. // } catch (UnsupportedEncodingException e) {
  259. // e.printStackTrace();
  260. // } catch (Exception e) {
  261. // e.printStackTrace();
  262. // }
  263. // // 解密错误返回null
  264. // return null;
  265. // }
  266. //
  267. // /*字节数组转成16进制字符串 */
  268. // public static String byte2hex(byte[] bytes) { // 一个字节的数,
  269. // StringBuffer sb = new StringBuffer(bytes.length * 2);
  270. // String tmp = "";
  271. // for (int n = 0; n < bytes.length; n++) {
  272. // // 整数转成十六进制表示
  273. // tmp = (java.lang.Integer.toHexString(bytes[n] & 0XFF));
  274. // if (tmp.length() == 1) {
  275. // sb.append("0");
  276. // }
  277. // sb.append(tmp);
  278. // }
  279. // return sb.toString().toUpperCase(); // 转成大写
  280. // }
  281. //
  282. // /*将hex字符串转换成字节数组 */
  283. // private static byte[] hex2byte(String str) {
  284. // if (str == null || str.length() < 2) {
  285. // return new byte[0];
  286. // }
  287. // str = str.toLowerCase();
  288. // int l = str.length() / 2;
  289. // byte[] result = new byte[l];
  290. // for (int i = 0; i < l; ++i) {
  291. // String tmp = str.substring(2 * i, 2 * i + 2);
  292. // result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
  293. // }
  294. // return result;
  295. // }
  296. //
  297. // public static void main(String[] args) {
  298. // String test = encryptHex("test", "1234567800000000");
  299. // System.out.println(test);
  300. //
  301. // System.out.println(decryptHex(test, "1234567800000000"));
  302. // }
  303. //}
  304. package com.yihu.jw.utils;
  305. /**
  306. * Created by hdwang on 2019/1/17.
  307. */
  308. import org.slf4j.Logger;
  309. import org.slf4j.LoggerFactory;
  310. import javax.crypto.Cipher;
  311. import javax.crypto.spec.IvParameterSpec;
  312. import javax.crypto.spec.SecretKeySpec;
  313. /**
  314. * 加密工具类
  315. */
  316. public class AesUtil {
  317. private static final Logger logger = LoggerFactory.getLogger(AesUtil.class);
  318. private static final String KEY_ALGORITHM = "AES";
  319. /**
  320. * 默认的加密算法
  321. */
  322. public static final String DEFAULT_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
  323. /**
  324. * AES 加密操作
  325. *
  326. * @param content 待加密内容
  327. * @param password 加密密码
  328. * @param iv 使用CBC模式,需要一个向量iv,可增加加密算法的强度
  329. * @return 加密数据
  330. */
  331. public static String encrypt(String content, String password, String iv) {
  332. try {
  333. //创建密码器
  334. Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
  335. //密码key(超过16字节即128bit的key,需要替换jre中的local_policy.jar和US_export_policy.jar,否则报错:Illegal key size)
  336. SecretKeySpec keySpec = new SecretKeySpec(password.getBytes("utf-8"),KEY_ALGORITHM);
  337. //向量iv
  338. IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
  339. //初始化为加密模式的密码器
  340. cipher.init(Cipher.ENCRYPT_MODE,keySpec,ivParameterSpec);
  341. //加密
  342. byte[] byteContent = content.getBytes("utf-8");
  343. byte[] result = cipher.doFinal(byteContent);
  344. // 2 对密文字节数组进行 转换为 HEX输出密文
  345. String cipherText = byte2hex(result);
  346. return cipherText;
  347. } catch (Exception ex) {
  348. logger.error(ex.getMessage(),ex);
  349. }
  350. return null;
  351. }
  352. /**
  353. * AES 解密操作
  354. *
  355. * @param content 密文
  356. * @param password 密码
  357. * @param iv 使用CBC模式,需要一个向量iv,可增加加密算法的强度
  358. * @return 明文
  359. */
  360. public static String decrypt(byte[] content, String password, String iv) {
  361. try {
  362. //创建密码器
  363. Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
  364. //密码key
  365. SecretKeySpec keySpec = new SecretKeySpec(password.getBytes("utf-8"),KEY_ALGORITHM);
  366. //向量iv
  367. IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes("utf-8"));
  368. //初始化为解密模式的密码器
  369. cipher.init(Cipher.DECRYPT_MODE,keySpec,ivParameterSpec);
  370. //执行操作
  371. byte[] result = cipher.doFinal(content);
  372. return new String(result,"utf-8");
  373. } catch (Exception ex) {
  374. logger.error(ex.getMessage(),ex);
  375. }
  376. return null;
  377. }
  378. /**
  379. * 字节数组转成16进制字符串,不转为大写
  380. * @param bytes
  381. * @return
  382. */
  383. public static String byte2hex(byte[] bytes) {
  384. // 一个字节的数
  385. StringBuffer sb = new StringBuffer(bytes.length * 2);
  386. String tmp = "";
  387. for (int n = 0; n < bytes.length; n++) {
  388. // 整数转成十六进制表示
  389. tmp = (Integer.toHexString(bytes[n] & 0XFF));
  390. if (tmp.length() == 1) {
  391. sb.append("0");
  392. }
  393. sb.append(tmp);
  394. }
  395. return sb.toString();
  396. }
  397. /*将hex字符串转换成字节数组 */
  398. public static byte[] hex2byte(String str) {
  399. if (str == null || str.length() < 2) {
  400. return new byte[0];
  401. }
  402. str = str.toLowerCase();
  403. int l = str.length() / 2;
  404. byte[] result = new byte[l];
  405. for (int i = 0; i < l; ++i) {
  406. String tmp = str.substring(2 * i, 2 * i + 2);
  407. result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
  408. }
  409. return result;
  410. }
  411. /**
  412. * Convert hex string to byte[]
  413. *
  414. * @param hexString the hex string
  415. * @return byte[]
  416. */
  417. public static byte[] hexStringToBytes(String hexString) {
  418. if (hexString == null || hexString.equals("")) {
  419. return null;
  420. }
  421. hexString = hexString.toUpperCase();
  422. int length = hexString.length() / 2;
  423. char[] hexChars = hexString.toCharArray();
  424. byte[] d = new byte[length];
  425. for (int i = 0; i < length; i++) {
  426. int pos = i * 2;
  427. d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
  428. }
  429. return d;
  430. }
  431. public static byte charToByte(char c) {
  432. return (byte)"0123456789ABCDEF".indexOf(c);
  433. }
  434. }