文章目录
写了个新的前端项目,公司要求,账号密码这些必须是加密传输的;后端使用了
GCM
模式加密,前端是复制的一个以前项目的代码,原来是有写加密的,使用的是
CryptoJS
组件
CTR
模式加密的,但是这个组件里面没有
GCM
加密模式,找了半天,发现浏览器其实是自带加密的组件的
window.crypto
,使用这个组件就可以使用
GCM
模式加密,代码贴在下面,顺便
java
代码也贴出来了。
CryptoJS
看点进源码里面看了下只支持这几种模式
去官网看了下 https://cryptojs.gitbook.io/docs#hashing,也是说支持这几种,估计是浏览器都支持了,所以
CryptoJS
也就没有再更新了吧
前端加密测试
包含了完整的加密解密代码,可以拷过去直接用
<!DOCTYPEhtml><html><head><metacharset="UTF-8"/><title>加密小工具</title></head><body><textarearows="8"cols="40"id="content"></textarea><br><buttononclick="encrypt1()">加密</button><buttononclick="decrypt1()">解密</button><p>结果: <labelid='result'></label></p></body><scripttype="text/javascript">// 将字符串转换为字节数组functionstringToUint8Array(str){let arr =newUint8Array(str.length);for(let i =0; i < str.length; i++){
arr[i]= str.charCodeAt(i);}return arr;}// 导入密钥asyncfunctionimportKey(keyStr){const keyBytes =stringToUint8Array(keyStr);const key =await window.crypto.subtle.importKey('raw',
keyBytes,'AES-GCM',// 或者其他算法false,['encrypt','decrypt']);return key;}// 加密函数asyncfunctionencrypt(message, key, iv){let msgBuffer =newTextEncoder().encode(message);let ivBytes =stringToUint8Array(iv);let ciphertext =await window.crypto.subtle.encrypt({name:"AES-GCM",iv: ivBytes
},
key,
msgBuffer
);return ciphertext;}asyncfunctiondecrypt(base64Ciphertext, key, iv){// 将 Base64 字符串转换回 ArrayBufferlet ciphertext = window.atob(base64Ciphertext);let ciphertextBuffer =newUint8Array(ciphertext.length);for(let i =0; i < ciphertext.length; i++){
ciphertextBuffer[i]= ciphertext.charCodeAt(i);}let ivBytes =stringToUint8Array(iv);let plaintext =await window.crypto.subtle.decrypt({name:"AES-GCM",iv: ivBytes
},
key,
ciphertextBuffer.buffer
);// 将 ArrayBuffer 转换为字符串let decoder =newTextDecoder();return decoder.decode(plaintext);}let key;let ivStr;(async()=>{const keyStr ="你的密钥";//"29H3LCRC49SGFR0A";
ivStr ="iv信息";//"FBTR064AT3LCRF4E";
key =awaitimportKey(keyStr);const ciphertext =awaitencrypt("uIv86omN9Fp#", key, ivStr);
console.log("Encrypted:", ciphertext);})();functionencrypt1(){const txt = document.getElementById("content").value;encrypt(txt, key, ivStr).then((ciphertext)=>{
console.log("Encrypted:",btoa(String.fromCharCode(...newUint8Array(ciphertext))));
document.getElementById("result").innerText =btoa(String.fromCharCode(...newUint8Array(ciphertext)));});}functiondecrypt1(){const txt = document.getElementById("content").value;decrypt(txt, key, ivStr).then((plaintext)=>{
console.log("Decrypted:", plaintext);
document.getElementById("result").innerText = plaintext;});}</script></html>
Java加解密代码
要先引入一个包
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>1.77</version>
</dependency>
packagecom.yuanjy.sf04;importorg.bouncycastle.jce.provider.BouncyCastleProvider;importorg.springframework.util.StringUtils;importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importjavax.crypto.spec.IvParameterSpec;importjavax.crypto.spec.SecretKeySpec;importjava.net.URLDecoder;importjava.security.Security;importjava.util.Base64;publicclassGCMTest{privatestaticString key ="你的密钥";//"29H3LCRC49SGFR0A";privatestaticString ivParameter ="iv信息";//"FBTR064AT3LCRF4E";privatestaticIvParameterSpecIV;privatestaticfinalStringALGORITHMSTR="AES/GCM/NoPadding";publicstaticvoidmain(String[] args)throwsException{Security.addProvider(newBouncyCastleProvider());System.out.println(encrypt("admin", key));System.out.println(decrypt("yagZI4sMNgee5R/AXhdFCPAjF1k4"));}publicstaticStringdecrypt(String encrypt)throwsException{returnURLDecoder.decode(decrypt(encrypt, key),"UTF-8");}publicstaticStringdecrypt(String encryptStr,String decryptKey)throwsException{returndecryptByBytes(Base64.getDecoder().decode(encryptStr), decryptKey);}publicstaticStringdecryptByBytes(byte[] encryptBytes,String decryptKey)throwsException{byte[] iv = ivParameter.getBytes();IV=newIvParameterSpec(iv);KeyGenerator kgen =KeyGenerator.getInstance("AES");
kgen.init(128);Security.addProvider(newBouncyCastleProvider());Cipher cipher =Cipher.getInstance(ALGORITHMSTR,"BC");
cipher.init(Cipher.DECRYPT_MODE,newSecretKeySpec(decryptKey.getBytes(),"AES"),IV);byte[] decryptBytes = cipher.doFinal(encryptBytes);returnnewString(decryptBytes);}publicstaticStringencrypt(String content,String encryptKey)throwsException{returnBase64.getEncoder().encodeToString(encryptToBytes(content, encryptKey));}publicstaticbyte[]encryptToBytes(String content,String encryptKey)throwsException{byte[] iv = ivParameter.getBytes();IV=newIvParameterSpec(iv);KeyGenerator kgen =KeyGenerator.getInstance("AES");
kgen.init(128);Cipher cipher =Cipher.getInstance(ALGORITHMSTR,"BC");
cipher.init(Cipher.ENCRYPT_MODE,newSecretKeySpec(encryptKey.getBytes(),"AES"),IV);return cipher.doFinal(content.getBytes("utf-8"));}}
版权归原作者 三书yjy 所有, 如有侵权,请联系我们删除。