UNPKG

1.84 kBJavaScriptView Raw
1/**
2 * RSA-OAEP is an asymmetric keypair used for encryption
3 */
4
5import * as webcrypto from 'lib0/webcrypto'
6export { exportKeyJwk } from './common.js'
7
8/**
9 * @typedef {Array<'encrypt'|'decrypt'>} Usages
10 */
11
12/**
13 * @type {Usages}
14 */
15const defaultUsages = ['encrypt', 'decrypt']
16
17/**
18 * Note that the max data size is limited by the size of the RSA key.
19 *
20 * @param {CryptoKey} key
21 * @param {Uint8Array} data
22 * @return {PromiseLike<Uint8Array>}
23 */
24export const encrypt = (key, data) =>
25 webcrypto.subtle.encrypt(
26 {
27 name: 'RSA-OAEP'
28 },
29 key,
30 data
31 ).then(buf => new Uint8Array(buf))
32
33/**
34 * @experimental The API is not final!
35 *
36 * Decrypt some data using AES-GCM method.
37 *
38 * @param {CryptoKey} key
39 * @param {Uint8Array} data
40 * @return {PromiseLike<Uint8Array>} decrypted buffer
41 */
42export const decrypt = (key, data) =>
43 webcrypto.subtle.decrypt(
44 {
45 name: 'RSA-OAEP'
46 },
47 key,
48 data
49 ).then(data => new Uint8Array(data))
50
51/**
52 * @param {Object} opts
53 * @param {boolean} [opts.extractable]
54 * @param {Usages} [opts.usages]
55 * @return {Promise<CryptoKeyPair>}
56 */
57export const generateKeyPair = ({ extractable = false, usages = defaultUsages } = {}) =>
58 webcrypto.subtle.generateKey(
59 {
60 name: 'RSA-OAEP',
61 modulusLength: 4096,
62 publicExponent: new Uint8Array([1, 0, 1]),
63 hash: 'SHA-256'
64 },
65 extractable,
66 usages
67 )
68
69/**
70 * @param {any} jwk
71 * @param {Object} opts
72 * @param {boolean} [opts.extractable]
73 * @param {Usages} [opts.usages]
74 */
75export const importKeyJwk = (jwk, { extractable = false, usages } = {}) => {
76 if (usages == null) {
77 /* c8 ignore next */
78 usages = jwk.key_ops || defaultUsages
79 }
80 return webcrypto.subtle.importKey('jwk', jwk, { name: 'RSA-OAEP', hash: 'SHA-256' }, extractable, /** @type {Usages} */ (usages))
81}