AES加密,前后端互解

2018-10-08 15:44 更新

应用场景: 有两个应用系统a,b。其中a系统中某一部分导航功能需要跳转至b系统(简单的说就是a系统现在要把b系统中的所有功能包含进来,为了前期快速上线,采用js重定向跳转实现),这里就涉及到a系统登录后的权限要同步到b系统,实现单点登录。其中对于内网用户,采用了idm的单点登录。但是针对外部用户就采用了aes加密的方式验证。 实现思路: 在登录a系统的情况下,外部用户点击跳转至b系统的时候免登录,同步权限。这里是在跳转时,前后端协商采用aes的加解密对该用户进行校验。

实现的核心代码:

<code class="language-html"><!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Title</title>  

  
</head>  

  
<!-- <script src="https://sellpow-html.oss-cn-beijing.aliyuncs.com/public/js/aes.js" rel="external nofollow" ></script>  --> 
<script type="text/javascript" src="http://react.file.alimmdn.com/aes.js" rel="external nofollow" ></script>
<body>
<script>
    var key = CryptoJS.enc.Utf8.parse("cyh@201812345678");//密钥为16字节

  
    var plaintText = 'cyh@123456789'; // 明文  

  
    var encryptedData = CryptoJS.AES.encrypt(plaintText, key, {  
        mode: CryptoJS.mode.ECB,  
        padding: CryptoJS.pad.Pkcs7  
    });  

  
    console.log("加密前:"+plaintText);  
    console.log("加密后:"+encryptedData.ciphertext.toString());   

  
    encryptedData = encryptedData.ciphertext.toString();  

  
    console.log("base64加密后:"+encryptedData);
    var encryptedHexStr = CryptoJS.enc.Hex.parse('5a6dcc986133465954e1072471f8d2e2');  
    var encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr);  

  
    var decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {  
        mode: CryptoJS.mode.ECB,  
        padding: CryptoJS.pad.Pkcs7  
    });  

  
    var decryptedStr = decryptedData.toString(CryptoJS.enc.Utf8);  

  
    console.log("解密后:"+decryptedStr);    

      
     var pwd = "PCsUFtgog9/qpqmqXsuCRQ==";  
    //加密服务端返回的数据  
    var decryptedData = CryptoJS.AES.decrypt(pwd, key, {  
        mode: CryptoJS.mode.ECB,  
        padding: CryptoJS.pad.Pkcs7  
    });  

      
    console.log("解密服务端返回的数据:"+decryptedStr);  

  
</script>  
</body>  
</html></code>

后端解密核心代码:

public class AccessHtmlFilter implements Filter {
    private static final Logger logger = Logger.getLogger(AccessHtmlFilter.class);
    private static String  VENTOLKENID = "cyh@*srm#";
    //密钥
    private static final String  TOKEN_KEY = "cyh@201812345678";
    //算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
....
    public boolean judgeToken(String ventolkenid, String userId){
        Boolean b = false;
        String tokenid = VENTOLKENID.replace("*", userId);
        byte[] bt = parseHexStr2Byte(ventolkenid);
        Object encoded = Base64.encodeBase64String(bt);
        String decrypt = "";
        try {
            decrypt = aesDecrypt(encoded.toString(), TOKEN_KEY);
        } catch (Exception e) {
            return b;
        }
        System.out.println("解密后:" + decrypt);
        if(tokenid.equals(decrypt.substring(0, decrypt.indexOf("#")+1))){
            b = true;
        }
        return b;
    }

    

    
     /** 
     * AES解密 
     * @param encryptBytes 待解密的byte[] 
     * @param decryptKey 解密密钥 
     * @return 解密后的String 
     * @throws Exception 
     */  
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {  
        KeyGenerator kgen = KeyGenerator.getInstance("AES");  
        kgen.init(128);  
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);  
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));  
        byte[] decryptBytes = cipher.doFinal(encryptBytes);  
        return new String(decryptBytes);  
    }  

  
    /** 
     * 将base 64 code AES解密 
     * @param encryptStr 待解密的base 64 code 
     * @param decryptKey 解密密钥 
     * @return 解密后的string 
     * @throws Exception 
     */  
    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {  
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);  
    }  
    /** 
     * base 64 decode 
     * @param base64Code 待解码的base 64 code 
     * @return 解码后的byte[] 
     * @throws Exception 
     */  
    public static byte[] base64Decode(String base64Code) throws Exception{  
        return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);  
    }  

  
    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    public String parseByte2HexStr(byte buf[]) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < buf.length; i++) {
                    String hex = Integer.toHexString(buf[i] & 0xFF);
                    if (hex.length() == 1) {
                            hex = '0' + hex;
                    }
                    sb.append(hex.toUpperCase());
            }
            return sb.toString();
    }

    

    
    /**将16进制转换为二进制
     * @param hexStr
     * @return
     */
    private byte[] parseHexStr2Byte(String hexStr) {
            if (hexStr.length() < 1)
                    return null;
            byte[] result = new byte[hexStr.length()/2];
            for (int i = 0;i< hexStr.length()/2; i++) {
                    int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
                    int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
                    result[i] = (byte) (high * 16 + low);
            }
            return result;
    }

    
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号