-
Notifications
You must be signed in to change notification settings - Fork 0
/
mycrypt.js
138 lines (129 loc) · 3.34 KB
/
mycrypt.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
function xorEncrypt(text, key) {
var key_len = key.length;
var result = "";
for(var i = 0; i < text.length; i++) {
key_pos = i % key_len;
result += String.fromCharCode(text.charCodeAt(i) ^ key.charCodeAt(key_pos));
}
return result;
}
function hammingWeight(i) {
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return ((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
function hammingDistNorm(s1, s2) {
if(s1.length != s2.length) {
throw new Error('Cannot do this when they are differing lengths.');
}
var len = s1.length;
var xorResult = xorEncrypt(s1, s2);
var totalWeight = 0;
for(var i = 0; i < len; i++) {
totalWeight += hammingWeight(xorResult.charCodeAt(i));
}
var normWeight = totalWeight / len;
return normWeight;
}
function printable(s) {
return /^[\x20-\x7E\x09]+$/m.test(s);
}
function printable_char(c) {
var ord = c.charCodeAt(0);
return ord >= 32 && ord <= 126
|| ord == 9;
}
function freq_score(s) {
var inner = function(s, score) {
if(s == "") return score;
switch(s[0].toLowerCase()) {
case 'e':
score += 21.9;
break;
case 't':
score += 16.6;
break;
case 'a':
score += 14.8;
break;
case 'o':
score += 14.0;
break;
case 'i':
score += 13.3;
break;
case 'n':
score += 12.6;
break;
case 's':
score += 11.4;
break;
case 'r':
score += 10.9;
break;
case 'h':
score += 10.7;
break;
case 'd':
score += 7.8;
break;
case 'l':
score += 7.2;
break;
case 'u':
score += 5.3;
break;
case 'c':
score += 5.0;
break;
case 'm':
score += 4.7;
break;
case 'f':
score += 4.2;
break;
case 'y':
case 'w':
score += 3.8;
break;
case 'g':
score += 3.7;
break;
case 'p':
score += 3.3;
break;
case 'b':
score += 2.7;
break;
case 'v':
score += 2.0;
break;
case '.':
score += 1.9;
break;
case '\n':
score += 1.7;
break;
case 'k':
score += 1.2;
break;
case 'x':
score += 0.3;
break;
case 'q':
case 'j':
case 'z':
score += 0.1;
break;
default:
if(printable_char(s[0])) {
score += 0.1;
} else {
score += -11;
}
break;
}
return inner(s.substring(1), score);
};
return inner(s, 0);
}