AES加密Java无效密钥长度

wun*_*tee 9 java encryption aes

我正在尝试创建AES加密方法,但出于某种原因,我一直在努力

java.security.InvalidKeyException: Key length not 128/192/256 bits

这是代码:

public static SecretKey getSecretKey(char[] password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException{
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    // NOTE: last argument is the key length, and it is 256
    KeySpec spec = new PBEKeySpec(password, salt, 1024, 256);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    return(secret);
}


public static byte[] encrypt(char[] password, byte[] salt, String text) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
    SecretKey secret = getSecretKey(password, salt);

    Cipher cipher = Cipher.getInstance("AES");

    // NOTE: This is where the Exception is being thrown
    cipher.init(Cipher.ENCRYPT_MODE, secret);
    byte[] ciphertext = cipher.doFinal(text.getBytes("UTF-8"));
    return(ciphertext);
}
Run Code Online (Sandbox Code Playgroud)

谁能看到我做错了什么?我认为它可能与SecretKeyFactory算法有关,但这是我能找到的唯一一个我正在开发的终端系统支持的算法.任何帮助,将不胜感激.谢谢.

Moh*_*our 8

要获得更强的密钥强度加密,您需要下载Java Cryptography Extension(JCE)Unlimited Strength Jurisdiction Policy Files.

http://java.sun.com/javase/downloads/index.jsp(查看其他下载内容).


Waj*_*sam -1

使用任何填充机制来填充空位

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
Run Code Online (Sandbox Code Playgroud)