Read Minified Javascript Jan 24th 2021 Words: 7.1k

Background

I am trying to make a plugin that uses a 3rd party service. Lucky for me there is an web app so I can “guess” the API one by one by using Chrome Development Tools. The service is using RESTful and it seems all the arguments and and return fields are intuitive. I Thought I could finish the documentation in one night ;)

However, not all goes on well. There are two APIs that returns the data in the “encrypted” form (just obfuscated encoding actually), as in the following example:

1
{"data":"MANBAYFBUEWDOQFP62SDOXFNJFNVOYP6AJAYFBU2SAYL7PKFXLJD2SFXFBVM7MWXFORDKDOABSOPZDFMWJLQ7SWMWPKQ7AJQF7PK2XPWVM7VOY2X2SDOQXYFYEYFSFUOYYFOY6CXFDOQFVR72UMW2UASDOMW2UQF2XQF2UASYFSFSWPZYFOYASDKDOOY6CR7VDKAVDKDOABSOPZDFMWJLQ7SWMWPKQ7SWAB...truncated...OMWUQ7DFMWXRDK6BDKUYEAY6I7OYDOFBUJLABAB25="}

It looks like base32, so let’s try to decode it… and FAILED.

Nahh, it can’t be that simple, right? OK, Challenge acceppted, let’s do it the hard way.

By searching the name of the API endpoint, it is easy to locate the function used to decode the message, in this case window.bays4.d, which lies in a script tag in the header of html.

