Detecting incorrect key using AES/GCM in JAVA

陌路散爱 提交于 2019-12-30 03:33:08

问题


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();

thanks


回答1:


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):

  1. an incorrect key is being used;
  2. the counter mode encrypted data was altered during transport;
  3. the additional authenticated data was altered;
  4. the authentication tag itself was altered during transport.

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.

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.




回答2:


You are using NoPadding. Change this to PKCS7Padding for both encryption and decryption. If the wrong key is used then the padding will almost certainly fail to decrypt as expected and an InvalidCipherTextException will be thrown.



来源:https://stackoverflow.com/questions/12228250/detecting-incorrect-key-using-aes-gcm-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!