Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
98 lines (89 loc) · 2.64 KB
/
Copy pathindex.ts
File metadata and controls
98 lines (89 loc) · 2.64 KB
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
import crypto from 'crypto-js'
import forge from 'node-forge'
import { CipherOption, makeBufferChunks, wordArrayToUint8Array } from './utils'
export const encryptAES = (
buffer: Buffer,
secret: string | crypto.lib.WordArray,
config?: CipherOption
) => {
const wordArray = crypto.lib.WordArray.create(buffer as unknown as number[])
const encrypted = crypto.AES.encrypt(wordArray, secret, config)
return Buffer.from(encrypted.toString())
}
export const decryptAES = (
buffer: Buffer,
secret: string | crypto.lib.WordArray,
config?: CipherOption
) => {
const wordArray = crypto.AES.decrypt(String(buffer), secret, config)
return Buffer.from(wordArrayToUint8Array(wordArray))
}
export const encryptRabbit = (
buffer: Buffer,
secret: string | crypto.lib.WordArray,
config?: CipherOption
) => {
const wordArray = crypto.lib.WordArray.create(buffer as unknown as number[])
const encrypted = crypto.Rabbit.encrypt(wordArray, secret, config)
return Buffer.from(encrypted.toString())
}
export const decryptRabbit = (
buffer: Buffer,
secret: string | crypto.lib.WordArray,
config?: CipherOption
) => {
const wordArray = crypto.Rabbit.decrypt(String(buffer), secret, config)
return Buffer.from(wordArrayToUint8Array(wordArray))
}
const _encryptPKI = (buffer: Buffer, publicKey: string) => {
return Buffer.from(
forge.pki
.publicKeyFromPem(publicKey)
.encrypt(forge.util.encodeUtf8(buffer.toString('base64')))
)
}
export const encryptPKI = (buffer: Buffer, publicKey: string) => {
const chunks = makeBufferChunks(buffer, 183)
.map((chunk) => _encryptPKI(chunk, publicKey).toString('base64'))
.join(',')
return Buffer.from(chunks)
}
const _decryptPKI = (encrypted: Buffer, privateKey: string) => {
return Buffer.from(
forge.pki.privateKeyFromPem(privateKey).decrypt(encrypted.toString()),
'base64'
)
}
export const decryptPKI = (encrypted: Buffer, privateKey: string) => {
const chunks = encrypted
.toString()
.split(',')
.map((chunk) => _decryptPKI(Buffer.from(chunk, 'base64'), privateKey))
return Buffer.concat(chunks)
}
export const generatePKIKeyPair = (
options: forge.pki.rsa.GenerateKeyPairOptions = {
bits: 2048,
workers: 2,
e: 0x10001
}
): Promise<
| {
publicKey: string
privateKey: string
}
| undefined
> => {
return new Promise((resolve) => {
forge.pki.rsa.generateKeyPair(options, (error, keypair) => {
if (error) {
resolve(undefined)
} else {
resolve({
publicKey: forge.pki.publicKeyToPem(keypair.publicKey),
privateKey: forge.pki.privateKeyToPem(keypair.privateKey)
})
}
})
})
}