forked from NdoleStudio/httpsms-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcipher-service.ts
More file actions
44 lines (39 loc) · 985 Bytes
/
cipher-service.ts
File metadata and controls
44 lines (39 loc) · 985 Bytes
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
import {
randomBytes,
createCipheriv,
createHash,
createDecipheriv,
} from 'node:crypto';
import {Buffer} from 'node:buffer';
class CipherService {
public encrypt(key: string, message: string): string {
const iv = randomBytes(16);
const cipher = createCipheriv(
'aes-256-cfb',
this.hash(key),
iv,
).setAutoPadding(false);
return Buffer.concat([
iv,
cipher.update(message, 'utf8'),
cipher.final(),
]).toString('base64');
}
public decrypt(key: string, message: string): string {
const cipherBytes = Buffer.from(message, 'base64');
const iv = cipherBytes.subarray(0, 16);
const decipher = createDecipheriv(
'aes-256-cfb',
this.hash(key),
iv,
).setAutoPadding(false);
return Buffer.concat([
decipher.update(cipherBytes.subarray(16, cipherBytes.length)),
decipher.final(),
]).toString();
}
private hash(value: string): Uint8Array {
return createHash('sha256').update(value).digest();
}
}
export default CipherService;