This repository has been archived by the owner on Mar 9, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
concealer.ts
60 lines (43 loc) · 1.48 KB
/
concealer.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
var Skip32: any = require('skip32').Skip32;
var Hashids: any = require('hashids');
// Public methods
export class Concealer {
private skip32: any;
private hashids: any;
constructor(private secretKey: number[], private salt: string,
private minLength = 1, private customAlphabet?: string) {
if (!secretKey) {
throw new Error('Secret Key must be provided');
}
if (!salt) {
throw new Error('Salt must be provided');
}
if (!Array.isArray(secretKey) || !secretKey.length || !secretKey.every(isByte)) {
throw new TypeError('Secret Key must be an Array of bytes represented by integers');
}
if (minLength !== undefined && !Number.isInteger(minLength)) {
throw new TypeError('Min Length must be an integer, if provided');
}
this.skip32 = new Skip32(secretKey);
this.hashids = new Hashids(salt, minLength || 1, customAlphabet);
}
encode(key: number): string {
if (!Number.isInteger(key) || key < 0) {
throw new TypeError('Key must be a non-negative integer');
}
const encrypted = this.skip32.encrypt(key);
return this.hashids.encode(encrypted);
}
decode(key: string): number {
const encrypted = this.hashids.decode(key)[0];
if (encrypted === undefined) {
return null;
}
return this.skip32.decrypt(encrypted);
}
}
// Private methods
// Returns whether a given value represents a single byte
function isByte(val: number) {
return Number.isInteger(val) && val >= 0 && val <= 255;
};