Skip to content

Instantly share code, notes, and snippets.

@57op
Created April 26, 2019 12:14
Show Gist options
  • Save 57op/0db580f47779c074053626f09b5664f9 to your computer and use it in GitHub Desktop.
Save 57op/0db580f47779c074053626f09b5664f9 to your computer and use it in GitHub Desktop.
(async () => {
const keyPair = await crypto.subtle.generateKey(
{
name:'ECDH',
namedCurve:'P-256'
},
true,
['deriveKey', 'deriveBits']
)
const nonce = await crypto.subtle.deriveBits(
{
name: 'ECDH',
public: keyPair.publicKey
},
keyPair.privateKey,
16 << 3 // 16 bytes
)
const key = await crypto.subtle.deriveKey(
{
name: 'ECDH',
public: keyPair.publicKey
},
keyPair.privateKey,
{
name: 'AES-GCM',
length: 256
},
true,
['encrypt', 'decrypt']
)
const encryptedMessage = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: nonce
},
key,
new TextEncoder().encode('ciao mondo')
)
const decryptedMessage = await crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: nonce
},
key,
encryptedMessage
)
console.log(new TextDecoder().decode(decryptedMessage))
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment