rweather / arduinolibs

Arduino Cryptography Library
444 stars 212 forks source link

Ascon128::decrypt doesn't seem to allow for inplace decryption, despite documentation saying so #80

Open D-VR opened 1 year ago

D-VR commented 1 year ago

from the decrypt documentation:

output | The output buffer to write to, which may be the same buffer as input. The output buffer must have at least as many bytes as the input buffer.

When I gave the same buffer (array) as input and output, for small ciphertext (5 bytes) the decryption worked, but the auth tag failed. For larger ciphertext (~10+ bytes) the decryption was wrong after 8 or so bytes and the auth tag also failed.

Using a secondary array for output fixed the issue

Example code (associatedDataLength was set to 0):

   // Add associated data for authentication
    cipher.addAuthData(payloadPtr, associatedDataLength);

    // Decrypt the payload in-place
    cipher.decrypt(payloadPtr + associatedDataLength, payloadPtr + associatedDataLength, payloadLength - associatedDataLength - tagLength);

plaintext = 1 2 3 4 5 6 7 8 9 A B C D E F 10

ciphertext + auth tag (truncated to first two bytes) = 92 181 255 163 70 222 138 218 130 80 168 62 113 52 80 28 2 167

decrypted ciphertext + auth tag = 1 2 3 4 5 6 7 8 84 128 94 117 16 31 1 107 2 167

computed decryption auth tag (truncated to first two bytes) = 222 64

Changing the code to:

 // Add associated data for authentication
    cipher.addAuthData(payloadPtr, associatedDataLength);
    uint8_t *tempPayload = new uint8_t[payloadLength];

    // Decrypt the payload, unlike encrypt can't be inplace!
    cipher.decrypt(tempPayload + associatedDataLength, payloadPtr + associatedDataLength, payloadLength - associatedDataLength - tagLength);

fixed the issue and returned the full plaintext + correct authentication tag

I'm not sure if I made a mistake, or if the library is at fault