W3C Web Cryptography (WebCrypto) API は,Webアプリケーションで基本的な暗号認証機能を実現するための JavaScript API を定義しています. WebCrypto APIを使うと,JavaScript で暗号化・復号,署名生成・検証等の暗号認証処理を実現できます. (→ Web Cryptography API Tutorial)
WebCrypto API は,Chrome,Firefox など主要な Webブラウザで実装されています.
主要な Webブラウザ毎の実装サポート状況は以下です.
なお,Chrome では現状,HTTPS などセキュアな環境でない場合,未定義な API になるようです.但し,HTTP でもローカルなマシン上ならば動作します.
WebCrypto API は,次の機能にアクセスするインターフェイスを定義しています.
利用できる暗号認証アルゴリズムは以下です (2017.10 現在) .
WebCrypto API のハッシュ関数,暗号化,鍵生成などの関数(メソッド)は,乱数生成を除いて全て "window.crypto.subtle" の名前空間に入っています(Firefox, Chrome など).
API の殆ど全ての暗号機能は非同期実行 API になっています. 各関数の戻り値は,非同期実行のための Promiseオブジェクトと呼ばれる値として返されます.非同期処理が終わった際に実行する関数や,エラーが起きた際に実行する処理を then()メソッドで定義します. (→ Promise)
主なメソッドの API を示します.(→ SubtleCrypto)
Promise<any> encrypt(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data);
Promise<any> decrypt(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data);
Promise<any> sign(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource data);
Promise<any> verify(AlgorithmIdentifier algorithm, CryptoKey key, BufferSource signature, BufferSource data);
Promise<any> digest(AlgorithmIdentifier algorithm, BufferSource data);
Promise<any> generateKey(AlgorithmIdentifier algorithm, boolean extractable, sequence <KeyUsage> keyUsages );
var encoder = new TextEncoder('utf-8'); var clearDataArrayBufferView = encoder.encode("Plain Text Data"); var aesAlgorithmKeyGen = { name: "AES-CBC", length: 128 }; var aesAlgorithmEncrypt = { name: "AES-CBC", iv: window.crypto.getRandomValues(new Uint8Array(16)) }; window.crypto.subtle.generateKey(aesAlgorithmKeyGen, false, ["encrypt"]).then( function(aesKey) { return window.crypto.subtle.encrypt(aesAlgorithmEncrypt, aesKey, [ clearDataArrayBufferView ]); } ).then(console.log.bind(console, "The ciphertext is: "), console.error.bind(console, "Unable to encrypt"));
var encoder = new TextEncoder('utf-8'); var algorithmKeyGen = { name: "RSASSA-PKCS1-v1_5", modulusLength: 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // e = 65537 hash: { name: "SHA-256" } }; var algorithmSign = { name: "RSASSA-PKCS1-v1_5" }; window.crypto.subtle.generateKey(algorithmKeyGen, false, ["sign"]).then( function(key) { var dataPart1 = encoder.encode("hello,"); var dataPart2 = encoder.encode(" world!"); return window.crypto.subtle.sign(algorithmSign, key.privateKey, [dataPart1, dataPart2]); }, console.error.bind(console, "Unable to generate a key") ).then( console.log.bind(console, "The signature is: "), console.error.bind(console, "Unable to sign") );