Cifrado Javascript simple usando Libsodium.js en esta demostración de sandbox

He pasado una cantidad embarazosa de horas tratando de hacer que Libsodium.js funcione.

Ver mi demo de violín (y el código pegado a continuación también).

Sigo recibiendoError: wrong secret key for the given ciphertext.

Lo que haríapreferi es replicar estePHP ejemplo defunction simpleEncrypt($message, $key) en Libsodium.js.

Pero como titular, me alegraría incluso obtener la @ básimuestra del repositorio Libsodium.js trabajar

¿Alguna pista?

Aquí está el código (también se muestra en el violín de trabajo):

const _sodium = require("libsodium-wrappers");
const concatTypedArray = require("concat-typed-array");
(async () => {
    await _sodium.ready;
    const sodium = _sodium;
    const utf8 = "utf-8";
    const td = new TextDecoder(utf8);
    const te = new TextEncoder(utf8);
    const nonceBytes = sodium.crypto_secretbox_NONCEBYTES;
    const macBytes = sodium.crypto_secretbox_MACBYTES;

    let key = sodium.from_hex("724b092810ec86d7e35c9d067702b31ef90bc43a7b598626749914d6a3e033ed");

    function encrypt_and_prepend_nonce(message, key) {
        let nonce = sodium.randombytes_buf(nonceBytes);
        var encrypted = sodium.crypto_secretbox_easy(message, nonce, key);
        var combined2 = concatTypedArray(Uint8Array, nonce, encrypted);
        return combined2;
    }

    function decrypt_after_extracting_nonce(nonce_and_ciphertext, key) {
        if (nonce_and_ciphertext.length < nonceBytes + macBytes) {
            throw "Short message";
        }
        let nonce = nonce_and_ciphertext.slice(0, nonceBytes);
        let ciphertext = nonce_and_ciphertext.slice(nonceBytes);
        return sodium.crypto_secretbox_open_easy(ciphertext, nonce, key);
    }

    function encrypt(message, key) {
        var x = encrypt_and_prepend_nonce(message, key);
        return td.decode(x);
    }

    function decrypt(nonce_and_ciphertext_str, key) {
        var nonce_and_ciphertext = te.encode(nonce_and_ciphertext_str);
        return decrypt_after_extracting_nonce(nonce_and_ciphertext, key);
    }

    var inputStr = "shhh this is a secret";
    var garbledStr = encrypt(inputStr, key);
    try {
        var decryptedStr = decrypt(garbledStr, key);
        console.log("Recovered input string:", decryptedStr);
        console.log("Check whether the following text matches the original:", decryptedStr === inputStr);
    } catch (e) {
        console.error(e);
    ,}
})();

Respuestas a la pregunta(3)

Su respuesta a la pregunta