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

随机数 + AES加密:
/**
     * 生成随机数
     * @param length
     * @return
     */
    private String getChar(int length) {
        char[] ss = new char[length];
        int i=0;
        while(i<length) {
            int f = (int) (Math.random()*3);
            if(f==0)
                ss[i] = (char) ('A'+Math.random()*26);
            else if(f==1)
                ss[i] = (char) ('a'+Math.random()*26);
            else
                ss[i] = (char) ('0'+Math.random()*10);
            i++;
        }
        String str = new String(ss);
        return str;
    }

    /**
     * 随机数 + AES加密
     * @param password
     * @return
     */
    private String aesEncode(String password) {
        String encodePassword = "";
        String key = "abcdef0123456789"; // 16位,可自由定义,长度必须为16
        String iv = "0123456789abcdef"; // 16位,可自由定义,长度必须为16
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NOPadding"); // 参数分别代表 算法名称/加密模式/数据填充方式
            int blockSize = cipher.getBlockSize();

            byte[] dataBytes = password.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);

            SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);

            String encode = new BASE64Encoder().encode(encrypted);
            //如果数据过长base64会自动添加换行符
            encode=encode.replaceAll(System.lineSeparator(), "");
            encodePassword = getChar(9)+encode; //随机数加加密后的密码
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encodePassword;
    }

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);
        }

猜你喜欢

转载自blog.csdn.net/pyy542718473/article/details/103808610