使用SubtleCrypto 对象可以通过可配置的属性从已有密钥获得新密钥。SubtleCrypto 支持一
个deriveKey()方法和一个deriveBits()方法,前者返回一个解决为CryptoKey 的期约,后者返回
一个解决为ArrayBuffer 的期约。
deriveBits()方法接收一个算法参数对象、主密钥和输出的位长作为参数。当两个人分别拥有自
己的密钥对,但希望获得共享的加密密钥时可以使用这个方法。下面的例子使用ECDH 算法基于两个密
钥对生成了对等密钥,并确保它们派生相同的密钥位:
(async function() {
const ellipticCurve = ‘P-256’;
const algoIdentifier = ‘ECDH’;
const derivedKeySize = 128;
const params = {
name: algoIdentifier,
namedCurve: ellipticCurve
};
const keyUsages = [‘deriveBits’];
const keyPairA = await crypto.subtle.generateKey(params, true, keyUsages);
const keyPairB = await crypto.subtle.generateKey(params, true, keyUsages);
// 从A 的公钥和B 的私钥派生密钥位
const derivedBitsAB = await crypto.subtle.deriveBits(
Object.assign({ public: keyPairA.publicKey }, params),
keyPairB.privateKey,
derivedKeySize);
// 从B 的公钥和A 的私钥派生密钥位
const derivedBitsBA = await crypto.subtle.deriveBits(
Object.assign({ public: keyPairB.publicKey }, params),
keyPairA.privateKey,
derivedKeySize);
const arrayAB = new Uint32Array(derivedBitsAB);
const arrayBA = new Uint32Array(derivedBitsBA);
// 确保密钥数组相等
console.log(
arrayAB.length === arrayBA.length &&
arrayAB.every((val, i) => val === arrayBA[i])); // true
})();
deriveKey()方法是类似的,只不过返回的是CryptoKey 的实例而不是ArrayBuffer。下面的
例子基于一个原始字符串,应用PBKDF2 算法将其导入一个原始主密钥,然后派生了一个AES-GCM格
式的新密钥:
(async function() {
const password = ‘foobar’;
const salt = crypto.getRandomValues(new Uint8Array(16));
const algoIdentifier = ‘PBKDF2’;
const keyFormat = ‘raw’;
const isExtractable = false;
const params = {
name: algoIdentifier
};
const masterKey = await window.crypto.subtle.importKey(
keyFormat,
(new TextEncoder()).encode(password),
params,
isExtractable,
[‘deriveKey’]
);
const deriveParams = {
name: ‘AES-GCM’,
length: 128
};
const derivedKey = await window.crypto.subtle.deriveKey(
Object.assign({salt, iterations: 1E5, hash: ‘SHA-256’}, params),
masterKey,
deriveParams,
isExtractable,
[‘encrypt’]
);
console.log(derivedKey);
// CryptoKey {type: “secret”, extractable: false, algorithm: {…}, usages: Array(1)}
})();
javascript基础学习系列八百九十四:从主密钥派生密钥
最新推荐文章于 2024-07-28 00:13:26 发布