sodium-plus icon indicating copy to clipboard operation
sodium-plus copied to clipboard

sodium.crypto_secretbox () or decrypted.toString(); does not handle UTF8 characters

Open agnasg opened this issue 2 years ago • 2 comments

Not sure if this is an issue or maybe I need to put charset="UTF-8" somewhere but if the original plaintext has UTF8 characters the resulting decrypted text returns garbage. For example: plaintext = 'El camión tenía piñas';

ciphertext.toString('hex') == bbbbe889db929838ddd6b62b0712479655c4abb10890bdd835d3298436234746d19da673c8

decrypted.toString() == El cami�n ten�a pi�as

I was about to swap the bytes but it seemed crazy, so I preferred to ask.

agnasg avatar May 11 '22 13:05 agnasg

try decrypted.toString('latin1') works for me but only in Spanish;

Or

new_plaintext = Buffer.from(plaintext).toString('base64')
...
Buffer.from(decrypted.toString(),'base64').toString()

zodman avatar Feb 27 '23 15:02 zodman

const { SodiumPlus } = require('sodium-plus');

(async function() {
    // Select a backend automatically
    let sodium = await SodiumPlus.auto();

    let key = await sodium.crypto_secretbox_keygen();
    let nonce = await sodium.randombytes_buf(24);
    let message = 'my unicode ÑÖ 中国 😉';

   let messageEncoded = Buffer.from(message,"utf8");
    let ciphertext = await sodium.crypto_secretbox(messageEncoded, nonce, key);
    let decrypted = await sodium.crypto_secretbox_open(ciphertext, nonce, key);
    console.log(decrypted.toString());
})();

zodman avatar Feb 27 '23 17:02 zodman