本文实例讲述了JS使用插件cryptojs进行加密解密数据。分享给大家供大家参考,具体如下:
Testing websocketsvar key = 'BOTWAVEE';
//CBC模式加密
function encryptByDESModeCBC(message) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var ivHex = CryptoJS.enc.Utf8.parse(key);
encrypted = CryptoJS.DES.encrypt(message, keyHex, {
iv:ivHex,
mode: CryptoJS.mode.CBC,
padding:CryptoJS.pad.Pkcs7
}
);
return encrypted.ciphertext.toString();
}
//CBC模式解密
function decryptByDESModeCBC(ciphertext2) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var ivHex = CryptoJS.enc.Utf8.parse(key);
// direct decrypt ciphertext
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Hex.parse(ciphertext2)
}, keyHex, {
iv:ivHex,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
//DES ECB模式加密
function encryptByDESModeEBC(message){
var keyHex = CryptoJS.enc.Utf8.parse(key);
var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.ciphertext.toString();
}
//DES ECB模式解密
function decryptByDESModeEBC(ciphertext){
var keyHex = CryptoJS.enc.Utf8.parse(key);
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Hex.parse(ciphertext)
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
var result_value = decrypted.toString(CryptoJS.enc.Utf8);
return result_value;
}
function test(){
var source = $("#source").val();
var cc = encryptByDESModeEBC(CryptoJS.enc.Utf8.parse(source));
$("#target").val(cc);
}
function test1(){
var source = $("#sourceS").val();
var dd = decryptByDESModeEBC(source);
$("#jiemi").val(dd);
}
加密前:
加密后:
密文:
解密后:
PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:
在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:http://tools.jb51.net/password/hash_md5_sha
希望本文所述对大家JavaScript程序设计有所帮助。