当我使用AES128对文本进行加密时,它可以正常工作,然后当我尝试使用相同的加密数据和密钥进行解密时,它会给我一个
javax.crypto.IlliegalBlockSizeException:输入必须是多个的 16用填充密码解密时
错误这只发生在我之前添加IvParameterSpec的修复
之后AES128 Java类:
package xcrypt;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class AES128
{
byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec ivSpec = new IvParameterSpec(iv);
private byte[] getRawKey(byte[] seed) throws Exception
{
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
public byte[] encrypt(byte[] raw, byte[] clear) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(raw), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec);
byte[] encrypted = cipher.doFinal(clear);
return encrypted;
}
public byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(raw), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
}
这里是调用方法的地方(主类):
public byte[] Encryption_AES128(byte[] plain , byte[] key) throws Exception
{
AES128 aes128 = new AES128();
return aes128.encrypt(key, plain);
}
public byte[] Decryption_AES128(byte[] cipher , byte[] key) throws Exception
{
AES128 aes128 = new AES128();
return aes128.decrypt(key, cipher);
}