Java后台加密js前端解密(基于AES和DES)

随机数 + AES加密:
/**
     * 生成随机数
     * @param length
     * @return
     */
    private String getChar(int length) {
        char[] ss = new char[length];
        int i=0;
        while(i

DES加密:

/**
     * DES加密
     * @param password
     * @param key 密钥,密钥长度必须大于8位
     * @return
     */
    private String desEncode(String password,String key) {
        if (key == null || "".equals(key) || key.length() < 8) { //如果没密钥或者密钥长度小于8,则给一个默认密钥
            key = "0123456789abcdef";
        }
        String encodePassword = "";
        try {
            // 生成一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            // 从密钥数据创建DESKeySpec对象
            DESKeySpec dks = new DESKeySpec(key.getBytes("UTF-8"));
            // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(dks);
            // Cipher对象实际完成加密操作
            Cipher cipher = Cipher.getInstance("DES");
            // 用密钥初始化Cipher对象
            cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
            encodePassword = new BASE64Encoder().encode(cipher.doFinal(password.getBytes("UTF-8")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encodePassword;
    }

JS AES解密:

function aesDecode(encodePassword) {
            var d = encodePassword.substr(9);
            var key = CryptoJS.enc.Latin1.parse('abcdef0123456789');//需要与后台保持一致
            var iv = CryptoJS.enc.Latin1.parse('0123456789abcdef');//需要与后台保持一致
            var decrypted = CryptoJS.AES.decrypt(d, key, {
                iv : iv,
                padding : CryptoJS.pad.ZeroPadding
            });
            var password = decrypted.toString(CryptoJS.enc.Utf8);
            return password;
        }

DES解密:

function desDecode(ciphertext, key) {//key需和后台保持一致
            if(!key || key.length < 8) {
                key = "0123456789abcdef";
            }
            var keyHex = CryptoJS.enc.Utf8.parse(key);
            // direct decrypt ciphertext
            var decrypted = CryptoJS.DES.decrypt({
                ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
            }, keyHex, {
                mode: CryptoJS.mode.ECB,
                padding: CryptoJS.pad.Pkcs7
            });
            console.log(decrypted.toString(CryptoJS.enc.Utf8))
            return decrypted.toString(CryptoJS.enc.Utf8);
        }

 

你可能感兴趣的:(Java)