aes 定长 java
时间: 2023-08-29 12:08:18 浏览: 37
在 Java 中,AES 加密算法可以使用 javax.crypto 包中的类进行实现。AES 是一种分块加密算法,其加密和解密操作都需要一个固定长度的密钥。在 AES 加密算法中,密钥长度只能是 128 比特、192 比特或 256 比特,因此,密钥长度是固定的。
下面是一个 Java 实现的 AES 加密和解密的示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
public class AESExample {
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
byte[] key = "0123456789abcdef".getBytes("UTF-8");
byte[] encrypted = encrypt(plainText.getBytes("UTF-8"), key);
System.out.println("Encrypted text: " + Arrays.toString(encrypted));
byte[] decrypted = decrypt(encrypted, key);
System.out.println("Decrypted text: " + new String(decrypted, "UTF-8"));
}
public static byte[] encrypt(byte[] plainText, byte[] key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(plainText);
}
public static byte[] decrypt(byte[] cipherText, byte[] key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
return cipher.doFinal(cipherText);
}
}
```
在该示例代码中,密钥长度为 16 字节,即 128 比特。加密和解密操作使用的加密模式为 ECB,填充模式为 PKCS5Padding。加密后的密文长度与原始明文长度相同,因为 AES 是一种分块加密算法,加密后的密文长度是固定的。