Last active
May 6, 2024 03:25
-
-
Save mpgn/2f990997b9aa5fad3f90ff94546fae1e to your computer and use it in GitHub Desktop.
SubtleCrypto javascript example
This file contains hidden or 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
// 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