1
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.bays4=e():t.bays4=e()}(this,function(){return function(r){var n={};function o(t){if(n[t])return n[t].exports;var e=n[t]={i:t,l:!1,exports:{}};return r[t].call(e.exports,e,e.exports,o),e.l=!0,e.exports}return o.m=r,o.c=n,o.i=function(t){return t},o.d=function(t,e,r){o.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:r})},o.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return o.d(e,"a",e),e},o.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},o.p="",o(o.s=3)}([function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function n(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}}(),o=function(){function r(){!function(t,e){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")}(this)}return n(r,null,[{key:"loop",value:function(t,r){"v".repeat(t).split("").map(function(t,e){return r(e)})}}]),r}();e.default=o},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function n(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}}(),o=a(r(5)),u=a(r(0));function a(t){return t&&t.__esModule?t:{default:t}}function i(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var f=function(){function t(){i(this,t),this._char=".",this._children={}}return n(t,[{key:"getChar",value:function(){return this._char}},{key:"getChildren",value:function(){return this._children}},{key:"setChar",value:function(t){this._char=t}},{key:"setChildren",value:function(t,e){this._children[t]=e}}]),t}(),s="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",c=[1,2,2,2,2,2],l=function(){function e(t){i(this,e),this._random=new o.default,this._sign="",this._inter={},this._head=new f}return n(e,[{key:"init",value:function(t){var e=this;this._random.seed(t),this._sign=t,u.default.loop(64,function(t){e._addSymbol("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[t],c[parseInt((t+1)/11)])}),this._inter["="]="="}},{key:"_addSymbol",value:function(t,e){var r=this,n=this._head,o="";return u.default.loop(e,function(t){for(var e=s[r._random.generate(32)];e in n.getChildren()&&"."!==n.getChildren()[e].getChar();)e=s[r._random.generate(32)];o+=e,e in n.getChildren()||n.setChildren(e,new f),n=n.getChildren()[e]}),n.setChar(t),this._inter[t]=o}},{key:"decode",value:function(t){for(var e="",r=4;r<t.length;)if("="!==t[r]){for(var n=this._head;t[r]in n.getChildren();)n=n.getChildren()[t[r]],r++;e+=n.getChar()}else e+="=",r++;return e}}]),e}();e.default=l},function(module,exports,__webpack_require__){var __WEBPACK_AMD_DEFINE_ARRAY__,__WEBPACK_AMD_DEFINE_RESULT__,ya,za;ya="undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:this,za=function(global){"use strict";global=global||{};var _Base64=global.Base64,version="2.5.1",buffer;if(void 0!==module&&module.exports)try{buffer=eval("require('buffer').Buffer")}catch(t){buffer=void 0}var b64chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",b64tab=function(t){for(var e={},r=0,n=t.length;r<n;r++)e[t.charAt(r)]=r;return e}(b64chars),fromCharCode=String.fromCharCode,cb_utob=function(t){if(t.length<2)return(e=t.charCodeAt(0))<128?t:e<2048?fromCharCode(192|e>>>6)+fromCharCode(128|63&e):fromCharCode(224|e>>>12&15)+fromCharCode(128|e>>>6&63)+fromCharCode(128|63&e);var e=65536+1024*(t.charCodeAt(0)-55296)+(t.charCodeAt(1)-56320);return fromCharCode(240|e>>>18&7)+fromCharCode(128|e>>>12&63)+fromCharCode(128|e>>>6&63)+fromCharCode(128|63&e)},re_utob=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,utob=function(t){return t.replace(re_utob,cb_utob)},cb_encode=function(t){var e=[0,2,1][t.length%3],r=t.charCodeAt(0)<<16|(1<t.length?t.charCodeAt(1):0)<<8|(2<t.length?t.charCodeAt(2):0);return[b64chars.charAt(r>>>18),b64chars.charAt(r>>>12&63),2<=e?"=":b64chars.charAt(r>>>6&63),1<=e?"=":b64chars.charAt(63&r)].join("")},btoa=global.btoa?function(t){return global.btoa(t)}:function(t){return t.replace(/[\s\S]{1,3}/g,cb_encode)},_encode=buffer?buffer.from&&Uint8Array&&buffer.from!==Uint8Array.from?function(t){return(t.constructor===buffer.constructor?t:buffer.from(t)).toString("base64")}:function(t){return(t.constructor===buffer.constructor?t:new buffer(t)).toString("base64")}:function(t){return btoa(utob(t))},encode=function(t,e){return e?_encode(String(t)).replace(/[+\/]/g,function(t){return"+"==t?"-":"_"}).replace(/=/g,""):_encode(String(t))},encodeURI=function(t){return encode(t,!0)},re_btou=new RegExp(["[À-ß][€-¿]","[à-ï][€-¿]{2}","[ð-÷][€-¿]{3}"].join("|"),"g"),cb_btou=function(t){switch(t.length){case 4:var e=((7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3))-65536;return fromCharCode(55296+(e>>>10))+fromCharCode(56320+(1023&e));case 3:return fromCharCode((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return fromCharCode((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},btou=function(t){return t.replace(re_btou,cb_btou)},cb_decode=function(t){var e=t.length,r=e%4,n=(0<e?b64tab[t.charAt(0)]<<18:0)|(1<e?b64tab[t.charAt(1)]<<12:0)|(2<e?b64tab[t.charAt(2)]<<6:0)|(3<e?b64tab[t.charAt(3)]:0),o=[fromCharCode(n>>>16),fromCharCode(n>>>8&255),fromCharCode(255&n)];return o.length-=[0,0,2,1][r],o.join("")},_atob=global.atob?function(t){return global.atob(t)}:function(t){return t.replace(/\S{1,4}/g,cb_decode)},atob=function(t){return _atob(String(t).replace(/[^A-Za-z0-9\+\/]/g,""))},_decode=buffer?buffer.from&&Uint8Array&&buffer.from!==Uint8Array.from?function(t){return(t.constructor===buffer.constructor?t:buffer.from(t,"base64")).toString()}:function(t){return(t.constructor===buffer.constructor?t:new buffer(t,"base64")).toString()}:function(t){return btou(_atob(t))},decode=function(t){return _decode(String(t).replace(/[-_]/g,function(t){return"-"==t?"+":"/"}).replace(/[^A-Za-z0-9\+\/]/g,""))},noConflict=function(){var t=global.Base64;return global.Base64=_Base64,t};if(global.Base64={VERSION:version,atob:atob,btoa:btoa,fromBase64:decode,toBase64:encode,utob:utob,encode:encode,encodeURI:encodeURI,btou:btou,decode:decode,noConflict:noConflict,__buffer__:buffer},"function"==typeof Object.defineProperty){var noEnum=function(t){return{value:t,enumerable:!1,writable:!0,configurable:!0}};global.Base64.extendString=function(){Object.defineProperty(String.prototype,"fromBase64",noEnum(function(){return decode(this)})),Object.defineProperty(String.prototype,"toBase64",noEnum(function(t){return encode(this,t)})),Object.defineProperty(String.prototype,"toBase64URI",noEnum(function(){return encode(this,!0)}))}}return global.Meteor&&(Base64=global.Base64),void 0!==module&&module.exports?module.exports.Base64=global.Base64:(__WEBPACK_AMD_DEFINE_ARRAY__=[],__WEBPACK_AMD_DEFINE_RESULT__=function(){return global.Base64}.apply(exports,__WEBPACK_AMD_DEFINE_ARRAY__),void 0===__WEBPACK_AMD_DEFINE_RESULT__||(module.exports=__WEBPACK_AMD_DEFINE_RESULT__)),{Base64:global.Base64}},module.exports=za(ya)},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n,o=function(){function n(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}}(),u=r(2),a=(n=r(1))&&n.__esModule?n:{default:n},i=function(t){var e=t.charCodeAt();return 65<=e?e-65:e-65+41},f=function(){function r(){!function(t,e){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")}(this)}return o(r,null,[{key:"_checkVersion",value:function(t){return((32*i(t[0])+i(t[1]))*i(t[2])+i(t[3]))%32<=1}},{key:"d",value:function(t){if(!this._checkVersion(t))return"";var e=new a.default;e.init(t.substr(0,4));var r=e.decode(t);return u.Base64.decode(r)}}]),r}();e.default=f,t.exports=f},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function n(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}}(),o=function(){function r(){!function(t,e){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")}(this)}return n(r,null,[{key:"get",value:function(t){return t>>>0}},{key:"xor",value:function(t,e){return this.get(this.get(t)^this.get(e))}},{key:"and",value:function(t,e){return this.get(this.get(t)&this.get(e))}},{key:"mul",value:function(t,e){var r=((4294901760&t)>>>0)*e,n=(65535&t)*e;return this.get((r>>>0)+(n>>>0))}},{key:"or",value:function(t,e){return this.get(this.get(t)|this.get(e))}},{key:"not",value:function(t){return this.get(~this.get(t))}},{key:"shiftLeft",value:function(t,e){return this.get(this.get(t)<<e)}},{key:"shiftRight",value:function(t,e){return this.get(t)>>>e}},{key:"mod",value:function(t,e){return this.get(this.get(t)%e)}}]),r}();e.default=o},function(t,e,r){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=function(){function n(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,e,r){return e&&n(t.prototype,e),r&&n(t,r),t}}(),o=a(r(0)),u=a(r(4));function a(t){return t&&t.__esModule?t:{default:t}}var i=function(){function r(){!function(t,e){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")}(this),this._status=[],this._mat1=0,this._mat2=0,this._tmat=0}return n(r,[{key:"seed",value:function(e){var r=this;o.default.loop(4,function(t){e.length>t?r._status[t]=u.default.get(e.charAt(t).charCodeAt()):r._status[t]=u.default.get(110)}),this._mat1=this._status[1],this._mat2=this._status[2],this._tmat=this._status[3],this._init()}},{key:"_init",value:function(){var e=this;o.default.loop(7,function(t){e._status[t+1&3]=u.default.xor(e._status[t+1&3],t+1+u.default.mul(1812433253,u.default.xor(e._status[3&t],u.default.shiftRight(e._status[3&t],30))))}),0==(2147483647&this._status[0])&&0===this._status[1]&&0===this._status[2]&&0===this._status[3]&&(this._status[0]=66,this._status[1]=65,this._status[2]=89,this._status[3]=83),o.default.loop(8,function(){return e._next_state()})}},{key:"_next_state",value:function(){var t=void 0,e=void 0;e=this._status[3],t=u.default.xor(u.default.and(this._status[0],2147483647),u.default.xor(this._status[1],this._status[2])),t=u.default.xor(t,u.default.shiftLeft(t,1)),e=u.default.xor(e,u.default.xor(u.default.shiftRight(e,1),t)),this._status[0]=this._status[1],this._status[1]=this._status[2],this._status[2]=u.default.xor(t,u.default.shiftLeft(e,10)),this._status[3]=e,this._status[1]=u.default.xor(this._status[1],u.default.and(-u.default.and(e,1),this._mat1)),this._status[2]=u.default.xor(this._status[2],u.default.and(-u.default.and(e,1),this._mat2))}},{key:"generate",value:function(t){this._next_state();var e,r=void 0;return r=this._status[3],e=u.default.xor(this._status[0],u.default.shiftRight(this._status[2],8)),r=u.default.xor(r,e),(r=u.default.xor(u.default.and(-u.default.and(e,1),this._tmat),r))%t}}]),r}();e.default=i}])})

After change the input blob several times, I found the decryption script is generic. There is no dynamic server generated keys, that’s a good news.

Of course, many libraries in Python or Node are able to evaluate the js script directly, so you don’t need to dig into the minified shit, but I want to do it just for fun.

Workspace setup

First, fire up a new project with my old friend Webstorm.

Now create an index file which loads the messy blob and invokes the decryption method once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST</title>
<script src="./decode.js"></script>
<script>
console.log(window.bays4.d("3GL7DI5MHU7CX3RD426CX4SFIWYXWRD4DGDI5MHWRDGP25DUEQQUKQ5EDXWRJ...truncated...X2Q26GTE3UKBAWRX2Q5D4QWPNHP2DGP2BAECCX2QPB4PCXUGHQ5UGP2263JXWRJXJQDIUGD44VCXP24GJQRCPB5DW5"))
</script>
</head>
<body>

</body>
</html>

Now the code can be debugged with fancy tools like breakpoints and variable tracker.

Beautify the file

Replace !0 to true and !1 to false

Ctrl + R

Manually add curly bracket

1
2
3
4
5
6
7
// short
for (var i = 0; i < 5; i++) this_is_a_very_long_expression()

// long
for (var i = 0; i < 5; i++) {
this_is_a_very_long_expression()
}
1
2
3
4
5
6
7
8
9
// short
a == 1 && b === 2 && c !== 3 && this_is_a_very_long_expression();

// long
if (a == 1 &&
b === 2 &&
c !== 3) {
this_is_a_very_long_expression();
}

Substitute comma expression

1
2
3
4
5
6
7
// short
var a,b,c = x

// long
var a = x;
var b = x;
var c = x;
1
2
3
4
5
6
7
// short
return do_a(), b = x, do_c(y)

// long
do_a();
b = x;
return do_c(y);

Search for keyword of library

Final JS output

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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
!function (t, e) {
"object" == typeof exports && "object" == typeof module ? module.exports = e() : "function" == typeof define && define.amd ? define([], e) : "object" == typeof exports ? exports.bays4 = e() : t.bays4 = e()
}
(this, function () {
/** Module loader */
function loadModule(func) {
var n = {};

function o(t) {
if (n[t]) return n[t].exports;
var e = n[t] = {i: t, l: false, exports: {}};
return func[t].call(e.exports, e, e.exports, o), e.l = true, e.exports
}

return o.m = func, o.c = n, o.i = function (t) {
return t
}, o.d = function (t, e, r) {
o.o(t, e) || Object.defineProperty(t, e, {configurable: false, enumerable: true, get: r})
}, o.n = function (t) {
var e = t && t.__esModule ? function () {
return t.default
} : function () {
return t
};
return o.d(e, "a", e), e
}, o.o = function (t, e) {
return Object.prototype.hasOwnProperty.call(t, e)
}, o.p = "", o(o.s = 3)
}

return loadModule([
/** Looper class */
function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
const setClassFunc = function () {
function n(t, e) {
for (var r = 0; r < e.length; r++) {
var n = e[r];
n.enumerable = n.enumerable || false, n.configurable = true, "value" in n && (n.writable = true), Object.defineProperty(t, n.key, n)
}
}

return function (t, e, r) {
return e && n(t.prototype, e), r && n(t, r), t
}
}();
const Looper = function () {
function constructor() {
!function (t, e) {
if (!(t instanceof constructor)) throw new TypeError("Cannot call a class as a function")
}(this)
}

setClassFunc(constructor, null, [{
// just alias of a basic for loop with count
key: "loop", value: function (count, func) {
"v".repeat(count).split("").map(function (currVal, index) {
return func(index)
})
}
}]);
return constructor;
}();
exports.default = Looper;
},
/** Decryption class */
function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
const setClassFunc = function () {
function n(t, e) {
for (var r = 0; r < e.length; r++) {
var n = e[r];
n.enumerable = n.enumerable || false, n.configurable = true, "value" in n && (n.writable = true), Object.defineProperty(t, n.key, n)
}
}

return function (t, e, r) {
return e && n(t.prototype, e), r && n(t, r), t
}
}();
const Random = a(__webpack_require__(5));
const Looper = a(__webpack_require__(0));

function a(t) {
return t && t.__esModule ? t : {default: t}
}

function checkIsCallable(t, e) {
if (!(t instanceof e)) throw new TypeError("Cannot call a class as a function")
}

const Head = function () {
function constructor() {
checkIsCallable(this, constructor);
this._char = ".";
this._children = {};
}

setClassFunc(constructor, [
{
key: "getChar", value: function () {
return this._char;
}
},
{
key: "getChildren", value: function () {
return this._children;
}
},
{
key: "setChar", value: function (char) {
this._char = char;
}
},
{
key: "setChildren", value: function (key, value) {
this._children[key] = value;
}
}]);
return constructor;
}();
const cipherSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
const Decryption = function () {
function constructor(t) {
checkIsCallable(this, constructor);
this._random = new Random.default;
this._inter = {};
this._head = new Head;
}

setClassFunc(constructor, [
{
key: "init", value: function (seed) {
const self = this;
this._random.seed(seed);
Looper.default.loop(64, function (index) {
self._addSymbol(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[index],
[1, 2, 2, 2, 2, 2][parseInt((index + 1) / 11)])
});
this._inter["="] = "="
}
},
{
key: "_addSymbol", value: function (plainChar, count) {
const self = this;
let head = this._head;
let cipherStr = "";
Looper.default.loop(count, function () {
let char = cipherSet[self._random.generate(32)];
for (; char in head.getChildren() && "." !== head.getChildren()[char].getChar();) {
char = cipherSet[self._random.generate(32)];
}
cipherStr += char;
char in head.getChildren() || head.setChildren(char, new Head);
head = head.getChildren()[char]; // cautious: `head` changes the reference
});
head.setChar(plainChar);
this._inter[plainChar] = cipherStr;
}
},
{
key: "decode", value: function (text) {
let result = ""
for (let index = 4; index < text.length;) {
if (text[index] !== "=") {
let head = this._head;
while (text[index] in head.getChildren()) {
head = head.getChildren()[text[index]];
index++;
}
result += head.getChar();
} else {
result += "=";
index++;
}
}
return result;
}
}]);
return constructor;
}();
exports.default = Decryption;
},
/** Base64 library */
function (module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__, ya, za;
ya = "undefined" != typeof self ? self : "undefined" != typeof window ? window : "undefined" != typeof global ? global : this, za = function (global) {
"use strict";
global = global || {};
var _Base64 = global.Base64, version = "2.5.1", buffer;
if (void 0 !== module && module.exports) try {
buffer = eval("require('buffer').Buffer")
} catch (t) {
buffer = void 0
}
var b64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
b64tab = function (t) {
for (var e = {}, r = 0, n = t.length; r < n; r++) e[t.charAt(r)] = r;
return e
}(b64chars), fromCharCode = String.fromCharCode, cb_utob = function (t) {
if (t.length < 2) return (e = t.charCodeAt(0)) < 128 ? t : e < 2048 ? fromCharCode(192 | e >>> 6) + fromCharCode(128 | 63 & e) : fromCharCode(224 | e >>> 12 & 15) + fromCharCode(128 | e >>> 6 & 63) + fromCharCode(128 | 63 & e);
var e = 65536 + 1024 * (t.charCodeAt(0) - 55296) + (t.charCodeAt(1) - 56320);
return fromCharCode(240 | e >>> 18 & 7) + fromCharCode(128 | e >>> 12 & 63) + fromCharCode(128 | e >>> 6 & 63) + fromCharCode(128 | 63 & e)
}, re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g, utob = function (t) {
return t.replace(re_utob, cb_utob)
}, cb_encode = function (t) {
var e = [0, 2, 1][t.length % 3],
r = t.charCodeAt(0) << 16 | (1 < t.length ? t.charCodeAt(1) : 0) << 8 | (2 < t.length ? t.charCodeAt(2) : 0);
return [b64chars.charAt(r >>> 18), b64chars.charAt(r >>> 12 & 63), 2 <= e ? "=" : b64chars.charAt(r >>> 6 & 63), 1 <= e ? "=" : b64chars.charAt(63 & r)].join("")
}, btoa = global.btoa ? function (t) {
return global.btoa(t)
} : function (t) {
return t.replace(/[\s\S]{1,3}/g, cb_encode)
}, _encode = buffer ? buffer.from && Uint8Array && buffer.from !== Uint8Array.from ? function (t) {
return (t.constructor === buffer.constructor ? t : buffer.from(t)).toString("base64")
} : function (t) {
return (t.constructor === buffer.constructor ? t : new buffer(t)).toString("base64")
} : function (t) {
return btoa(utob(t))
}, encode = function (t, e) {
return e ? _encode(String(t)).replace(/[+\/]/g, function (t) {
return "+" == t ? "-" : "_"
}).replace(/=/g, "") : _encode(String(t))
}, encodeURI = function (t) {
return encode(t, true)
}, re_btou = new RegExp(["[À-ß][€-¿]", "[à-ï][€-¿]{2}", "[ð-÷][€-¿]{3}"].join("|"), "g"),
cb_btou = function (t) {
switch (t.length) {
case 4:
var e = ((7 & t.charCodeAt(0)) << 18 | (63 & t.charCodeAt(1)) << 12 | (63 & t.charCodeAt(2)) << 6 | 63 & t.charCodeAt(3)) - 65536;
return fromCharCode(55296 + (e >>> 10)) + fromCharCode(56320 + (1023 & e));
case 3:
return fromCharCode((15 & t.charCodeAt(0)) << 12 | (63 & t.charCodeAt(1)) << 6 | 63 & t.charCodeAt(2));
default:
return fromCharCode((31 & t.charCodeAt(0)) << 6 | 63 & t.charCodeAt(1))
}
}, btou = function (t) {
return t.replace(re_btou, cb_btou)
}, cb_decode = function (t) {
var e = t.length, r = e % 4,
n = (0 < e ? b64tab[t.charAt(0)] << 18 : 0) | (1 < e ? b64tab[t.charAt(1)] << 12 : 0) | (2 < e ? b64tab[t.charAt(2)] << 6 : 0) | (3 < e ? b64tab[t.charAt(3)] : 0),
o = [fromCharCode(n >>> 16), fromCharCode(n >>> 8 & 255), fromCharCode(255 & n)];
return o.length -= [0, 0, 2, 1][r], o.join("")
}, _atob = global.atob ? function (t) {
return global.atob(t)
} : function (t) {
return t.replace(/\S{1,4}/g, cb_decode)
}, atob = function (t) {
return _atob(String(t).replace(/[^A-Za-z0-9\+\/]/g, ""))
}, _decode = buffer ? buffer.from && Uint8Array && buffer.from !== Uint8Array.from ? function (t) {
return (t.constructor === buffer.constructor ? t : buffer.from(t, "base64")).toString()
} : function (t) {
return (t.constructor === buffer.constructor ? t : new buffer(t, "base64")).toString()
} : function (t) {
return btou(_atob(t))
}, decode = function (t) {
return _decode(String(t).replace(/[-_]/g, function (t) {
return "-" == t ? "+" : "/"
}).replace(/[^A-Za-z0-9\+\/]/g, ""))
}, noConflict = function () {
var t = global.Base64;
return global.Base64 = _Base64, t
};
if (global.Base64 = {
VERSION: version,
atob: atob,
btoa: btoa,
fromBase64: decode,
toBase64: encode,
utob: utob,
encode: encode,
encodeURI: encodeURI,
btou: btou,
decode: decode,
noConflict: noConflict,
__buffer__: buffer
}, "function" == typeof Object.defineProperty) {
var noEnum = function (t) {
return {value: t, enumerable: false, writable: true, configurable: true}
};
global.Base64.extendString = function () {
Object.defineProperty(String.prototype, "fromBase64", noEnum(function () {
return decode(this)
})), Object.defineProperty(String.prototype, "toBase64", noEnum(function (t) {
return encode(this, t)
})), Object.defineProperty(String.prototype, "toBase64URI", noEnum(function () {
return encode(this, true)
}))
}
}
return global.Meteor && (Base64 = global.Base64), void 0 !== module && module.exports ? module.exports.Base64 = global.Base64 : (__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return global.Base64
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), void 0 === __WEBPACK_AMD_DEFINE_RESULT__ || (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)), {Base64: global.Base64}
}, module.exports = za(ya)
},
/** Decryption helper class */
function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
const setClassFunc = function () {
function n(t, e) {
for (var r = 0; r < e.length; r++) {
var n = e[r];
n.enumerable = n.enumerable || false, n.configurable = true, "value" in n && (n.writable = true), Object.defineProperty(t, n.key, n)
}
}

return function (t, e, r) {
return e && n(t.prototype, e), r && n(t, r), t
}
}();
const Base64 = __webpack_require__(2);
let Decryption = __webpack_require__(1);
Decryption = Decryption.__esModule ? Decryption : {default: Decryption};
const charToMagicInt = function (text) {
var first_char_code = text.charCodeAt();
return first_char_code >= 65 ? first_char_code - 65 : first_char_code - 65 + 41
};
const DecryptionHelper = function () {
function constructor() {
!function (t, e) {
if (!(t instanceof constructor)) throw new TypeError("Cannot call a class as a function")
}(this)
}

setClassFunc(constructor, null, [
{
key: "_checkVersion", value: function (t) {
return ((32 * charToMagicInt(t[0]) + charToMagicInt(t[1])) * charToMagicInt(t[2]) + charToMagicInt(t[3])) % 32 <= 1
}
},
{
key: "d", value: function (encrypted_text) {
if (!this._checkVersion(encrypted_text)) return "";
var decryptor = new Decryption.default;
decryptor.init(encrypted_text.substr(0, 4));
var base64_text = decryptor.decode(encrypted_text);
return Base64.Base64.decode(base64_text)
}
}]);
return constructor;
}();
exports.default = DecryptionHelper;
module.exports = DecryptionHelper;
},
/** Bitwise operation class */
function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
const setClassFunc = function () {
function n(t, e) {
for (var r = 0; r < e.length; r++) {
var n = e[r];
n.enumerable = n.enumerable || false, n.configurable = true, "value" in n && (n.writable = true), Object.defineProperty(t, n.key, n)
}
}

return function (t, e, r) {
return e && n(t.prototype, e), r && n(t, r), t
}
}();
const BitOp = function () {
function constructor() {
!function (t, e) {
if (!(t instanceof constructor)) throw new TypeError("Cannot call a class as a function")
}(this)
}

setClassFunc(constructor, null, [
{
key: "get", value: function (t) {
return t >>> 0
}
},
{
key: "xor", value: function (t, e) {
return this.get(this.get(t) ^ this.get(e))
}
},
{
key: "and", value: function (t, e) {
return this.get(this.get(t) & this.get(e))
}
},
{
key: "mul", value: function (t, e) {
var r = ((4294901760 & t) >>> 0) * e, n = (65535 & t) * e;
return this.get((r >>> 0) + (n >>> 0))
}
},
{
key: "or", value: function (t, e) {
return this.get(this.get(t) | this.get(e))
}
},
{
key: "not", value: function (t) {
return this.get(~this.get(t))
}
},
{
key: "shiftLeft", value: function (t, e) {
return this.get(this.get(t) << e)
}
},
{
key: "shiftRight", value: function (t, e) {
return this.get(t) >>> e
}
},
{
key: "mod", value: function (t, e) {
return this.get(this.get(t) % e)
}
}]);
return constructor;
}();
exports.default = BitOp;
},
/** Random generator class */
function (module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {value: true});
const setClassFunc = function () {
function n(t, e) {
for (var r = 0; r < e.length; r++) {
var n = e[r];
n.enumerable = n.enumerable || false, n.configurable = true, "value" in n && (n.writable = true), Object.defineProperty(t, n.key, n)
}
}

return function (t, e, r) {
return e && n(t.prototype, e), r && n(t, r), t
}
}();
const Looper = a(__webpack_require__(0));
const BitOp = a(__webpack_require__(4));

function a(t) {
return t && t.__esModule ? t : {default: t}
}

var Random = function () {
function constructor() {
!function (t, e) {
if (!(t instanceof constructor)) throw new TypeError("Cannot call a class as a function")
}(this);
this._status = [];
this._mat1 = 0;
this._mat2 = 0;
this._tmat = 0;
}

setClassFunc(constructor, [
{
key: "seed", value: function (seed) {
const self = this;
Looper.default.loop(4, function (index) {
seed.length > index ?
self._status[index] = BitOp.default.get(seed.charAt(index).charCodeAt()) :
self._status[index] = BitOp.default.get(110);
});
this._mat1 = this._status[1];
this._mat2 = this._status[2];
this._tmat = this._status[3];
this._init();
}
},
{
key: "_init", value: function () {
const self = this;
Looper.default.loop(7, function (index) {
self._status[index + 1 & 3] = BitOp.default.xor(self._status[index + 1 & 3],
index + 1 + BitOp.default.mul(1812433253,
BitOp.default.xor(self._status[3 & index],
BitOp.default.shiftRight(self._status[3 & index], 30))))
});
if (0 == (2147483647 & this._status[0]) &&
0 === this._status[1] &&
0 === this._status[2] &&
0 === this._status[3]) {
this._status[0] = 66;
this._status[1] = 65;
this._status[2] = 89;
this._status[3] = 83;
}
Looper.default.loop(8, function () {
return self._next_state();
});
}
},
{
key: "_next_state", value: function () {
let n1, n2;
n1 = BitOp.default.xor(BitOp.default.and(this._status[0], 2147483647),
BitOp.default.xor(this._status[1], this._status[2]));
n2 = this._status[3];
n1 = BitOp.default.xor(n1, BitOp.default.shiftLeft(n1, 1));
n2 = BitOp.default.xor(n2, BitOp.default.xor(BitOp.default.shiftRight(n2, 1), n1));
this._status[0] = this._status[1];
this._status[1] = this._status[2];
this._status[2] = BitOp.default.xor(n1, BitOp.default.shiftLeft(n2, 10));
this._status[3] = n2;
this._status[1] = BitOp.default.xor(this._status[1],
BitOp.default.and(-BitOp.default.and(n2, 1), this._mat1));
this._status[2] = BitOp.default.xor(this._status[2],
BitOp.default.and(-BitOp.default.and(n2, 1), this._mat2))
}
},
{
key: "generate", value: function (range) {
this._next_state();
let n1, n2;
n1 = BitOp.default.xor(this._status[0],
BitOp.default.shiftRight(this._status[2], 8));
n2 = this._status[3];
n2 = BitOp.default.xor(n2, n1);
return (BitOp.default.xor(BitOp.default.and(-BitOp.default.and(n1, 1), this._tmat), n2)) % range;
}
}]);
return constructor
}();
exports.default = Random
}
])
})

