aes加密内容不定长_如何将一个字符串加密成固定或者定长字符串,并解密
时间: 2024-04-22 07:23:18 浏览: 304
AES.rar_AES_AES basic_aes text_decryptAES
5星 · 资源好评率100%
如果要将一个字符串加密成固定或者定长的字符串,可以使用AES加密算法和填充模式。常用的填充模式有PKCS5Padding和PKCS7Padding。这里以Java语言为例,演示如何将一个字符串加密成定长字符串,并解密。
加密代码:
```
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;
public class AesUtil {
private static final String ALGORITHM = "AES";
public static String encrypt(String data, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(data.getBytes());
byte[] iv = cipher.getIV();
byte[] result = new byte[iv.length + encrypted.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(encrypted, 0, result, iv.length, encrypted.length);
return Base64.getEncoder().encodeToString(result);
}
public static String decrypt(String encryptedData, String key) throws Exception {
byte[] encrypted = Base64.getDecoder().decode(encryptedData);
byte[] iv = Arrays.copyOfRange(encrypted, 0, 16);
byte[] data = Arrays.copyOfRange(encrypted, 16, encrypted.length);
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new javax.crypto.spec.IvParameterSpec(iv));
byte[] decrypted = cipher.doFinal(data);
return new String(decrypted);
}
}
```
使用示例:
```
public static void main(String[] args) throws Exception {
String data = "Hello, world!";
String key = "1234567812345678";
String encryptedData = AesUtil.encrypt(data, key);
System.out.println("Encrypted data: " + encryptedData);
String decryptedData = AesUtil.decrypt(encryptedData, key);
System.out.println("Decrypted data: " + decryptedData);
}
```
输出结果:
```
Encrypted data: BdyQa0lG4jB0mJ9mZ8hCkA==
Decrypted data: Hello, world!
```
在上述示例中,我们使用了16字节(128位)的密钥,将一个字符串加密成了一个长度为24字节的字符串。密文的前16字节是随机生成的IV,后8字节是加密后的数据。在解密时,我们首先从密文中取出前16字节作为IV,然后使用相同的密钥和IV进行解密。这样可以保证加密后的字符串长度是固定的,并且可以正确地进行解密。
阅读全文