Detecting incorrect key using AES/GCM in JAVA

前端 未结 2 760
悲&欢浪女
悲&欢浪女 2021-01-01 06:52

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.

相关标签:
2条回答
  • 2021-01-01 07:05

    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.

    0 讨论(0)
  • 2021-01-01 07:17

    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.

    0 讨论(0)
提交回复
热议问题