我正在使用以下 unix 命令生成 AES 的 128 位 key 并将其写入文件。
dd if=/dev/urandom of=/data/key.txt bs=16 count=1
我正在从java类中的文件中读取 key 并将其用于加密/解密
BufferedReader reader = new BufferedReader(new FileReader(keylocation.getFile()));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
String secretKey = stringBuilder.toString();
SecretKeySpec key = new SecretKeySpec(secretKey.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
encryptedString = (Base64.encodeBase64String(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))));
但是我遇到了以下异常
java.security.InvalidKeyException: Invalid AES key length: 28 bytes
由于我在文件中生成 128 位(16 字节) key ,如何将其更改为 28 字节?
最佳答案
您使用阅读器
。 阅读器
的目的是阅读文本。
但是你想要二进制,即字节数组。
解决方案:不要使用Reader
。使用 InputStream
并读入 16 元素 byte
数组。
关于java - 获取异常 java.security.InvalidKeyException : Invalid AES key length: 28 bytes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22007780/