一、前端
1、使用npm下载CryptoJS
npm install crypto-js
2、代码
const CryptoJS = require('crypto-js');
// 密钥
const secretKey = '1F74B0E91C7E403AACB89ED4C4D9FD2A';
// 初始向量(IV),必须为128位或256位
const iv = '1234567890123456';
/**
* 解密函数
* @param encodingText 加密的密文
* @returns {*} 解密后的字符串
*/
function decoding(encodingText) {
return CryptoJS.AES.decrypt(encodingText, CryptoJS.enc.Utf8.parse(secretKey), {
iv: CryptoJS.enc.Utf8.parse(iv),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString(CryptoJS.enc.Utf8);
}
/**
* 加密函数
* @param content 要加密的字符串
* @returns {*} 密文
*/
function encoding (content) {
return CryptoJS.AES.encrypt(content, CryptoJS.enc.Utf8.parse(secretKey), {
iv: CryptoJS.enc.Utf8.parse(iv),
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}).toString();
}
二、后端
1、使用在pom.xml中添加依赖
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.68</version>
</dependency>
2、代码
package demo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;
public class EncryptionExample {
private static final String secretKey = "1F74B0E91C7E403AACB89ED4C4D9FD2A"; // 密钥
private static final String iv = "1234567890123456"; // 初始向量(IV),必须为128位或256位
static {
Security.addProvider(new BouncyCastleProvider());
}
public static String encoding(String plaintext) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decoding(String encryptedData) throws Exception {
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
public static void main(String[] args) throws Exception {
String str = "hello world";
System.out.println(encoding(str));
}
}