libsodium.js demo
by rwhal06
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/libsodium-wrappers/0.5.4/sodium.min.js"></script>
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
JavaScript 1.7
"use strict";
console.log("https://github.com/jedisct1/libsodium.js");
const _sodium = require("libsodium-wrappers");
const concatTypedArray = function (ResultConstructor, ...arrays) {
let totalLength = 0;
for (const arr of arrays) {
totalLength += arr.length;
}
const result = new ResultConstructor(totalLength);
let offset = 0;
for (const arr of arrays) {
result.set(arr, offset);
offset += arr.length;
}
return result;
};
(async () => {
await _sodium.ready;
const sodium = _sodium;
const nonceBytes = sodium.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES;
let key = sodium.from_hex("724b092810ec86d7e35c9d067702b31ef90bc43a7b598626749914d6a3e033ed");
var nonceTest;
/**
* @param {string} message
* @param {string} key
* @returns {Uint8Array}
*/
function encrypt_and_prepend_nonce(message, key) {
let nonce = sodium.randombytes_buf(nonceBytes);
nonceTest = nonce.toString();
//console.log("nonce", nonce.toString());
var encrypted = sodium.crypto_aead_xchacha20poly1305_ietf_encrypt(message, null, nonce, nonce, key);
//console.log("encrypted", encrypted.toString());
var nonce_and_ciphertext = concatTypedArray(Uint8Array, nonce, encrypted); //https://github.com/jedisct1/libsodium.js/issues/130#issuecomment-361399594
//console.log("nonce_and_ciphertext", nonce_and_ciphertext, "type", typeof nonce_and_ciphertext);
//console.log("nonce_and_ciphertext.toString()", nonce_and_ciphertext.toString());
return nonce_and_ciphertext;
}
/**
* @param {Uint8Array} nonce_and_ciphertext
* @param {string} key
* @returns {string}
*/
function decrypt_after_extracting_nonce(nonce_and_ciphertext, key) {
//console.log("nonce_and_ciphertext in decrypt_after_extracting_nonce", nonce_and_ciphertext);
console.log("nonce_and_ciphertext in decrypt_after_extracting_nonce", nonce_and_ciphertext.toString()); //this matches
let nonce = nonce_and_ciphertext.slice(0, nonceBytes);...