在java中解密AES加密文件

我有一个使用AES加密的java应用程序文件。 我还有一个加密的密钥文件。 但我无法理解如何使用密钥来解密文件。 大多数教程和示例创建临时随机密钥,加密文件并在一个地方解密。 那么,问题是如何指定一个必须用于解密的密钥?

编辑 :我发现的样本使用以下代码生成密钥。 我不知道我在哪里可以使用我的钥匙。

KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key = kgen.generateKey(); 

只是总结一下我对路西法答案的评论。

  1. 如果您不知道用于加密的填充,则使用“无填充”设置进行解密。 这将解密所有内容,包括填充,并且不会因填充不匹配而引发错误。

  2. 解密密文后,查看输出的最后一个块,看看使用了哪个填充。 不同的填充会留下不同的字节模式,因此通常很容易辨别。

  3. 设置您的解密方法以期望正确的填充类型,它将自动为您删除。

答案可能只是将关键数据作为字节放入SecretKeySpec中,如下所示:

 SecretKeySpec aesKey = new SecretKeySpec(myKeyData, "AES"); 

请注意, SecretKeySpec实现了Key接口,因此您可以直接在Cipher.init()方法中使用它。 所以不需要SecretKeyFactory,否则你会使用它。

请尝试以下方法,如果可能对您有所帮助。

 private static byte[] cipherData(PaddedBufferedBlockCipher cipher, byte[] data) throws Exception { int minSize = cipher.getOutputSize(data.length); byte[] outBuf = new byte[minSize]; int length1 = cipher.processBytes(data, 0, data.length, outBuf, 0); int length2 = cipher.doFinal(outBuf, length1); int actualLength = length1 + length2; byte[] result = new byte[actualLength]; System.arraycopy(outBuf, 0, result, 0, result.length); return result; } private static byte[] decrypt(byte[] cipher, byte[] key, byte[] iv) throws Exception { PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(false, ivAndKey); return cipherData(aes, cipher); } private static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception { PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(true, ivAndKey); return cipherData(aes, plain); } 

完整的加密/解密 大型video的示例, 不会抛出Java OutOfMemoryException并使用Java SecureRandom进行初始化向量生成。 还描述了将密钥字节存储到数据库,然后从那些字节重建相同的密钥。

https://stackoverflow.com/a/18892960/185022