This repository has been archived by the owner on Jul 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
/
rsa.ts
69 lines (58 loc) · 2.24 KB
/
rsa.ts
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
import crypto from 'crypto'
import { promisify } from 'util'
import { CodeError } from '@libp2p/interfaces/errors'
import randomBytes from '../random-bytes.js'
import * as utils from './rsa-utils.js'
import type { JWKKeyPair } from './interface.js'
const keypair = promisify(crypto.generateKeyPair)
export { utils }
export async function generateKey (bits: number): Promise<JWKKeyPair> { // eslint-disable-line require-await
// @ts-expect-error node types are missing jwk as a format
const key = await keypair('rsa', {
modulusLength: bits,
publicKeyEncoding: { type: 'pkcs1', format: 'jwk' },
privateKeyEncoding: { type: 'pkcs1', format: 'jwk' }
})
return {
// @ts-expect-error node types are missing jwk as a format
privateKey: key.privateKey,
// @ts-expect-error node types are missing jwk as a format
publicKey: key.publicKey
}
}
// Takes a jwk key
export async function unmarshalPrivateKey (key: JsonWebKey): Promise<JWKKeyPair> { // eslint-disable-line require-await
if (key == null) {
throw new CodeError('Missing key parameter', 'ERR_MISSING_KEY')
}
return {
privateKey: key,
publicKey: {
kty: key.kty,
n: key.n,
e: key.e
}
}
}
export { randomBytes as getRandomValues }
export async function hashAndSign (key: JsonWebKey, msg: Uint8Array): Promise<Uint8Array> {
return crypto.createSign('RSA-SHA256')
.update(msg)
// @ts-expect-error node types are missing jwk as a format
.sign({ format: 'jwk', key })
}
export async function hashAndVerify (key: JsonWebKey, sig: Uint8Array, msg: Uint8Array): Promise<boolean> { // eslint-disable-line require-await
return crypto.createVerify('RSA-SHA256')
.update(msg)
// @ts-expect-error node types are missing jwk as a format
.verify({ format: 'jwk', key }, sig)
}
const padding = crypto.constants.RSA_PKCS1_PADDING
export function encrypt (key: JsonWebKey, bytes: Uint8Array): Uint8Array {
// @ts-expect-error node types are missing jwk as a format
return crypto.publicEncrypt({ format: 'jwk', key, padding }, bytes)
}
export function decrypt (key: JsonWebKey, bytes: Uint8Array): Uint8Array {
// @ts-expect-error node types are missing jwk as a format
return crypto.privateDecrypt({ format: 'jwk', key, padding }, bytes)
}