DES加密解密-CryptoJS与Java

DES加密解密-CryptoJS与Java

前端页面在往后台传递某些敏感数据时需要对数据进行加密,以提高安全性。但需要注意的是,前端加密和后端解密的算法应该保持一致,才能确保功能能正常使用,废话不多说直接上码。

CryptoJS

CryptoJS 点击这里

function encryptByDES(message, key) {
    var keyHex = CryptoJS.enc.Utf8.parse(key);      
    var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.toString();
}

function decryptByDES(ciphertext, key) {        
    var keyHex = CryptoJS.enc.Utf8.parse(key);      
    var decrypted = CryptoJS.DES.decrypt({
        ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
    }, keyHex, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });

    return decrypted.toString(CryptoJS.enc.Utf8);
}

Java

/**
 * DES加密
 * @param datasource
 * @return
 */
public String encode(String datasource){
    try{
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE));
        //创建一个密匙工厂,然后用它把DESKeySpec转换成
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        //Cipher对象实际完成加密操作
        Cipher cipher = Cipher.getInstance("DES");
        //用密匙初始化Cipher对象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        //现在,获取数据并加密
        byte[] temp = Base64.encodeBase64(cipher.doFinal(datasource.getBytes()));
        return IOUtils.toString(temp,"UTF-8");
    }catch(Throwable e){
        e.printStackTrace();
        return null;
    }
}

/**
 * DES解密
 * @return
 */
public String decode(String src) throws Exception {
    // DES算法要求有一个可信任的随机数源
    SecureRandom random = new SecureRandom();
    // 创建一个DESKeySpec对象
    DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE));
    // 创建一个密匙工厂
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
    // 将DESKeySpec对象转换成SecretKey对象
    SecretKey securekey = keyFactory.generateSecret(desKey);
    // Cipher对象实际完成解密操作
    Cipher cipher = Cipher.getInstance("DES");
    // 用密匙初始化Cipher对象
    cipher.init(Cipher.DECRYPT_MODE, securekey, random);
    // 真正开始解密操作
    return IOUtils.toString(cipher.doFinal(Base64.decodeBase64(src)),"UTF-8");
}

全部代码下载地址:Github

你可能感兴趣的:(java)