Python script for decryption

Caution:

  • Javascript bitwise operation uses int32, where in Python, there is no such bit limit, so it is better to wrap bitwise operation(especially shiftting) in the mask function.
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import base64
import json


def int32(num: int):
return int(0xFFFFFFFF & num)


class CustomMersenneTwister:
_status: list
_mat1: int
_mat2: int
_tmat: int

def __init__(self, seed: str):
self._status = list()
self._mat1 = 0
self._mat2 = 0
self._tmat = 0
for index in range(4):
self._status.append(ord(seed[index]) if len(seed) > index else 110)
self._mat1 = self._status[1]
self._mat2 = self._status[2]
self._tmat = self._status[3]

for index in range(7):
self._status[index + 1 & 3] ^= int32(index + 1 + int32(1812433253 * (
self._status[3 & index] ^ int32(self._status[3 & index] >> 30))))
if 0 == (2147483647 & self._status[0]) and \
0 == self._status[1] and \
0 == self._status[2] and \
0 == self._status[3]:
self._status = [66, 65, 89, 83]
for _ in range(8):
self._twist()

def _twist(self):
n1 = (self._status[0] & 2147483647) ^ (self._status[1] ^ self._status[2])
n2 = self._status[3]
n1 ^= int32(n1 << 1)
n2 ^= int32(n2 >> 1) ^ n1
self._status[0] = self._status[1]
self._status[1] = self._status[2]
self._status[2] = n1 ^ int32(n2 << 10)
self._status[3] = n2
self._status[1] ^= -(n2 & 1) & self._mat1
self._status[2] ^= -(n2 & 1) & self._mat2

