我写了一个加密和解密函数。加密工作正常,但我总是在解密中得到 IllegalBlockSizeException。
public static String aes_encrypt (String text, String key)
{
SecretKey skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
cipher.init(Cipher.ENCRYPT_MODE, skey);
return new String((cipher.doFinal(text.getBytes())));
}
这是解密函数:
public static String aes_decrypt (String text, String key)
{
SecretKey skey = new SecretKeySpec(key.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
cipher.init(Cipher.DECRYPT_MODE, skey);
return new String((cipher.doFinal(text.getBytes())));
}
这是测试这个的简单主要方法:
public static void main (String args[])
{
String text = "Hello, world!";
String key = "nv93h50sk1zh508v";
String en, de;
System.out.println("Text: " + text);
System.out.println("Encrypted: " + (en = aes_encrypt(text, key))
+ " length = " + en.length());
System.out.println("Decrypted: " + (de = aes_decrypt(en, key)));
}
有谁知道如何正确“填充”加密字符串以便我可以解密它?(我尝试用 0 填充字符串,直到长度是 16 的倍数,但得到了类似的东西string not properly padded
。)
谢谢