forked from UniiemStudio/CTFever
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoreValuesCipher.js
119 lines (107 loc) · 2.46 KB
/
coreValuesCipher.js
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"use strict";
function assert(...express) {
const l = express.length;
const msg = (typeof express[l - 1] === 'string') ? express[l - 1] : 'Assert Error';
for (let b of express) {
if (!b) {
throw new Error(msg);
}
}
}
function randBin() {
return Math.random() >= 0.5;
}
const values = '富强民主文明和谐自由平等公正法治爱国敬业诚信友善';
function str2utf8(str) {
const notEncoded = /[A-Za-z\d\-_.!~*'()]/g;
const str1 = str.replace(notEncoded, c => c.codePointAt(0).toString(16));
let str2 = encodeURIComponent(str1);
return str2.replace(/%/g, '').toUpperCase();
}
function utf82str(utfs) {
assert(typeof utfs === 'string', 'utfs Error');
const l = utfs.length;
assert((l & 1) === 0);
const split = [];
for (let i = 0; i < l; i++) {
if ((i & 1) === 0) {
split.push('%');
}
split.push(utfs[i]);
}
return decodeURIComponent(split.join(''));
}
function hex2duo(hexs) {
// duodecimal in array of number
// '0'.. '9' -> 0.. 9
// 'A'.. 'F' -> 10, c - 10 a2fFlag = 10
// or 11, c - 6 a2fFlag = 11
assert(typeof hexs === 'string')
const duo = [];
for (let c of hexs) {
const n = Number.parseInt(c, 16);
if (n < 10) {
duo.push(n);
} else {
if (randBin()) {
duo.push(10);
duo.push(n - 10);
} else {
duo.push(11);
duo.push(n - 6);
}
}
}
return duo;
}
function duo2hex(duo) {
assert(duo instanceof Array);
const hex = [];
const l = duo.length;
let i = 0;
while (i < l) {
if (duo[i] < 10) {
hex.push(duo[i]);
} else {
if (duo[i] === 10) {
i++;
hex.push(duo[i] + 10);
} else {
i++;
hex.push(duo[i] + 6);
}
}
i++;
}
// noinspection JSCheckFunctionSignatures
return hex.map(v => v.toString(16).toUpperCase()).join('');
}
function duo2values(duo) {
return duo.map(d => values[2 * d] + values[2 * d + 1]).join('');
}
function valuesDecode(cipher) {
const duo = [];
for (let c of cipher) {
const i = values.indexOf(c);
if (i === -1) {
} else if (i & 1) {
} else {
duo.push(i >> 1);
}
}
const hexs = duo2hex(duo);
assert((hexs.length & 1) === 0);
let str;
try {
str = utf82str(hexs);
} catch (e) {
throw e;
}
return str;
}
function valuesEncode(str) {
return duo2values(hex2duo(str2utf8(str)));
}
module.exports = {
coreValuesEncode: valuesEncode, coreValuesDecode: valuesDecode
}