js aes加密 java解密
时间: 2023-07-12 22:31:08 浏览: 69
好的,这是一个常见的加密解密场景。你可以使用以下步骤进行加密和解密:
1. 在 JavaScript 中使用 AES 加密文本,例如使用 CryptoJS 库。
```javascript
var key = CryptoJS.enc.Utf8.parse("Secret Passphrase"); // 使用加密密钥
var iv = CryptoJS.enc.Utf8.parse("Initialization Vector"); // 使用初始化向量
var encrypted = CryptoJS.AES.encrypt("Hello World!", key, { iv: iv }); // 加密数据
var encryptedText = encrypted.toString();
```
2. 将加密后的文本发送到后端,使用 Java 进行解密,例如使用 Bouncy Castle 库。
```java
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
public class AesUtil {
public static String decrypt(String encryptedText, String key, String iv) {
Security.addProvider(new BouncyCastleProvider());
try {
byte[] keyBytes = key.getBytes("UTF-8");
byte[] ivBytes = iv.getBytes("UTF-8");
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes, "UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
```
3. 在 Java 中调用 `AesUtil.decrypt()` 方法进行解密。
```java
String encryptedText = "U2FsdGVkX1+4kg4xJ0TZx8M1m3B0i3WrJHv5QSwz5vU=";
String key = "Secret Passphrase";
String iv = "Initialization Vector";
String decryptedText = AesUtil.decrypt(encryptedText, key, iv);
System.out.println(decryptedText); // 输出 "Hello World!"
```
请注意,这只是一个基本的示例,你需要根据你的具体情况进行调整。此外,确保保护好你的加密密钥和初始化向量,以确保安全性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)