def generate(self, range: int):
self._twist()
n1 = self._status[0] ^ int32(self._status[2] >> 8)
n2 = self._status[3]
n2 ^= n1
return ((-(n1 & 1) & self._tmat) ^ n2) % range


class Decryption:
_head: dict
_rng: CustomMersenneTwister
_mapping: dict

def __init__(self, seed: str):
self._head = {
"char": ".",
"children": dict()
}
self._rng = CustomMersenneTwister(seed)
self._init_mapping_dict()

def _init_mapping_dict(self):
self._mapping = dict()
base64_charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
cipher_charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
for i in range(64):
plain_char = base64_charset[i]
cipher_str = ""
head = self._head
for _ in range([1, 2, 2, 2, 2, 2][int((i + 1) / 11)]):
char = cipher_charset[self._rng.generate(32)]
while char in head["children"].keys() and head["children"][char]["char"] != ".":
char = cipher_charset[self._rng.generate(32)]
cipher_str += char
if not char in head["children"].keys():
head["children"][char] = {
"char": ".",
"children": dict()
}
head = head["children"][char]
head["char"] = plain_char
self._mapping[plain_char] = cipher_str
self._mapping["="] = "="

def decode_to_base64(self, encrypted_text: str):
result = list()
i = 4
while i < len(encrypted_text):
if encrypted_text[i] != "=":
head = self._head
while i < len(encrypted_text) and encrypted_text[i] in head["children"].keys():
head = head["children"][encrypted_text[i]]
i += 1
result.append(head["char"])
else:
result.append("=")
i += 1
return ''.join(result)

