flutterdartencryption

Check in Dart whether a ChaCha20-Poly1305-IETF decryption was successful


In my Dart/Flutter Code I have data that is encrypted with ChaCha20-Poly1305-IETF.

I decrypt the data using the Pointycastle library and the following code:

Uint8List encryptedData = Uint8List.fromList([...]);
Uint8List nonce = Uint8List.fromList([...]);
Uint8List encryptionKey = Uint8List.fromList([...]);

final ChaCha20Poly1305 chaCha20Poly1305 = ChaCha20Poly1305(ChaCha7539Engine(), Poly1305());
final params = AEADParameters(KeyParameter(encryptionKey), 128, nonce, encryptedData);
chaCha20Poly1305.init(false, params);

decryptedData = chaCha20Poly1305.process(encryptedData); // this can be wrong

I now have the following question: How can I find out whether the decryption was successful? Even if the encryptionKey is obviously wrong (e.g. if I change it hardcoded), decryptedData contains a list of data at the end. This data is of course not correct and causes problems in further processing. I would now like to find out whether the decryption has failed and then simply discard the data.


Solution

  • With the Solution suggested by @Topaco I came to the following result, which works for me:

        final ChaCha20Poly1305 chaChaEngine = ChaCha20Poly1305(ChaCha7539Engine(), 
        Poly1305());
        final params = AEADParameters(KeyParameter(encryptionKey), 128, nonce, Uint8List(0));
        chaChaEngine.init(false, params);
        
        decrypted = Uint8List(encryptedData.length - encryptionType.macLength);
        int len = chaChaEngine.processBytes(encryptedData, 0, encryptedData.length, decrypted, 0);
        try {
            len += chaChaEngine.doFinal(decrypted, len);
        } catch (e) {
            debugPrint('Could not decrypt data: $e');
            return null;
        }