AES加密,前后端互解

2018-10-08 15:44 更新

應(yīng)用場景: 有兩個應(yīng)用系統(tǒng)a,b。其中a系統(tǒng)中某一部分導(dǎo)航功能需要跳轉(zhuǎn)至b系統(tǒng)(簡單的說就是a系統(tǒng)現(xiàn)在要把b系統(tǒng)中的所有功能包含進來,為了前期快速上線,采用js重定向跳轉(zhuǎn)實現(xiàn)),這里就涉及到a系統(tǒng)登錄后的權(quán)限要同步到b系統(tǒng),實現(xiàn)單點登錄。其中對于內(nèi)網(wǎng)用戶,采用了idm的單點登錄。但是針對外部用戶就采用了aes加密的方式驗證。 實現(xiàn)思路: 在登錄a系統(tǒng)的情況下,外部用戶點擊跳轉(zhuǎn)至b系統(tǒng)的時候免登錄,同步權(quán)限。這里是在跳轉(zhuǎn)時,前后端協(xié)商采用aes的加解密對該用戶進行校驗。

實現(xiàn)的核心代碼:

  1. <code class="language-html"><!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <!-- <script src="https://sellpow-html.oss-cn-beijing.aliyuncs.com/public/js/aes.js" rel="external nofollow" ></script> -->
  8. <script type="text/javascript" src="http://react.file.alimmdn.com/aes.js" rel="external nofollow" ></script>
  9. <body>
  10. <script>
  11. var key = CryptoJS.enc.Utf8.parse("cyh@201812345678");//密鑰為16字節(jié)
  12. var plaintText = 'cyh@123456789'; // 明文
  13. var encryptedData = CryptoJS.AES.encrypt(plaintText, key, {
  14. mode: CryptoJS.mode.ECB,
  15. padding: CryptoJS.pad.Pkcs7
  16. });
  17. console.log("加密前:"+plaintText);
  18. console.log("加密后:"+encryptedData.ciphertext.toString());
  19. encryptedData = encryptedData.ciphertext.toString();
  20. console.log("base64加密后:"+encryptedData);
  21. var encryptedHexStr = CryptoJS.enc.Hex.parse('5a6dcc986133465954e1072471f8d2e2');
  22. var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  23. var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
  24. mode: CryptoJS.mode.ECB,
  25. padding: CryptoJS.pad.Pkcs7
  26. });
  27. var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);
  28. console.log("解密后:"+decryptedStr);
  29. var pwd = "PCsUFtgog9/qpqmqXsuCRQ==";
  30. //加密服務(wù)端返回的數(shù)據(jù)
  31. var decryptedData = CryptoJS.AES.decrypt(pwd, key, {
  32. mode: CryptoJS.mode.ECB,
  33. padding: CryptoJS.pad.Pkcs7
  34. });
  35. console.log("解密服務(wù)端返回的數(shù)據(jù):"+decryptedStr);
  36. </script>
  37. </body>
  38. </html></code>

后端解密核心代碼:

  1. public class AccessHtmlFilter implements Filter {
  2. private static final Logger logger = Logger.getLogger(AccessHtmlFilter.class);
  3. private static String VENTOLKENID = "cyh@*srm#";
  4. //密鑰
  5. private static final String TOKEN_KEY = "cyh@201812345678";
  6. //算法
  7. private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
  8. ....
  9. public boolean judgeToken(String ventolkenid, String userId){
  10. Boolean b = false;
  11. String tokenid = VENTOLKENID.replace("*", userId);
  12. byte[] bt = parseHexStr2Byte(ventolkenid);
  13. Object encoded = Base64.encodeBase64String(bt);
  14. String decrypt = "";
  15. try {
  16. decrypt = aesDecrypt(encoded.toString(), TOKEN_KEY);
  17. } catch (Exception e) {
  18. return b;
  19. }
  20. System.out.println("解密后:" + decrypt);
  21. if(tokenid.equals(decrypt.substring(0, decrypt.indexOf("#")+1))){
  22. b = true;
  23. }
  24. return b;
  25. }
  26. /**
  27. * AES解密
  28. * @param encryptBytes 待解密的byte[]
  29. * @param decryptKey 解密密鑰
  30. * @return 解密后的String
  31. * @throws Exception
  32. */
  33. public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
  34. KeyGenerator kgen = KeyGenerator.getInstance("AES");
  35. kgen.init(128);
  36. Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
  37. cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
  38. byte[] decryptBytes = cipher.doFinal(encryptBytes);
  39. return new String(decryptBytes);
  40. }
  41. /**
  42. * 將base 64 code AES解密
  43. * @param encryptStr 待解密的base 64 code
  44. * @param decryptKey 解密密鑰
  45. * @return 解密后的string
  46. * @throws Exception
  47. */
  48. public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
  49. return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
  50. }
  51. /**
  52. * base 64 decode
  53. * @param base64Code 待解碼的base 64 code
  54. * @return 解碼后的byte[]
  55. * @throws Exception
  56. */
  57. public static byte[] base64Decode(String base64Code) throws Exception{
  58. return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
  59. }
  60. /**將二進制轉(zhuǎn)換成16進制
  61. * @param buf
  62. * @return
  63. */
  64. public String parseByte2HexStr(byte buf[]) {
  65. StringBuffer sb = new StringBuffer();
  66. for (int i = 0; i < buf.length; i++) {
  67. String hex = Integer.toHexString(buf[i] & 0xFF);
  68. if (hex.length() == 1) {
  69. hex = '0' + hex;
  70. }
  71. sb.append(hex.toUpperCase());
  72. }
  73. return sb.toString();
  74. }
  75. /**將16進制轉(zhuǎn)換為二進制
  76. * @param hexStr
  77. * @return
  78. */
  79. private byte[] parseHexStr2Byte(String hexStr) {
  80. if (hexStr.length() < 1)
  81. return null;
  82. byte[] result = new byte[hexStr.length()/2];
  83. for (int i = 0;i< hexStr.length()/2; i++) {
  84. int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
  85. int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
  86. result[i] = (byte) (high * 16 + low);
  87. }
  88. return result;
  89. }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號