JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<html lang="en">
<!--
https://gist.github.com/chrisveness/43bcda93af9f646d083fad678071b90a
https://medium.com/net-magazine/the-web-cryptography-api-15d052271494
-->
<head>
<meta charset="UTF-8">
<title>WebCrypto API Demo: AES-GCM</title>
<script type="text/javascript">
function AES_GCM_encrypt() {
var iv = crypto.getRandomValues(new Uint8Array(16));
console.log(iv);
var ivHex = bytesToHexString(iv);
//console.log(ivHex);
var pwUtf8 = new TextEncoder().encode(document.getElementById("password").value);
crypto.subtle.digest('SHA-256', pwUtf8)
.then(function(hash) {
var pwHex = bytesToHexString(hash);
var keyData = hexStringToUint8Array(pwHex);
crypto.subtle.importKey("raw", keyData, "aes-gcm", false, ["encrypt"])
.then(function(key) {
var plainText = document.getElementById("plainTextGCM").value;
return crypto.subtle.encrypt({
name: "aes-gcm",
iv: iv
}, key, asciiToUint8Array(plainText));
}, failAndLog)
.then(function(cipherText) {
document.getElementById("cipherTextGCM").value = ivHex + bytesToHexString(cipherText);
}, failAndLog);
});
}
function AES_GCM_decrypt() {
var pwUtf8 = new TextEncoder().encode(document.getElementById("password").value);
crypto.subtle.digest('SHA-256', pwUtf8)
.then(function(hash) {
var pwHex = bytesToHexString(hash);
var keyData = hexStringToUint8Array(pwHex);
crypto.subtle.importKey("raw", keyData, "aes-gcm", false, ["decrypt"])
.then(function(key) {
var cipherText = document.getElementById("cipherTextGCM").value;
var iv = hexStringToUint8Array(cipherText.slice(0, 32));
var cipherHex = cipherText.slice(32);
...