[英]Can I decrypt only part of file encrypted with AES/CBC in Java?
我將如何處理? 我有使用Java中的AES / CBC / PKCS5Padding加密文件的代碼,據我所知,這張照片是:
部分解密應該是可能的,其前一部分和密鑰使用部分密文。 我還沒有找到任何例子。 有什么幫助嗎?
解密代碼如下:
//skip the IV (ivSize is 16 here) - IV was pretended to the stream during encryption
data.skip(ivSize);
//skip n blocks
int n = 2;
System.out.println("skipped: " + data.skip(n*16));
byte[] iv = new byte[ivSize];
//use next 16 bytes as IV
data.read(iv);
// Hashing key.
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.update(encryptionKey.getBytes(StandardCharsets.UTF_8));
byte[] keyBytes = new byte[16];
System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);
Cipher cipher;
try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
} catch (GeneralSecurityException e) {
throw new IOException(e);
}
CipherInputStream cis = new CipherInputStream(data, cipher);
try {
ByteStreams.copy(ByteStreams.limit(cis, limit), output);
} catch (IOException exception) {
// starting with java 8 the JVM wraps an IOException around a GeneralSecurityException
// it should be safe to swallow a GeneralSecurityException
if (!(exception.getCause() instanceof GeneralSecurityException)) {
throw exception;
}
log.warning(exception.getMessage());
} finally {
cis.close();
}
對的,這是可能的。
您需要在塊邊界上選擇“部分”,長度是塊大小的倍數,並將上一個塊用作IV。 對於AES,塊大小為16字節。
如果“部分”包含最后一個塊,請指定正確的填充,否則,請不指定填充NoPadding
:在這種情況下為AES/CBC/NoPadding
。 這將消除填充錯誤。 僅最后一塊具有填充。
必須使用正確的填充選項實例化Cipher
,這取決於Cipher
是否是整個加密數據的最后一塊。
請參閱: PKCS#7填充 (有時錯誤地稱為PKCS#5),這是最常見的填充。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.