問題描述
我正在使用 AES
在 GCM
模式下使用 BouncyCastle 加密/解密一些文件.
雖然我證明了錯(cuò)誤的解密密鑰,但也不例外.
我應(yīng)該如何檢查密鑰是否不正確?
我的代碼是這樣的:
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 模式下沒有方法可以檢測到不正確的鍵.您可以檢查的是身份驗(yàn)證標(biāo)簽是否有效,這意味著您使用了正確的密鑰.問題是,如果身份驗(yàn)證標(biāo)簽不正確,那么這可能表明以下各項(xiàng)(或所有內(nèi)容的組合,直至并包括完全替換密文和身份驗(yàn)證標(biāo)簽):
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):
- 使用了不正確的密鑰;
- 計(jì)數(shù)器模式加密數(shù)據(jù)在傳輸過程中被更改;
- 其他經(jīng)過身份驗(yàn)證的數(shù)據(jù)已更改;
- 身份驗(yàn)證標(biāo)簽本身在傳輸過程中被更改.
您可以做的是發(fā)送額外的數(shù)據(jù)來識(shí)別所使用的密鑰.這可能是一個(gè)可讀的標(biāo)識(shí)符 ("encryption-key-1"
),但它也可能是一個(gè) KCV,一個(gè)密鑰檢查值.KCV 通常由使用密鑰加密的零塊或密鑰上的加密安全哈希(也稱為指紋)組成.因?yàn)榱銐K上的加密會(huì)泄漏信息,所以您不應(yīng)該使用它來識(shí)別加密密鑰.
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.
您實(shí)際上可以使用 GCM 模式的 AAD 功能來計(jì)算密鑰標(biāo)識(shí)數(shù)據(jù)上的身份驗(yàn)證標(biāo)簽.請(qǐng)注意,您無法區(qū)分指紋泄露和使用不正確的密鑰.但是指紋被意外損壞的可能性比IV、AAD、密文和認(rèn)證標(biāo)簽的整個(gè)結(jié)構(gòu)要小.
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.
這篇關(guān)于在 JAVA 中使用 AES/GCM 檢測不正確的密鑰的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!