SubtleCrypto 对象支持使用公钥和对称算法加密和解密消息。这两种操作分别通过SubtleCrypto.
encrypt()和SubtleCrypto.decrypt()方法完成。
加密消息需要传入参数对象以指定算法和必要的值、加密密钥和要加密的数据。下面的例子会生成
对称AES-CBC 密钥,用它加密消息,最后解密消息:
(async function() {
const algoIdentifier = ‘AES-CBC’;
const keyParams = {
name: algoIdentifier,
length: 256
};
const keyUsages = [‘encrypt’, ‘decrypt’];
const key = await crypto.subtle.generateKey(keyParams, true,
keyUsages);
const originalPlaintext = (new TextEncoder()).encode(‘I am Satoshi Nakamoto’);
const encryptDecryptParams = {
name: algoIdentifier,
iv: crypto.getRandomValues(new Uint8Array(16))
};
const ciphertext = await crypto.subtle.encrypt(encryptDecryptParams, key,
originalPlaintext);
console.log(ciphertext);
// ArrayBuffer(32) {}
const decryptedPlaintext = await crypto.subtle.decrypt(encryptDecryptParams, key,
ciphertext);
console.log((new TextDecoder()).decode(decryptedPlaintext));
// I am Satoshi Nakamoto
})();
包装和解包密钥
SubtleCrypto 对象支持包装和解包密钥,以便在非信任渠道传输。这两种操作分别通过Subtle-
Crypto.wrapKey()和SubtleCrypto.unwrapKey()方法完成。
包装密钥需要传入一个格式字符串、要包装的CryptoKey 实例、要执行包装的CryptoKey,以及
一个参数对象用于指定算法和必要的值。下面的例子生成了一个对称AES-GCM 密钥,用AES-KW 来
包装这个密钥,最后又将包装的密钥解包:
(async function() {
const keyFormat = ‘raw’;
const extractable = true;
const wrappingKeyAlgoIdentifier = ‘AES-KW’;
const wrappingKeyUsages = [‘wrapKey’, ‘unwrapKey’];
const wrappingKeyParams = {
name: wrappingKeyAlgoIdentifier,
length: 256
};
const keyAlgoIdentifier = ‘AES-GCM’;
const keyUsages = [‘encrypt’];
const keyParams = {
name: keyAlgoIdentifier,
length: 256
};
const wrappingKey = await crypto.subtle.generateKey(wrappingKeyParams, extractable,
wrappingKeyUsages);
console.log(wrappingKey);
// CryptoKey {type: “secret”, extractable: true, algorithm: {…}, usages: Array(2)}
const key = await crypto.subtle.generateKey(keyParams, extractable, keyUsages);
console.log(key);
// CryptoKey {type: “secret”, extractable: true, algorithm: {…}, usages: Array(1)}
const wrappedKey = await crypto.subtle.wrapKey(keyFormat, key, wrappingKey,
wrappingKeyAlgoIdentifier);
console.log(wrappedKey);
// ArrayBuffer(40) {}
const unwrappedKey = await crypto.subtle.unwrapKey(keyFormat, wrappedKey,
wrappingKey, wrappingKeyParams, keyParams, extractable, keyUsages);
console.log(unwrappedKey);
// CryptoKey {type: “secret”, extractable: true, algorithm: {…}, usages: Array(1)}
})()
小结
除了定义新标签,HTML5 还定义了一些JavaScript API。这些API 可以为开发者提供更便捷的Web
接口,暴露堪比桌面应用的能力。本章主要介绍了以下API。
Atomics API 用于保护代码在多线程内存访问模式下不发生资源争用。
postMessage() API 支持从不同源跨文档发送消息,同时保证安全和遵循同源策略。
Encoding API 用于实现字符串与缓冲区之间的无缝转换(越来越常见的操作)。
File API 提供了发送、接收和读取大型二进制对象的可靠工具。
媒体元素和拥有自己的API,用于操作音频和视频。并不是每个浏览器都会支
持所有媒体格式,使用canPlayType()方法可以检测浏览器支持情况。
拖放API 支持方便地将元素标识为可拖动,并在操作系统完成放置时给出回应。可以利用它创
建自定义可拖动元素和放置目标。
Notifications API 提供了一种浏览器中立的方式,以此向用户展示消通知弹层。
Streams API 支持以全新的方式读取、写入和处理数据。
Timing API 提供了一组度量数据进出浏览器时间的可靠工具。
Web Components API 为元素重用和封装技术向前迈进提供了有力支撑。
Web Cryptography API 让生成随机数、加密和签名消息成为一类特性。
javascript七基础学习系列三千零三十六:使用对称密钥加密和解密
猜你喜欢
转载自blog.csdn.net/m0_68635815/article/details/143462804
今日推荐
周排行