java openapi接口 aes加密
时间: 2023-11-18 19:53:52 浏览: 35
您好,关于Java OpenAPI接口的AES加密,可以使用Java自带的加密库javax.crypto来实现。具体步骤如下:
1. 导入javax.crypto库
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
```
2. 定义加密算法和密钥
```java
String algorithm = "AES";
String key = "1234567890123456"; // 密钥长度必须为16位
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
```
3. 创建加密器并进行加密
```java
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
```
其中,plainText为需要加密的明文字符串。
4. 将加密后的字节数组转换为Base64编码的字符串
```java
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
```
完整代码如下:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AesEncryptor {
public static void main(String[] args) throws Exception {
String algorithm = "AES";
String key = "1234567890123456"; // 密钥长度必须为16位
String plainText = "Hello, world!";
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println(encryptedText);
}
}
```