Skip to content

🐛 decipher.final() not throwing error on incorrect key for aes-256-gcm #798

@michaeltout

Description

@michaeltout

What's happening?

Hi, I've noticed an issue where the code shown below produces meaningless output when decrypting encrypted data using aes-256-gcm with an incorrect decryption key. The correct behavior (as shown if you replace the react-native-quick-crypto lib below with nodejs crypto in a node environment, or react-native-crypto in a react native environment) would be to throw an Unsupported state or unable to authenticate data error to indicate decryption failure. Let me know if you need any additional details. The log output is pasted from the metro bundler.

react-native version: 0.71.19

Reproducible Code

var aes256 = {},
  crypto = require('react-native-quick-crypto'),
  algorithm = 'aes-256-gcm';

aes256.encrypt = async function (key, data) {
  var sha256 = crypto.createHash('sha256');
  sha256.update(key);

  var iv = crypto.randomBytes(16)

  var plaintext = Buffer.from(data),
    cipher = crypto.createCipheriv(algorithm, sha256.digest(), iv),
    ciphertext = cipher.update(plaintext);
  ciphertext = Buffer.concat([iv, ciphertext, cipher.final(), cipher.getAuthTag()]);

  return ciphertext.toString('base64');
};

aes256.decrypt = function (key, data) {
  var sha256 = crypto.createHash('sha256');
  sha256.update(key);

  var input = Buffer.from(data, 'base64'),
    iv = input.slice(0, 16),
    ciphertext = input.slice(16, -16),
    authTag = input.slice(-16),
    decipher = crypto.createDecipheriv(algorithm, sha256.digest(), iv);

  decipher.setAuthTag(authTag);

  const plaintextBuf = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
  return plaintextBuf.toString('utf8');
};

const password = "12345"
const phrase = "phrase"
const wrongPassword = "543214"

const encryptedData = aes256.encrypt(password, phrase);
const decryptedData = aes256.decrypt(password, encryptedData)
const wronglyDecryptedData = aes256.decrypt(wrongPassword, encryptedData)

console.log(encryptedData)
console.log(decryptedData)
console.log(wronglyDecryptedData)

Relevant log output

LOG  dY63CB+fSoJI2a8qOAyH/jtISbkrwvy31zYep1Kxo496UOskG30=
 LOG  phrase
 LOG  2]��=

Device

iPhone 15 Simulator

QuickCrypto Version

0.7.17

Can you reproduce this issue in the QuickCrypto Example app?

I didn't try (⚠️ your issue might get ignored & closed if you don't try this)

Additional information

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions