}
let srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
});
return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}
/**
1. AES 解密 :字符串 key iv 返回base64
2. 3. @return {string}
*/
export function Decrypt(word, keyStr, ivStr) {
let key = KEY;
let iv = IV;
if (keyStr) {
key = CryptoJS.enc.Utf8.parse(keyStr);
iv = CryptoJS.enc.Utf8.parse(ivStr);
}
let base64 = CryptoJS.enc.Base64.parse(word);
let src = CryptoJS.enc.Base64.stringify(base64);
let decrypt = CryptoJS.AES.decrypt(src, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.ZeroPadding
});
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
三、前端页面引入并加密数据
import {Encrypt} from ‘…/…/secrt.js’
//text为需要加密的内容
var userId= Encrypt(text);
四、后端解密数据
1.pom引用
2.创建工具类
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;public class SecretUtil {
/***
* key和iv值可以随机生成,确保与前端的key,iv对应
*/
private static String KEY = “abcdefgh12345678”;
private static String IV = “12345678abcdefgh”;/***
* 加密
*
* @param data 要加密的数据
* @return encrypt
*/
public static String encrypt(String data) {
return encrypt(data, KEY, IV);
}
/**** 解密
* @param data 要解密的数据
*/
public static String desEncrypt(String data) {
return desEncrypt(data, KEY, IV);
}/**
* 加密方法
*/
private static String encrypt(String data, String key, String iv) {
try {
// "算法/模式/补码方式"NoPadding PkcsPadding
Cipher cipher = Cipher.getInstance(“AES/CBC/NoPadding”);
int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes();
int plaintextLength = dataBytes.length;
if (plaintextLength % blockSize != 0) {
plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
}
byte[] plaintext = new byte[plaintextLength];
System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), “AES”);
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);return new Base64().encodeToString(encrypted);
} catch (Exception e) {
最后
面试题千万不要死记,一定要自己理解,用自己的方式表达出来,在这里预祝各位成功拿下自己心仪的offer。
这里预祝各位成功拿下自己心仪的offer。
[外链图片转存中…(img-azMH8KCP-1720094266456)]
[外链图片转存中…(img-IdHsueT2-1720094266458)]
[外链图片转存中…(img-sbqKfeyL-1720094266459)]
[外链图片转存中…(img-bkKDZBQT-1720094266460)]