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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章