問題描述
我正在使用 AES
在 GCM
模式下使用 BouncyCastle 加密/解密一些文件.
雖然我證明了錯誤的解密密鑰,但也不例外.
我應該如何檢查密鑰是否不正確?
我的代碼是這樣的:
I'm using AES
to encrypt/decrypt some files in GCM
mode using BouncyCastle.
While I'm proving wrong key for decryption there is no exception.
How should I check that the key is incorrect?
my code is this:
SecretKeySpec incorrectKey = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
byte[] block = new byte[1048576];
int i;
cipher.init(Cipher.DECRYPT_MODE, incorrectKey, ivSpec);
BufferedInputStream fis=new BufferedInputStream(new ProgressMonitorInputStream(null,"Decrypting ...",new FileInputStream("file.enc")));
BufferedOutputStream ro=new BufferedOutputStream(new FileOutputStream("file_org"));
CipherOutputStream dcOut = new CipherOutputStream(ro, cipher);
while ((i = fis.read(block)) != -1) {
dcOut.write(block, 0, i);
}
dcOut.close();
fis.close();
謝謝
推薦答案
在 GCM 模式下沒有方法可以檢測到不正確的鍵.您可以檢查的是身份驗證標簽是否有效,這意味著您使用了正確的密鑰.問題是,如果身份驗證標簽不正確,那么這可能表明以下各項(或所有內容的組合,直至并包括完全替換密文和身份驗證標簽):
There is no method that you can detect incorrect key in GCM mode. What you can check is if the authentication tag validates, which means you were using the right key. The problem is that if the authentication tag is incorrect then this could indicate each of the following (or a combination of all, up to and including the full replacement of the ciphertext and authentication tag):
- 使用了不正確的密鑰;
- 計數器模式加密數據在傳輸過程中被更改;
- 其他經過身份驗證的數據已更改;
- 身份驗證標簽本身在傳輸過程中被更改.
您可以做的是發送額外的數據來識別所使用的密鑰.這可能是一個可讀的標識符 ("encryption-key-1"
),但它也可能是一個 KCV,一個密鑰檢查值.KCV 通常由使用密鑰加密的零塊或密鑰上的加密安全哈希(也稱為指紋)組成.因為零塊上的加密會泄漏信息,所以您不應該使用它來識別加密密鑰.
What you could do is send additional data to identify the secret key used. This could be a readable identifier ("encryption-key-1"
) but it could also be a KCV, a key check value. A KCV normally consists of a zero-block encrypted with the key, or a cryptographically secure hash over the key (also called a fingerprint). Because the encryption over a zero block leaks information you should not use that to identify the encryption key.
您實際上可以使用 GCM 模式的 AAD 功能來計算密鑰標識數據上的身份驗證標簽.請注意,您無法區分指紋泄露和使用不正確的密鑰.但是指紋被意外損壞的可能性比IV、AAD、密文和認證標簽的整個結構要小.
You could actually use the AAD feature of GCM mode to calculate the authentication tag over the key identification data. Note that you cannot distinguish between compromise of the fingerprint and using an incorrect key. It's however less likely that the fingerprint is accidentally damaged than the entire structure of IV, AAD, ciphertext and authentication tag.
這篇關于在 JAVA 中使用 AES/GCM 檢測不正確的密鑰的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!