I've spent an embarrasing number of hours trying to get Libsodium.js to work.
See my fiddle demo (and code pasted below too).
I keep getting Error: wrong secret key for the given ciphertext
.
What I would prefer is to replicate this PHP example of function simpleEncrypt($message, $key)
into Libsodium.js.
But as a starter, I'd be happy even getting the basic sample from the Libsodium.js repo to work.
Any hints?
Here is the code (also shown in the working fiddle):
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);
}
})();
null
withnonce
in the functions above so that the results would be interchangeable with Sodium-PHP. Here is a related question: security.stackexchange.com/questions/191472/… I also added padding. – Citify