Skip to content

Instantly share code, notes, and snippets.

@mpgn
Last active December 31, 2023 05:12
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpgn/2f990997b9aa5fad3f90ff94546fae1e to your computer and use it in GitHub Desktop.
Save mpgn/2f990997b9aa5fad3f90ff94546fae1e to your computer and use it in GitHub Desktop.
SubtleCrypto javascript example
// exemple based on https://github.com/diafygi/webcrypto-examples#rsa-oaep
function importKey() {
return window.crypto.subtle.importKey(
"jwk", //can be "jwk" or "raw"
{ //this is an example jwk key, "raw" would be an ArrayBuffer
kty: "oct",
k: "Y0zt37HgOx-BY7SQjYVmrqhPkO44Ii2Jcb9yydUDPfE",
alg: "A256GCM",
ext: true,
},
{ //this is the algorithm options
name: "AES-GCM",
},
false, //whether the key is extractable (i.e. can be used in exportKey)
["encrypt", "decrypt"] //can "encrypt", "decrypt", "wrapKey", or "unwrapKey"
)
}
function generateKey() {
return window.crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256, //can be 128, 192, or 256
},
true, //whether the key is extractable (i.e. can be used in exportKey)
["encrypt", "decrypt"] //can "encrypt", "decrypt", "wrapKey", or "unwrapKey"
)
}
function encrypt(data, key, iv) {
return window.crypto.subtle.encrypt(
{
name: "AES-GCM",
//Don't re-use initialization vectors!
//Always generate a new iv every time your encrypt!
//Recommended to use 12 bytes length
iv: iv,
//Additional authentication data (optional)
// additionalData: ArrayBuffer,
//Tag length (optional)
tagLength: 128, //can be 32, 64, 96, 104, 112, 120 or 128 (default)
},
key, //from generateKey or importKey above
data //ArrayBuffer of data you want to encrypt
)
}
function decrypt(data, key, iv) {
return window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv, //The initialization vector you used to encrypt
//additionalData: ArrayBuffer, //The addtionalData you used to encrypt (if any)
tagLength: 128, //The tagLength you used to encrypt (if any)
},
key, //from generateKey or importKey above
data //ArrayBuffer of the data
)
}
var keys = await importKey()
var iv = new Uint8Array([188, 185, 57, 146, 246, 194, 114, 34, 12, 80, 198, 77])
var enc = new TextEncoder();
var data = enc.encode("This is a secret message")
var encryptedData = await encrypt(data, keys, iv)
var decryptedData = await decrypt(encryptedData, keys, iv)
var enc = new TextDecoder("utf-8");
enc.decode(decryptedData)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment