48 lines
956 B
TypeScript
48 lines
956 B
TypeScript
const subtle = globalThis.crypto.subtle;
|
|
|
|
export type ValidEncAlg = 'AES256-GCM' | 'AES128-GCM' | 'AES256-CBC' | 'AES128-CBC';
|
|
|
|
const encAlgMap: Record<ValidEncAlg, AesDerivedKeyParams> = {
|
|
'AES256-GCM': {
|
|
name: 'AES-GCM',
|
|
length: 256,
|
|
},
|
|
'AES128-GCM' : {
|
|
name: 'AES-GCM',
|
|
length: 128,
|
|
},
|
|
'AES256-CBC' : {
|
|
name: 'AES-CBC',
|
|
length: 256,
|
|
},
|
|
'AES128-CBC' : {
|
|
name: 'AES-CBC',
|
|
length: 128,
|
|
},
|
|
}
|
|
|
|
export async function PBKDF2_SHA512(password: string, salt: BufferSource, alg: ValidEncAlg = 'AES256-GCM', iterations = 600000): Promise<CryptoKey> {
|
|
const param: Pbkdf2Params = {
|
|
name: 'PBKDF2',
|
|
hash: 'SHA-512',
|
|
salt: salt,
|
|
iterations,
|
|
};
|
|
|
|
const encoder = new TextEncoder();
|
|
const baseKey = await subtle.importKey(
|
|
"raw",
|
|
encoder.encode(password),
|
|
{ name: "PBKDF2" },
|
|
false,
|
|
["deriveBits", "deriveKey"]
|
|
);
|
|
|
|
return await subtle.deriveKey(
|
|
param,
|
|
baseKey,
|
|
encAlgMap[alg],
|
|
true,
|
|
["encrypt", "decrypt"]
|
|
);
|
|
} |