-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
keystore.ts
102 lines (85 loc) · 2.51 KB
/
keystore.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import IDB from '../idb'
import keys from './keys'
import operations from './operations'
import config from '../config'
import utils from '../utils'
import KeyStoreBase from '../keystore/base'
import { KeyStore, Config, KeyUse, CryptoSystem, Msg, PublicKey } from '../types'
export class RSAKeyStore extends KeyStoreBase implements KeyStore {
static async init(maybeCfg?: Partial<Config>): Promise<RSAKeyStore> {
const cfg = config.normalize({
...(maybeCfg || {}),
type: CryptoSystem.RSA
})
const { rsaSize, hashAlg, storeName, readKeyName, writeKeyName } = cfg
const store = IDB.createStore(storeName)
await IDB.createIfDoesNotExist(readKeyName, () => (
keys.makeKeypair(rsaSize, hashAlg, KeyUse.Read)
), store)
await IDB.createIfDoesNotExist(writeKeyName, () => (
keys.makeKeypair(rsaSize, hashAlg, KeyUse.Write)
), store)
return new RSAKeyStore(cfg, store)
}
async sign(msg: Msg, cfg?: Partial<Config>): Promise<string> {
const mergedCfg = config.merge(this.cfg, cfg)
const writeKey = await this.writeKey()
return utils.arrBufToBase64(await operations.sign(
msg,
writeKey.privateKey,
mergedCfg.charSize
))
}
async verify(
msg: string,
sig: string,
publicKey: string | PublicKey,
cfg?: Partial<Config>
): Promise<boolean> {
const mergedCfg = config.merge(this.cfg, cfg)
return operations.verify(
msg,
sig,
publicKey,
mergedCfg.charSize,
mergedCfg.hashAlg
)
}
async encrypt(
msg: Msg,
publicKey: string | PublicKey,
cfg?: Partial<Config>
): Promise<string> {
const mergedCfg = config.merge(this.cfg, cfg)
return utils.arrBufToBase64(await operations.encrypt(
msg,
publicKey,
mergedCfg.charSize,
mergedCfg.hashAlg
))
}
async decrypt(
cipherText: Msg,
publicKey?: string | PublicKey, // unused param so that keystore interfaces match
cfg?: Partial<Config>
): Promise<string> {
const readKey = await this.readKey()
const mergedCfg = config.merge(this.cfg, cfg)
return utils.arrBufToStr(
await operations.decrypt(
cipherText,
readKey.privateKey,
),
mergedCfg.charSize
)
}
async publicReadKey(): Promise<string> {
const readKey = await this.readKey()
return operations.getPublicKey(readKey)
}
async publicWriteKey(): Promise<string> {
const writeKey = await this.writeKey()
return operations.getPublicKey(writeKey)
}
}
export default RSAKeyStore