基本上,我试图将用户指定的字符串散列到256位字节数组中,以便在使用Java的AES256实现加密数据时用作密钥。我一直得到这个运行时异常:非法密钥大小或默认参数
java.security.InvalidKeyException: Illegal key size or default parameters
我怀疑这是因为一些字节不是8位长,所以整体密钥大小不是256位。我想知道如何用左边的0填充它们,所以确保密钥的长度?
编辑:
这是从一个值到一个消息摘要的转化:
MessageDigest hasher = MessageDigest.getInstance("SHA-256");
// Use the factory method to get the SHA-256 instance of a MessageDigest object.
hasher.update(input.getBytes());
// Update the message digest object with the bytes of the value to hash.
return hasher.digest();
// Hash the value and return the string representation.
这是加密,使用从“散列器”的输出。
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
cryptoTool.init(Cipher.ENCRYPT_MODE, key); // This is where the error fires.
return String.valueOf(cryptoTool.doFinal(plaintext.getBytes()));
您可以确定所有字节在Java中都是8位长。 – Axel 2013-02-14 22:42:46
Okey doke。那么你能想到另一个原因,为什么我可能会得到SHA256散列结果的无效密钥异常? – christopher 2013-02-14 22:43:48
你能提供你的代码吗?这可能会帮助我们确定问题。 – 2013-02-14 22:44:11