-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.js
77 lines (68 loc) · 2.39 KB
/
crypto.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/* eslint-disable no-bitwise */
/** @typedef {CryptoKey} CryptoUtilsExport */
import { parseAlgorithmIdentifier } from '../lib/jwa.js';
import { uint8ArrayFromUtf8 } from './utf8.js';
/** @type {Crypto} */
// eslint-disable-next-line unicorn/no-await-expression-member
export const crypto = globalThis.crypto ?? (await import(new URL('node:crypto').toString())).webcrypto;
/**
* @param {JWK} jwk
* @param {Parameters<SubtleCrypto['importKey']>[2]} algorithmIdentifier
* @return {Promise<CryptoUtilsExport>}
*/
export async function importJWK(jwk, algorithmIdentifier) {
return await crypto.subtle.importKey(
'jwk',
jwk,
parseAlgorithmIdentifier(algorithmIdentifier),
false,
jwk.key_ops ?? ['sign', 'verify'],
);
}
/**
* @param {Parameters<SubtleCrypto['sign']>[0]} algorithmIdentifier
* @param {CryptoUtilsExport} key
* @param {string|BufferSource} data
* @return {Promise<ArrayBuffer>}
*/
export async function sign(algorithmIdentifier, key, data) {
const binary = typeof data === 'string' ? uint8ArrayFromUtf8(data) : data;
return await crypto.subtle.sign(algorithmIdentifier, key, binary);
}
/**
* @param {Parameters<SubtleCrypto['verify']>[0]} algorithmIdentifier
* @param {CryptoUtilsExport} key
* @param {BufferSource} signature
* @param {BufferSource} data
* @return {Promise<boolean>}
*/
export async function verify(algorithmIdentifier, key, signature, data) {
return await crypto.subtle.verify(algorithmIdentifier, key, signature, data);
}
/**
* @param {Parameters<SubtleCrypto['encrypt']>[0]} algorithmIdentifier
* @param {CryptoUtilsExport} key
* @param {BufferSource} data
* @return {Promise<ArrayBuffer>}
*/
export async function encrypt(algorithmIdentifier, key, data) {
return await crypto.subtle.encrypt(algorithmIdentifier, key, data);
}
/**
* @param {Parameters<SubtleCrypto['decrypt']>[0]} algorithmIdentifier
* @param {CryptoUtilsExport} key
* @param {BufferSource} data
* @return {Promise<ArrayBuffer>}
*/
export async function decrypt(algorithmIdentifier, key, data) {
return await crypto.subtle.decrypt(algorithmIdentifier, key, data);
}
/**
* @param {'SHA-1'|'SHA-256'|'SHA-384'|'SHA-512'} algorithm
* @param {string|BufferSource} data
* @return {Promise<ArrayBuffer>}
*/
export async function digest(algorithm, data) {
const binary = typeof data === 'string' ? uint8ArrayFromUtf8(data) : data;
return await crypto.subtle.digest(algorithm, binary);
}