前后端分离API接口如何加密 —— AES加密方案
生活随笔
收集整理的這篇文章主要介紹了
前后端分离API接口如何加密 —— AES加密方案
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
場(chǎng)景還原:頁(yè)面中需要展示手機(jī)號(hào),身份證號(hào),因?yàn)槭乔昂蠖朔蛛x,所有接口API地址有可能暴露,這樣不懷好意的人可以拿到個(gè)人敏感信息
解決方案:
1. 敏感信息加掩碼,例如:接口返回130**12這樣的手機(jī)號(hào)。弊端:在有表單中無(wú)法實(shí)現(xiàn)這種方案。
2. 后端加密,前端解密的方式(本文采用的方式),前后端統(tǒng)一加密方案,salt字符串等信息。弊端:前端js無(wú)法做到高級(jí)加密,salt可以被查到,但是成本相對(duì)較高。
后臺(tái)加密工具類
package org.jeecg.modules.system.util;import org.apache.commons.codec.binary.Base64;import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec;public class AesUtils {private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";/*** 加密** @param content* @param key* @return*/public static String encrypt(String content, String key) {try {//獲得密碼的字節(jié)數(shù)組byte[] raw = key.getBytes();//根據(jù)密碼生成AES密鑰SecretKeySpec skey = new SecretKeySpec(raw, "AES");//根據(jù)指定算法ALGORITHM自成密碼器Cipher cipher = Cipher.getInstance(ALGORITHMSTR);//初始化密碼器,第一個(gè)參數(shù)為加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二個(gè)參數(shù)為生成的AES密鑰cipher.init(Cipher.ENCRYPT_MODE, skey);//獲取加密內(nèi)容的字節(jié)數(shù)組(設(shè)置為utf-8)不然內(nèi)容中如果有中文和英文混合中文就會(huì)解密為亂碼byte[] byte_content = content.getBytes("utf-8");//密碼器加密數(shù)據(jù)byte[] encode_content = cipher.doFinal(byte_content);//將加密后的數(shù)據(jù)轉(zhuǎn)換為字符串返回return Base64.encodeBase64String(encode_content);} catch (Exception e) {e.printStackTrace();return null;}}/*** 解密** @param encryptStr* @param decryptKey* @return*/public static String decrypt(String encryptStr, String decryptKey) {try {//獲得密碼的字節(jié)數(shù)組byte[] raw = decryptKey.getBytes();//根據(jù)密碼生成AES密鑰SecretKeySpec skey = new SecretKeySpec(raw, "AES");//根據(jù)指定算法ALGORITHM自成密碼器Cipher cipher = Cipher.getInstance(ALGORITHMSTR);//初始化密碼器,第一個(gè)參數(shù)為加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二個(gè)參數(shù)為生成的AES密鑰cipher.init(Cipher.DECRYPT_MODE, skey);//把密文字符串轉(zhuǎn)回密文字節(jié)數(shù)組byte[] encode_content = Base64.decodeBase64(encryptStr);//密碼器解密數(shù)據(jù)byte[] byte_content = cipher.doFinal(encode_content);//將解密后的數(shù)據(jù)轉(zhuǎn)換為字符串返回return new String(byte_content, "utf-8");} catch (Exception e) {e.printStackTrace();return null;}}}
前端解密
{title: '聯(lián)系方式',align: 'center',width:100,dataIndex: 'phone',customRender: function(phone,record) {const key = CryptoJS.enc.Utf8.parse(record.key);let tel = CryptoJS.AES.decrypt(phone,key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});tel = tel.toString(CryptoJS.enc.Utf8)return tel;}},總結(jié)
以上是生活随笔為你收集整理的前后端分离API接口如何加密 —— AES加密方案的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 随身wifi挑选要注意哪些问题才能避免上
- 下一篇: 剑指offer算法题028:数组中出现次