Skip to content

Instantly share code, notes, and snippets.

@Dviejopomata
Created April 11, 2020 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dviejopomata/d58c6c8eb028ecf64c239a5bd01c8350 to your computer and use it in GitHub Desktop.
Save Dviejopomata/d58c6c8eb028ecf64c239a5bd01c8350 to your computer and use it in GitHub Desktop.
Encriptar y desencriptar crypto API
function getMessageEncoding(message) {
let enc = new TextEncoder();
return enc.encode(message);
}
function bufferToStr(buff) {
return String.fromCharCode.apply(null, new Uint8Array(buff));
}
async function main() {
const counter = window.crypto.getRandomValues(new Uint8Array(16));
const key = Buffer.from("holasoydavid1234");
const key_encoded = await crypto.subtle.importKey(
"raw",
key.buffer,
"AES-CTR",
false,
["encrypt", "decrypt"]
);
const msg = "mi mensaje secreto";
const encrypted = await window.crypto.subtle.encrypt(
{
name: "AES-CTR",
counter: counter,
length: 64
},
key_encoded,
getMessageEncoding(msg)
);
console.log(encrypted, "1");
const decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-CTR",
counter: counter,
length: 64
},
key_encoded,
encrypted
);
console.log(bufferToStr(decrypted));
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment