Web Crypto API AES-GCM - generateKey/Encrypt/Decrypt

by Anish

Posted on Monday september 17, 2018


This sample chapter extracted from the book, Cryptography for JavaScript Developers.


The Crypto interface represents an interface to general purpose cryptographic functionality including a cryptographically strong pseudo-random number generator seeded with truly random values.

The SubtleCrypto.generateKey() method returns a Promise of a newly generated CryptoKey

The Syntax

var result = crypto.subtle.generateKey(algo, extractable, keyUsages);
  • algo: Supported algo are: AES-CBC, AES-CTR, AES-GCM, RSA-OAEP, AES-KW, HMAC, RSASSA-PKCS1-v1_5, ECDSA, ECDH, and DH.

  • extractable is a Boolean indicating if the key can be extracted from the CryptoKey object at a later stage

  • keyUsages is an Array indicating what can be done with the newly generated key. Possible values of the array are for AES encryption:

    • encrypt, allowing the key to be used for encrypting messages.
    • decrypt, allowing the key to be used for decrypting messages.
    • wrapKey, allowing the key to wrap a symmetric key for usage (transfer, storage) in unsecure environments.
    • unwrapKey, allowing the key to unwrap a symmetric key for usage (transfer, storage) in unsecure environments.

The Demo

Plain Text:
Cipher Text:
Result:


The webcrypto api java script example AES-GCM generateKey Encryption and Decryption

 var iv = crypto.getRandomValues(new Uint8Array(16));
 var secretKey;

window.crypto.subtle.generateKey({
            name: "AES-GCM",
            length: 256, //can be  128, 192, or 256
        },
        false, //whether the key is extractable (i.e. can be used in exportKey)
        ["encrypt", "decrypt"] //can "encrypt", "decrypt" or  "wrapKey", or "unwrapKey"
    ).then(function(key) {
        secretKey = key;
    })
    .catch(function(err) {
        console.error(err);
    });


function AES256_GCM_ENCRYPT() {

    if (secretKey == null) {
        alert("Failed to Generate AES Keys Check The browser Comptabilty ")
        return;
    }

    var plainText = document.getElementById("plainTextGCM").value;

    return crypto.subtle.encrypt({
        name: "aes-gcm",
        iv: iv,
        tagLength: 128 //can be 32, 64, 96, 104, 112, 120 or 128 (default)
    }, secretKey, asciiToUint8Array(plainText)).then(function(cipherText) {
        document.getElementById("cipherTextGCM").value = bytesToHexString(cipherText);
    }, failAndLog);

}

function AES256_GCM_decrypt() {

    if (secretKey == null) {
        alert("Failed to Generate AES Keys Check The browser Comptabilty ")
        return;
    }

    var cipherText = document.getElementById("cipherTextGCM").value;
    crypto.subtle.decrypt({
            name: "aes-gcm",
            iv: iv,
            tagLength: 128 //can be 32, 64, 96, 104, 112, 120 or 128 (default)
        },
        secretKey,
        hexStringToUint8Array(cipherText)
    ).then(
        function(plainText) {
            document.getElementById("resultGCM").innerHTML = "Result: " + bytesToASCIIString(plainText);
        },
        function(result) {
            document.getElementById("resultGCM").innerHTML = "Result: " + result;
        });
}

The HTML

 <div>
    Plain Text: <input type="text" id="plainTextGCM" value="Hello 8gwifi.org">
    <button type="button" onclick="AES256_GCM_ENCRYPT()">AES256-GCM-ENCRYPT</button>
</div>
<div>
    Cipher Text: <input type="text" id="cipherTextGCM" size="50">
    <button type="button" onclick="AES256_GCM_decrypt()">AES256_GCM_decrypt</button>
</div>
<div id="resultGCM">
    Result:
</div>

Download the sample code here
Next Reading Perform AES Encryption Using importKey Method

Thanku for reading !!! Give a Share for Support

Asking for donation sound bad to me, so i'm raising fund from The Modern Cryptography CookBook for Just $9. Leanpub books Discount coupon first 100 reader. No hurry read the sample chapters here then decide.

Alternatively to support you can buy My all four Cryptography book Just $10.99


Referefce
  • The Modern Cryptography Book.
  • Go lang Cryptography for developers
  • Python Cryptography
  • Cryptography for JavaScript Developer


python Cryptography Topics
Topics
For Coffee/ Beer/ Amazon Bill and further development of the project Support by Purchasing, The Modern Cryptography CookBook for Just $9 Coupon Price

Cryptography for Python Developers

Cryptography for JavaScript Developers

Go lang ryptography for Developers

Here