Java已有AES加解密,现需要前端Javascript加密调接口,返回的需要解密目前互通不了,报错-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

Java已有AES加解密,现需要前端Javascript加密调接口,返回的需要解密目前互通不了,报错

因为相信,所以看见。 2020-05-27 12:59:51 49

"

目前Javascript使用'crypto-js'包。

前后台可以自己跑通加解密,但是, 无法互通。

针对对象{}加密……网上的方案,已经尝试了4天左右了,还没成功,请指导。

无思路,无报错。

Java

package com.pactera.sms.foundbase.util;


import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESUtils {
    private static final String IV_STRING = "16-Bytes--String";
    /**
     * 加密方法
     * 
     * @param seed
     *            密钥
     * @param clearText
     *            明文
     * @return
     */
    public static String encrypt(String seed, String clearText) {
        byte[] result = null;
        try {
            byte[] rawkey = getRawKey(seed.getBytes());
            result = encrypt(rawkey, clearText.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String content = toHex(result);
        return content;
    }

    /**
     * 解密方法
     * 
     * @param seed
     * @param encrypted
     * @return
     */
    public static String decrypt(String seed, String encrypted) {
        byte[] rawKey;
        try {
            rawKey = getRawKey(seed.getBytes());
            byte[] enc = toByte(encrypted);
            byte[] result = decrypt(rawKey, enc);
            String coentn = new String(result);
            return coentn;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    private static byte[] getRawKey(byte[] seed) throws Exception {
        
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(seed);
        kgen.init(128, sr);
        SecretKey sKey = kgen.generateKey();
        byte[] raw = sKey.getEncoded();
        return raw;
    }

    private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
        byte[] initParam = IV_STRING.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(
                initParam));
        byte[] encrypted = cipher.doFinal(clear);
        return encrypted;
    }

    private static byte[] decrypt(byte[] raw, byte[] encrypted)
            throws Exception {
        byte[] initParam = IV_STRING.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(
                initParam));
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    public static String toHex(String txt) {
        return toHex(txt.getBytes());
    }

    public static String fromHex(String hex) {
        return new String(toByte(hex));
    }

    public static byte[] toByte(String hexString) {
        int len = hexString.length() / 2;
        byte[] result = new byte[len];
        for (int i = 0; i < len; i++)
            result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
                    16).byteValue();
        return result;
    }

    public static String toHex(byte[] buf) {
        if (buf == null)
            return "";
        StringBuffer result = new StringBuffer(2 * buf.length);
        for (int i = 0; i < buf.length; i++) {
            appendHex(result, buf[i]);
        }
        return result.toString();
    }

    private static void appendHex(StringBuffer sb, byte b) {
        final String HEX = "0123456789ABCDEF";
        sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
    }
}

32位的key

Javascript

import CryptoJS from 'crypto-js';
// 加密方法
export function Encrypt(data, key) {
    key = handleAccountParam(key);
    key = CryptoJS.enc.Utf8.parse(key);
    var iv = CryptoJS.enc.Utf8.parse('16-Bytes--String');
    var encrypted = CryptoJS.AES.encrypt(JSON.stringify(data), key,
        {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
    return encrypted.toString();
}

// 解密方法
export function Decrypt(data, key) {
    key = handleAccountParam(key);
    key = CryptoJS.enc.Utf8.parse(key);
    var iv = CryptoJS.enc.Utf8.parse('16-Bytes--String');
    var decrypted = CryptoJS.AES.decrypt(data, key,
        {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
    var decryptedData = JSON.parse(decrypted.toString(CryptoJS.enc.Utf8));
    return decryptedData;
}

export function handleAccountParam(str) {
    if (str.length < 16) {
        let length = 16 - str.length;
        for (var i = 0; i < length; i++) {
            str += 0;
        }
    } else if (str.length > 16) {
        str = str.slice(0, 16)
    }
    return str;
}
"
前端开发 JavaScript Java 数据安全/隐私保护
分享到
取消 提交回答
全部回答(1)
  • 因为相信,所以看见。
    2020-05-27 16:23:23

    "

    AES-128-CBC加解密,紧紧抓住两个关键点:加密用的key、iv即可。

    后台加密用的key可能进行一系列的转化,前端如果想对调,也需要进行一致的转化。

    所以,如果调不通的话,看看后台对key、iv进行了什么处理了吧

    ######

    加密完的数据一般是二进制数组,不要直接toString,需要使用base64编码一下。
    解密的时候base64解码再解密

    替换一个JS那边的参数试试

    {
                                iv: iv,
                                mode: CryptoJS.mode.CBC,
                                keySize: 256 / 32,
                                padding: CryptoJS.pad.Pkcs7
    }
    ######

    js 测试链接: https://blog.zhengxianjun.com...

    package com.xxxxx;
    
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    
    import org.apache.commons.codec.binary.Base64;
    
    
    /*******************************************************************************
     * AES加解密算法
     *
     * @author jueyue
     *
    
    加密用的Key 可以用26个字母和数字组成,最好不要用保留字符,虽然不会错,至于怎么裁决,个人看情况而定
    此处使用AES-128-CBC加密模式,key需要为16位。
     */
    
    class AES {
    
        // 加密
        public static String Encrypt(String sSrc, String sKey) throws Exception {
            if (sKey == null) {
                System.out.print("Key为空null");
                return null;
            }
            // 判断Key是否为16位
            if (sKey.length() != 16) {
                System.out.print("Key长度不是16位");
                return null;
            }
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
            IvParameterSpec iv = new IvParameterSpec(sKey.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes());
    
            return Base64.encodeBase64String(encrypted);//此处使用BAES64做转码功能,同时能起到2次加密的作用。
        }
    
        // 解密
        public static String Decrypt(String sSrc, String sKey) throws Exception {
            try {
                // 判断Key是否正确
                if (sKey == null) {
                    System.out.print("Key为空null");
                    return null;
                }
                // 判断Key是否为16位
                if (sKey.length() != 16) {
                    System.out.print("Key长度不是16位");
                    return null;
                }
                byte[] raw = sKey.getBytes("ASCII");
                SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                IvParameterSpec iv = new IvParameterSpec(sKey.getBytes());
                cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
                byte[] encrypted1 = Base64.decodeBase64(sSrc);//先用bAES64解密
                try {
                    byte[] original = cipher.doFinal(encrypted1);
                    String originalString = new String(original);
                    return originalString;
                } catch (Exception e) {
                    System.out.println(e.toString());
                    return null;
                }
            } catch (Exception ex) {
                System.out.println(ex.toString());
                return null;
            }
        }
    }
    
    
    public class Main {
        public static void main(String[] args) {
            String username = "administrator";
            String privateKey = "AFXWmoyuZ84Hq3Wv";
    
            String time = "1482806052";
            String nonce = "DpVXpxd5";
            String accessToken = "ZE1l0IteNM9mRSACFYwtT9VSaHMMkFdJ";
    
            try {
                String usernameHash = AES.Encrypt(username, privateKey);
                //print :   b8WQz3wr/e7G5KsI46tdaA==
                System.out.println(usernameHash);
    
                String decodeUsername = AES.Decrypt(usernameHash, privateKey);
                System.out.println(decodeUsername);
    
                //api token
                String content = usernameHash + accessToken + time + nonce;
                String apiToken = AES.Encrypt(content, privateKey);
                System.out.println(apiToken);
    
            } catch (Exception e){
                System.out.println(e.toString());
    
            }
        }
    }
    
    "
    0 0
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题