Open in a new tab

SHA-256, AES-256-GCM and ECDSA P-256 through crypto.subtle with fw's async wrappers, and an explicit unsupported state when crypto.subtle is missing.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

When the browser's own implementation is what you want: hardware speed, non-extractable keys, and algorithms the platform already audits. The tier needs a secure context (https: or localhost); fw's pure-JavaScript tier (fw/crypto-hash, fw/crypto-aead, fw/crypto-signature) runs anywhere.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html over https: or localhost. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Keep the isAvailable() check and the unsupported message.

What it shows

  • webcryptoDigest.sha256(bytes); webcryptoAes.generateKey('GCM', 256), encryptGcm(key, iv, plaintext) returning ciphertext||tag, decryptGcm returning false on a bad tag.
  • webcryptoEcc.generateKey('ECDSA', 'P-256'), sign, verify.
  • Every call is a promise; false is the wrapper's failure value, and the page turns a failure into a "failed: …" status instead of a silent blank.
  • The IV comes from fw's random, the hex from fw's hex codec.
  • The same SHA-256 answers as the pure-JavaScript tier.

Code

main.js

javascriptApache-2.078 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { webcryptoDigest } from '@awacloud/fw/crypto/webcrypto/digest.js';
import { webcryptoAes } from '@awacloud/fw/crypto/webcrypto/aes.js';
import { webcryptoEcc } from '@awacloud/fw/crypto/webcrypto/ecc.js';
import { random } from '@awacloud/fw/crypto/utils/random.js';
import { hex } from '@awacloud/fw/io/codec/hex.js';

fw.runtime.registerAllDeep([webcryptoDigest, webcryptoAes, webcryptoEcc, random, hex]);
const DIGEST = fw.runtime.resolve('webcryptoDigest');
const AES = fw.runtime.resolve('webcryptoAes');
const ECC = fw.runtime.resolve('webcryptoEcc');
const RANDOM = fw.runtime.resolve('random');
const HEX = fw.runtime.resolve('hex');

const encoder = new TextEncoder();
const decoder = new TextDecoder();

/** `crypto.subtle` needs a secure context (https or localhost). */
export const available = DIGEST.isAvailable() && AES.isAvailable() && ECC.isAvailable();

/** @param {string} message @returns {Promise<string>} hex */
export async function sha256(message) {
    const out = await DIGEST.sha256(encoder.encode(message));
    if (!out) throw new Error('digest failed');
    return HEX.fromBytes(out);
}

/** AES-256-GCM, fresh key, random 96-bit IV: ciphertext||tag, and `false` on a bad tag. @param {string} message */
export async function aesGcmRoundTrip(message) {
    const key = await AES.generateKey('GCM', 256);
    if (!key) throw new Error('key generation failed');
    const iv = /** @type {Uint8Array} */ (RANDOM.bytes(12));
    const sealed = await AES.encryptGcm(key, iv, encoder.encode(message));
    if (!sealed) throw new Error('encryption failed');
    const opened = await AES.decryptGcm(key, iv, sealed);
    const tampered = sealed.slice();
    tampered[0] ^= 1;
    const back = opened ? decoder.decode(opened) : null;
    const tamperedRejected = (await AES.decryptGcm(key, iv, tampered)) === false;
    return { iv: HEX.fromBytes(iv), sealed: HEX.fromBytes(sealed), back, tamperedRejected };
}

/** ECDSA P-256 / SHA-256: sign, verify, and reject a changed message. @param {string} message */
export async function ecdsaRoundTrip(message) {
    const pair = await ECC.generateKey('ECDSA', 'P-256');
    if (!pair) throw new Error('key generation failed');
    const signature = await ECC.sign(pair.privateKey, encoder.encode(message));
    if (!signature) throw new Error('signing failed');
    return {
        signature: HEX.fromBytes(signature),
        ok: await ECC.verify(pair.publicKey, signature, encoder.encode(message)),
        changedOk: await ECC.verify(pair.publicKey, signature, encoder.encode(`${message}!`)),
    };
}

/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };
const message = /** @type {HTMLInputElement} */ (document.getElementById('message'));

export async function update() {
    if (!available) return show('status', 'crypto.subtle is not available here: open the page over https or localhost');
    try {
        show('digest', await sha256(message.value));
        const aes = await aesGcmRoundTrip(message.value);
        show('aes', `${aes.iv} · ${aes.sealed}`);
        show('aes-back', `${aes.back} (tampered copy rejected: ${aes.tamperedRejected})`);
        const ecdsa = await ecdsaRoundTrip(message.value);
        show('ecdsa', ecdsa.signature);
        show('ecdsa-ok', `${ecdsa.ok} (changed message: ${ecdsa.changedOk})`);
        show('status', 'native WebCrypto');
    } catch (err) {
        show('status', `failed: ${/** @type {Error} */ (err).message}`);
    }
}

message.addEventListener('change', update);
await update();

index.html

htmlApache-2.029 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · The native WebCrypto tier</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>The native WebCrypto tier</h1>
    <label for="message">Message</label>
    <input id="message" type="text" value="abc" autocomplete="off">
    <p id="status" aria-live="polite"></p>
    <dl>
      <dt>SHA-256</dt><dd><code id="digest"></code></dd>
      <dt>AES-256-GCM (iv · ciphertext+tag), decrypted back</dt>
        <dd><code id="aes"></code> → <output id="aes-back"></output></dd>
      <dt>ECDSA P-256 signature, verifies</dt><dd><code id="ecdsa"></code> → <output id="ecdsa-ok"></output></dd>
    </dl>
  </main>
</body>
</html>