[英]Decrypt AES encrypted file in java
我有一個使用AES使用java應用程序加密的文件。 我還有一個加密的密鑰文件。 但我無法理解如何使用密鑰來解密文件。 大多數教程和示例創建臨時隨機密鑰,加密文件並在一個地方解密。 那么,問題是如何指定一個必須用於解密的密鑰?
編輯 :我發現的樣本使用以下代碼生成密鑰。 我不知道我在哪里可以使用我的鑰匙。
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
SecretKey key = kgen.generateKey();
答案可能只是將關鍵數據作為字節放入SecretKeySpec,如下所示:
SecretKeySpec aesKey = new SecretKeySpec(myKeyData, "AES");
請注意, SecretKeySpec實現了Key接口,因此您可以直接在Cipher.init()
方法中使用它。 所以不需要SecretKeyFactory,否則你會使用它。
只是總結一下我對路西法答案的評論。
如果您不知道用於加密的填充,則使用“無填充”設置進行解密。 這將解密所有內容,包括填充,並且不會因填充不匹配而引發錯誤。
解密密文后,查看輸出的最后一個塊,看看使用了哪個填充。 不同的填充會留下不同的字節模式,因此通常很容易分辨。
設置您的解密方法以期望正確的填充類型,它將自動為您刪除。
完整的加密/解密 大型視頻的示例, 不會拋出Java OutOfMemoryException
並使用Java SecureRandom
進行初始化向量生成。 還描述了將密鑰字節存儲到數據庫,然后從那些字節重建相同的密鑰。
請嘗試以下方法,如果可能對您有幫助。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.