google / webcrypto.dart

Cross-platform implementation of Web Cryptography APIs
https://pub.dev/packages/webcrypto
Apache License 2.0
71 stars 43 forks source link

Give access to the authorization tag in AES-GCM mode #97

Closed Skyost closed 3 months ago

Skyost commented 3 months ago

It would be great to have this feature because it would allow us to check for data integrity before actually having to decrypt the whole data. Right now the only way to use this built-in check is to do something like that :

Future<bool> isValid(Uint8List encryptedData, AesGcmSecretKey key) async => await decrypt(encryptedData, key) != null;

This is not optimal if the key is valid because the whole data is then proceeded.

Specs summarized here : https://crypto.stackexchange.com/a/25256.

jonasfj commented 3 months ago

Acesssing the authentication tag

This package provides a cross platform information of the webcrypto specification.

On the subject AES-GCM encrypt the webcrypto specification says:

  1. Let C and T be the outputs that result from performing the Authenticated Encryption Function described in Section 7.1 of [NIST-SP800-38D] using AES as the block cipher, the contents of the iv member of normalizedAlgorithm as the IV input parameter, the contents of additionalData as the A input parameter, tagLength as the t pre-requisite and the contents of plaintext as the input plaintext.

  2. Let ciphertext be equal to C | T, where '|' denotes concatenation.

  3. Return the result of creating an ArrayBuffer containing ciphertext.

Meaning that if you want to extract the authorization tag from the result, you probably just have to take the last tagLength / 8 bytes.

But are you sure that's what you want?

I'm not sure what you imagine that isValid would do? Given that it's missing parameters iv, additionalData and tagLength.

If you want to check data integrity, then yes decrypt will do this. You are probably right that it would be possible to produce a method that decrypts everything and validates the authentication tag without allocating all of the plaintext -- but it would probably still do decryption or almost decryption -- I'll admit I'm not super strong on the internals here. But my impression is that the tag isn't simply as hash of the ciphertext. So to verify that the tag is valid, you'd probably do all the same computation as decrypt will (at at-least almost).

Skyost commented 3 months ago

Thanks for your answer. I'll check and consider what's the best for my project 🙂