前台调用crypto-js DES cbc模式下默认iV值加密,java后台解密

431 阅读1分钟

crypto-js前台DES cbc模式下默认iV值(iv值为空)加密,java后台调通过javax.crypto包解密

前台代码:

//DES加密
function encryptByDES(message, key,iv){
    var ivHex = CryptoJS.enc.Utf8.parse(iv);
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        iv:ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString();
}
//DES解密
function decryptByDES(ciphertext, key,iv){
    var keyHex = CryptoJS.enc.Utf8.parse(key);
    var ivHex = CryptoJS.enc.Utf8.parse(iv);
    var decrypted = CryptoJS.DES.decrypt({
        ciphertext: CryptoJS.enc.Hex.parse(ciphertext)
    }, keyHex, {
        iv:ivHex,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    var result_value = decrypted.toString(CryptoJS.enc.Utf8);
    return result_value;
}

后台代码:

package com.ideabank.util;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;

public class CBCUtil {

    /**
     * 偏移变量,固定占8位字节
     */
    /*private final static String IV_PARAMETER = "12345678";*/
    /* 默认密钥*/
    private static final String secretKey = "RTYV983423%$#!qw";
    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "DES";

    /**
     * 加密/解密算法-工作模式-填充模式
     * DES共有四种工作模式-->>ECB:电子密码本模式、CBC:加密分组链接模式、CFB:加密反馈模式、OFB:输出反馈模式
     */
    private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";

    /**
     * 默认编码
     */
    private static final String CHARSET = "utf-8";

    /**
     * 生成key
     *
     * @param password 密钥字符串
     * @return 密钥对象
     * @throws Exception
     */
    private static Key generateKey(String password) throws Exception {
        DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
        return keyFactory.generateSecret(dks);
    }

    /**
     * 加密字符串
     *
     * @param password 加密密码,长度不能够小于8位
     * @param data     待加密字符串
     * @return 加密后内容(十六进制字符串)
     */
    public static String encrypt(String data,String password, String IV_PARAMETER) {
        if (ParamValidater.isNull(data)) {
            return null;
        }
        if (ParamValidater.isNull(password)) {
            password=secretKey;
        }
        if(password.length() < 8){
            return null;
        }

        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            byte[] iv_value=new byte[8];
            if(ParamValidater.isNotNull(IV_PARAMETER)){
                iv_value=IV_PARAMETER.getBytes(CHARSET);
            }
            IvParameterSpec iv = new IvParameterSpec(iv_value);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] bytes = cipher.doFinal(data.getBytes(CHARSET));
            //return new String(Base64.getEncoder().encode(bytes));
            return byte2HexString(bytes);
        } catch (Exception e) {
           /* e.printStackTrace();*/
            return null;
        }
    }

    /**
     * 解密字符串
     *
     * @param password 解密密码,长度不能够小于8位
     * @param data     待解密字符串(十六进制字符串)
     * @return 解密后内容
     */
    public static String decrypt( String data,String password,String IV_PARAMETER) {
        if (ParamValidater.isNull(data)) {
            return null;
        }
        if (ParamValidater.isNull(password)) {
            password=secretKey;
        }
        if(password.length() < 8){
            return null;
        }
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
            byte[] iv_value=new byte[8];
            if(ParamValidater.isNotNull(IV_PARAMETER)){
                iv_value=IV_PARAMETER.getBytes(CHARSET);
            }
            IvParameterSpec iv = new IvParameterSpec(iv_value);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            byte[] bytes = hexStringToByteArray(data);
            /*  System.out.println(byte2HexString(cipher.doFinal(bytes)));*/
            return new String(cipher.doFinal(bytes), CHARSET);
            //return new String(cipher.doFinal(Base64.getDecoder().decode(data.getBytes(CHARSET))));
        } catch (Exception e) {
            /*e.printStackTrace();*/
            return null;
        }
    }

    /**
     * byte数组转十六进制
     *
     * @param bytes
     * @return
     */
    public static String byte2HexString(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        if (bytes != null) {
            for (Byte b : bytes) {
                hex.append(String.format("%02X", b.intValue() & 0xFF));
            }
        }
        return hex.toString();
    }

    /**
     * 十六进制转byte数组
     *
     * @param s
     * @return
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        try {
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                        + Character.digit(s.charAt(i + 1), 16));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data;
    }


    /**
     * 测试函数
     * @param args 参数
     * @date 2015年11月30日 下午3:02:07
     */
    public static void main(String[] args) throws Exception {
        String encryptData= encrypt("交管所内","RTYV983423%$#!qw","");
        System.out.println(encryptData);
        String data= decrypt(encryptData,"RTYV983423%$#!qw","");
        System.out.println("2617E750410D5FAEBB0A73BA95E8B0C8304CCC6532EEC4A8".length());
    

    }

}