Javascript前端和JAVA后端对加密库的处理实例

时间:2022-12-28 21:08:15

前端加密

Javascript的加解密有开源的库,http://www.oschina.net/p/crypto-js/

如下是具体的使用例子

<!DOCTYPE html>

<html lang="zh-cn">

<head>

<meta charset="utf-8"/>

<meta name="viewport" content="width=device-width, initial-scale=1" />

<script src="aes_1.js"></script> //引入的js文件在该链接中:https://github.com/hellobajie/AES-of-JavaScript

</head>

<body>

<script type="text/javascript" >

//16位

var pwd="abcd2016_-=00_X_";

function Decrypt(word){ 

var encryptedHexStr = CryptoJS.enc.Hex.parse(word);

var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);

console.log(srcs);

var decrypt = CryptoJS.AES.decrypt(srcs, key, { iv: iv,mode:CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7});

var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);

return decryptedStr.toString();

}

function Encrypt(word){

var key = CryptoJS.enc.Utf8.parse(pwd); 

var iv  = CryptoJS.enc.Utf8.parse(pwd); 

var srcs = CryptoJS.enc.Utf8.parse(word);

var encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv,mode:CryptoJS.mode.CBC,padding: CryptoJS.pad.Pkcs7});

srcs = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

return srcs ;

}  

var mm = Encrypt('DEMO');

console.log(mm)   

var jm = Decrypt(mm);

console.log(jm)

</script>

如果使用typescript可以在这找到其和ts集成的定义文件

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/36d40a63a05b5cb3413737fbdf7c9a2a26f211fd/crypto-js/crypto-js.d.ts

后端的java处理

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.util.Arrays;

String pwd = "abcd2016_-=00_X_";
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] raw = pwd.getBytes("utf-8");
SecretKey secretKey = new SecretKeySpec(raw, "AES");
System.out.println("密钥的长度为:" + secretKey.getEncoded().length);
Base64 b64 = new Base64();

encrypt = b64.decode(b64.encodeToString("DEMO"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(raw));//使用解密模式初始化 密钥
byte[] decrypt = cipher.doFinal(encrypt);
System.out.println("解密后:" + new String(decrypt));

 

如果,可以在前端和后端进行各种加密的处理,或把加密的信息在前后端之间交换.