crypto.js加密傳輸

前端頁面javascript

<!DOCTYPE html>
<html>html

<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/crypto-js.js"></script>
<script>
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
});java

return decrypted.toString(CryptoJS.enc.Utf8);
}
$(function() {
var pwd = encryptByDES("crd", "12345678");
$("#aaa").val(pwd);
$("#pwd").val(decryptByDES(pwd,"12345678"));
});
</script>
</head>jquery

<body>算法

<input id="aaa" value="" />
<input id="pwd" value="" />
</body>dom

</html>spa

 

 

後臺:code

/**
* DES解密
*
* @param secretData
* 密碼字符串
* @param secretKey
* 解密密鑰
* @return 原始字符串
* @throws Exception
*/
public String decryption(String secretData, String secretKey) throws Exception {
// DES算法要求有一個可信任的隨機數源
SecureRandom random = new SecureRandom();
// 建立一個DESKeySpec對象
DESKeySpec desKey = new DESKeySpec(secretKey.getBytes("UTF-8"));
// 建立一個密匙工廠
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(secretData.getBytes())),"UTF-8");htm

}

 

 

調用:

System.out.println("=========" + decryption("tzZ2WRdJ32o=", "12345678"));

 

注意密匙須要八位以上的因此這裏用了1到8,密匙能夠自定義

相關文章
相關標籤/搜索