我想使用自己的密钥使用AES加密字符串。但是我在密钥的位长上遇到了麻烦。你能否查看我的代码并查看我需要修复/更改的内容。
public static void main(String[] args) throws Exception { String username = "bob@google.org"; String password = "Password1"; String secretID = "BlahBlahBlah"; String SALT2 = "deliciously salty"; // Get the Key byte[] key = (SALT2 + username + password).getBytes(); System.out.println((SALT2 + username + password).getBytes().length); // Need to pad key for AES // TODO: Best way? // Generate the secret key specs. SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); // Instantiate the cipher Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encrypted = cipher.doFinal((secrectID).getBytes()); System.out.println("encrypted string: " + asHex(encrypted)); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] original = cipher.doFinal(encrypted); String originalString = new String(original); System.out.println("Original string: " + originalString + "\nOriginal string (Hex): " + asHex(original)); }
现在,我得到一个异常“ 无效的AES密钥长度:86个字节 ”。我需要垫我的钥匙吗?我该怎么办?
我还需要为ECB或CBC设置任何内容吗?
如注释中所写,旧代码不是“最佳实践”。你应该使用像PBKDF2这样的密钥生成算法,并且迭代次数很高。你还应该至少部分使用非静态(对于每个“身份”而言是唯一的)盐。如果可能,则随机生成并与密文一起存储。
SecureRandom sr = SecureRandom.getInstanceStrong(); byte[] salt = new byte[16]; sr.nextBytes(salt); PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1000, 128 * 8); SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec); Cipher aes = Cipher.getInstance("AES"); aes.init(Cipher.ENCRYPT_MODE, key);