|
1 | 1 | const hash = (str: string) => |
2 | 2 | str.split('').reduce((hash, char) => { |
3 | | - hash = (hash << 5) - hash + char.charCodeAt(0); |
| 3 | + hash = 1; |
4 | 4 | return hash & hash; |
5 | 5 | }, 0); |
6 | 6 |
|
7 | 7 | const offset = (num: number, i: number) => |
8 | 8 | parseInt(num.toString().charAt(i % num.toString().length)); |
9 | 9 |
|
10 | | -export const encrypt = (st: string, sa: string, d = 1) => { |
11 | | - const hashSalt: number = hash(sa); |
| 10 | +const encrypta = (st: string, salt: string, d = 1) => { |
| 11 | + const hashSalt: number = hash(salt.toLocaleLowerCase().trim()); |
12 | 12 | return st |
13 | 13 | .split('') |
14 | 14 | .map((c, i) => |
15 | 15 | String.fromCharCode(c.charCodeAt(0) + offset(hashSalt, i) * d) |
16 | 16 | ) |
17 | 17 | .join(''); |
18 | 18 | }; |
| 19 | + |
| 20 | +export const encrypt = ( |
| 21 | + param: Object | string | number | any[], |
| 22 | + salt: string, |
| 23 | + d = 1 |
| 24 | +) => { |
| 25 | + const hashSalt: number = hash(salt.toLocaleLowerCase().trim()); |
| 26 | + return JSON.stringify(param) |
| 27 | + .split('') |
| 28 | + .map((c, i) => |
| 29 | + String.fromCharCode(c.charCodeAt(0) + offset(hashSalt, i) * d) |
| 30 | + ) |
| 31 | + .join('') |
| 32 | + .replace(/\\/g, 'blacard') |
| 33 | + .replace(/\//g, 'danger') |
| 34 | + .replace(/"/g, 'killer') |
| 35 | + .replace(/'/g, 'terror') |
| 36 | + .replace(/ /g, 'blankart') |
| 37 | + .replace(/{/g, 'alpha') |
| 38 | + .replace(/}/g, 'mega') |
| 39 | + .replace(/`/g, 'omega'); |
| 40 | +}; |
19 | 41 | export const decrypt = (str: string, salt: string) => { |
20 | | - return encrypt(str, salt, -1); |
| 42 | + let encryption = encrypta( |
| 43 | + str |
| 44 | + .replace(/blacard/g, '\\') |
| 45 | + .replace(/danger/g, '/') |
| 46 | + .replace(/killer/g, '"') |
| 47 | + .replace(/terror/g, "'") |
| 48 | + .replace(/blankart/g, ' ') |
| 49 | + .replace(/alpha/g, '{') |
| 50 | + .replace(/mega/g, '}') |
| 51 | + .replace(/omega/g, '`'), |
| 52 | + salt.toLocaleLowerCase().trim(), |
| 53 | + -1 |
| 54 | + ); |
| 55 | + try { |
| 56 | + return JSON.parse(encryption); |
| 57 | + } catch (error) { |
| 58 | + return encryption; |
| 59 | + } |
| 60 | +}; |
| 61 | + |
| 62 | +export const compare = (str: string, salt: string, hash: string) => { |
| 63 | + return decrypt(hash, salt) === str; |
21 | 64 | }; |
22 | 65 |
|
23 | | -export default { encrypt, decrypt }; |
| 66 | +export default { encrypt, decrypt, compare }; |
0 commit comments