Skip to content

Instantly share code, notes, and snippets.

@aurbano
Created April 4, 2020 16:21
Show Gist options
  • Save aurbano/bfd88ff35599c801e83cd19dbd39d37f to your computer and use it in GitHub Desktop.
Save aurbano/bfd88ff35599c801e83cd19dbd39d37f to your computer and use it in GitHub Desktop.
Generate a symmetric key, encrypt a message, export the key, import the key and decrypt the message
// Temporary Encryption Demo
// 1. generate an encryption key
const algorithm = "AES-GCM";
const iv = window.crypto.getRandomValues(new Uint8Array(12));
crypto.subtle.generateKey(
{
name: algorithm,
length: 256,
}, true, ['encrypt', 'decrypt']).then(key => {
console.log('key', key);
// Encrypt the users message
const enc = new TextEncoder();
const encoded = enc.encode("random message 123");
crypto.subtle.encrypt({
name: algorithm,
iv,
}, key, encoded).then(encrypted => {
// Export the key to be shared
crypto.subtle.exportKey('raw', key).then((exported) => {
// Import the key
const imported = crypto.subtle.importKey('raw', exported, algorithm, true, ['encrypt', 'decrypt']);
imported.then(importedKey => {
// decrypt the test message
crypto.subtle.decrypt({
name: algorithm,
iv,
}, importedKey, encrypted).then(decrypted => {
const dec = new TextDecoder();
const original = dec.decode(decrypted);
console.log('decrypted:', original);
});
})
});
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment