Created
April 11, 2020 12:44
-
-
Save Dviejopomata/d58c6c8eb028ecf64c239a5bd01c8350 to your computer and use it in GitHub Desktop.
Encriptar y desencriptar crypto API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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