在使用AES加密算法时,需要确定填充方案,以确保数据块的长度为128位。以下是一个示例,使用Java中的Crypto库实现AES加密算法并指定填充方案为PKCS5Padding:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private static final byte[] key = "secretkey123456".getBytes(); // 16 byte key
public static byte[] encrypt(String plainText) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText) throws Exception{
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(cipherText));
}
public static void main(String args[]) throws Exception {
String plainText = "Hello, world!";
byte[] cipherText = encrypt(plainText);
String decryptedText = decrypt(cipherText);
System.out.println("Plain text: " + plainText);
System.out.println("Encrypted text: " + new String(cipherText));
System.out.println("Decrypted text: " + decryptedText);
}
}
在此示例中,我们指定了填充方案为PKCS5Padding。如果要使用其他填充方案,请使用相应的字符串替换“PKCS5Padding”。
上一篇:AES加密数据的长度
下一篇:aes加密算法实现