How to decrypt a value [encrypted using utils.crypto.encrypt] outside of a realm function

I’m struggling to decrypt values in a react native app that were encrypted in a realm function.

I created a function that encrypts some values using:

I can decrypt the values using utils.crypto.decrypt inside another realm function. What I can’t seem to achieve is to decrypt the value once the document syncs to the react native app.

I understand that I could encrypt the whole realm, but that doesn’t work for my use case.

Maybe I can get some clarity on:

  • What aes algorithm does utils.crypto use? Realm docs don’t document the “aes” algorithm used, I think it is “aes-256-cbc”
  • Does the base64 encoded and encrypted message contain an initialization vector?

I can get as far as decoding the bson from the base64 encoded value. But I can’t get a decrypted value.

const payload = new BSON.Binary(Buffer.from(encryptedMessage, 'base64'));
const decipher = createDecipheriv('aes-256-cbc', secretKey, randomiv);

console.log(payload.toString('hex')); // this outputs a value

let decrypted = decipher.update(bin.toString('hex'), 'hex', 'hex');
decrypted +='hex');

console.log(decrypted); // this outputs an empty value

Any guidance will be immensely appreciated.

Had an error in the example, here is the diff.

[-] let decrypted = decipher.update(bin.toString('hex'), 'hex', 'hex');
[+] let decrypted = decipher.update(payload.toString('hex'), 'hex', 'hex');

Another helpful detail, which I failed to include :slight_smile: the latest iteration throws an error on the'hex')

library: 'digital envelope routines',
function: 'EVP_DecryptFinal_ex',
reason: 'wrong final block length',