def decode_to_json(self, encrypt_text: str):
return base64.b64decode(self.decode_to_base64(encrypt_text))


if __name__ == "__main__":
# test
rng = CustomMersenneTwister("3GL7")
ans = [12, 18, 13, 10, 10, 11, 19, 21, 13, 31, 23]
for i in range(11):
assert rng.generate(32) == ans[i]
decryption = Decryption("3GL7")

ans = {
"0": "ED",
"1": "5D",
"2": "P2",
"3": "4S",
"4": "ZL",
"5": "Q5",
"6": "GT",
"7": "PJ",
"8": "C2",
"9": "W5",
"A": "M",
"B": "S",
"C": "N",
"D": "K",
"E": "L",
"F": "T",
"G": "V",
"H": "7",
"I": "X",
"J": "H",
"K": "I3",
"L": "WP",
"M": "4G",
"N": "BA",
"O": "ZX",
"P": "JA",
"Q": "U2",
"R": "FI",
"S": "J7",
"T": "J3",
"U": "3B",
"V": "PB",
"W": "UK",
"X": "UG",
"Y": "CX",
"Z": "QQ",
"a": "ZA",
"b": "DG",
"c": "E3",
"d": "4Q",
"e": "DI",
"f": "RC",
"g": "P5",
"h": "EC",
"i": "JQ",
"j": "WR",
"k": "3J",
"l": "26",
"m": "3R",
"n": "2Q",
"o": "JX",
"p": "D4",
"q": "UV",
"r": "UW",
"s": "4P",
"t": "UE",
"u": "A4",
"v": "U7",
"w": "IX",
"x": "4V",
"y": "5M",
"z": "WY",
"+": "EX",
"/": "A2",
"=": "="
}
for k, v in ans.items():
assert decryption._mapping[k] == v