如何使用CryptoJS配合Java進行AES加密和解密

注意前端

1. PKCS5PaddingPKCS7Padding是同樣的java

2. 加密時使用的key和iv要轉換成base64格式後端

 

1、前端函數

1.函數加密

    function encrypt (msg, key, iv) {
        return  CryptoJS.AES.encrypt(msg,  key, {
            iv: iv,
            padding: CryptoJS.pad.Pkcs7,
            mode: CryptoJS.mode.CBC
        });
    }


    function decrypt (cipherText, key, iv) {
        return  CryptoJS.AES.decrypt({ ciphertext: cipherText }, key, {
            iv: iv,
            padding: CryptoJS.pad.Pkcs7,
            mode: CryptoJS.mode.CBC

        });
    }

 

2. 示例spa

            var key =    CryptoJS.enc.Base64.parse('ZGIyMTM5NTYxYzlmZTA2OA==');
            var iv =    CryptoJS.enc.Base64.parse('ZGIyMTM5NTYxYzlmZTA2OA==');

            var encrypted = encrypt('Hello World', key, iv);
            var cipherText = encrypted.ciphertext.toString();
            //java 使用 34439a96e68b129093105b67de81c0fc
            console.log(cipherText);

            // 拿到字符串類型的密文須要先將其用Hex方法parse一下
            var cipherTextHexStr = CryptoJS.enc.Hex.parse(cipherText);

            // 將密文轉爲Base64的字符串
            // 只有Base64類型的字符串密文才能對其進行解密
            var cipherTextBase64Str = CryptoJS.enc.Base64.stringify(cipherTextHexStr);

            //下面三種解密均可以
            var decrypted = CryptoJS.AES.decrypt(cipherTextBase64Str, key, {
                iv: iv,
                padding: CryptoJS.pad.Pkcs7,
                mode: CryptoJS.mode.CBC
            });

            decrypted = decrypt(CryptoJS.enc.Base64.parse(cipherTextBase64Str), key, iv);
            decrypted = decrypt(cipherTextHexStr, key, iv);

            console.log(decrypted.toString(CryptoJS.enc.Utf8));
            

 

 

2、後端code

1.函數blog

    public static byte[] AES_CBC_Decrypt(byte[] data, byte[] key, byte[] iv) throws Exception{
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE, key, iv);
        return cipher.doFinal(data);
    }

    private static Cipher getCipher(int mode, byte[] key, byte[] iv) throws Exception{
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//由於AES的加密塊大小是128bit(16byte), 因此key是12八、19二、256bit無關 //System.out.println("cipher.getBlockSize(): " + cipher.getBlockSize());
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); cipher.init(mode, secretKeySpec, new IvParameterSpec(iv)); return cipher; }

 

2.示例ip

        //傳給crypto的key、iv要使用base64格式
        //ZGIyMTM5NTYxYzlmZTA2OA==
        byte[] bytes = "db2139561c9fe068".getBytes();
        String base64Str = Base64.encodeBase64String(bytes);
        System.out.println(base64Str);

        String crypto = "34439a96e68b129093105b67de81c0fc";
        data = Hex.decodeHex(crypto.toCharArray());
        s = AES_CBC_Decrypt(data, bytes, bytes);
        System.out.println(new String(s));
相關文章
相關標籤/搜索