-
Notifications
You must be signed in to change notification settings - Fork 831
/
crypto.js
308 lines (257 loc) 路 10.5 KB
/
crypto.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
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
/*jshint strict: false */
/*global Buffer */
////////////////////////////////////////////////////////////////////////////////
/// @brief Some crypto functions
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
var internal = require("internal");
// -----------------------------------------------------------------------------
// --SECTION-- RANDOM
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief generate a random number
///
/// the value returned might be positive or negative or even 0.
/// if random number generation fails, then undefined is returned
////////////////////////////////////////////////////////////////////////////////
exports.rand = function () {
return internal.rand();
};
// -----------------------------------------------------------------------------
// --SECTION-- HASHES
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief apply an HMAC
////////////////////////////////////////////////////////////////////////////////
exports.hmac = function (key, message, algorithm) {
return internal.hmac(key, message, algorithm);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief apply a PBKDF2
////////////////////////////////////////////////////////////////////////////////
exports.pbkdf2 = function (salt, password, iterations, keyLength) {
return internal.pbkdf2(salt, password, iterations, keyLength);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief apply an MD5 hash
////////////////////////////////////////////////////////////////////////////////
exports.md5 = function (value) {
return internal.md5(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief apply an SHA 512 hash
////////////////////////////////////////////////////////////////////////////////
exports.sha512 = function (value) {
return internal.sha512(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief apply an SHA 384 hash
////////////////////////////////////////////////////////////////////////////////
exports.sha384 = function (value) {
return internal.sha384(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief apply an SHA 256 hash
////////////////////////////////////////////////////////////////////////////////
exports.sha256 = function (value) {
return internal.sha256(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief apply an SHA 224 hash
////////////////////////////////////////////////////////////////////////////////
exports.sha224 = function (value) {
return internal.sha224(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief apply an SHA 1 hash
////////////////////////////////////////////////////////////////////////////////
exports.sha1 = function (value) {
return internal.sha1(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief Generates a string of a given length containing numbers.
////////////////////////////////////////////////////////////////////////////////
exports.genRandomNumbers = function (value) {
return internal.genRandomNumbers(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief Generates a string of a given length containing numbers and characters.
////////////////////////////////////////////////////////////////////////////////
exports.genRandomAlphaNumbers = function (value) {
return internal.genRandomAlphaNumbers(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief Generates a string of a given length containing ASCII characters.
////////////////////////////////////////////////////////////////////////////////
exports.genRandomSalt = function (value) {
return internal.genRandomSalt(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief Generates a base64 encoded nonce string.
////////////////////////////////////////////////////////////////////////////////
exports.createNonce = function () {
return internal.createNonce();
};
////////////////////////////////////////////////////////////////////////////////
/// @brief Checks and marks a nonce
////////////////////////////////////////////////////////////////////////////////
exports.checkAndMarkNonce = function (value) {
return internal.checkAndMarkNonce(value);
};
////////////////////////////////////////////////////////////////////////////////
/// @brief Compares two strings in constant time
////////////////////////////////////////////////////////////////////////////////
exports.constantEquals = function (a, b) {
'use strict';
var length, result, i;
length = a.length > b.length ? a.length : b.length;
result = true;
for (i = 0; i < length; i++) {
if (a.charCodeAt(i) !== b.charCodeAt(i)) {
result = false;
}
}
return result;
};
////////////////////////////////////////////////////////////////////////////////
/// @brief Encodes JSON Web Token
////////////////////////////////////////////////////////////////////////////////
function jwtUrlEncode(str) {
'use strict';
return str.replace(/[+]/g, '-').replace(/[\/]/g, '_').replace(/[=]/g, '');
}
function jwtHmacSigner(algorithm) {
'use strict';
return function (key, segments) {
return new Buffer(exports.hmac(key, segments.join('.'), algorithm), 'hex').toString('base64');
};
}
function jwtHmacVerifier(algorithm) {
'use strict';
return function (key, segments) {
return exports.constantEquals(
exports.hmac(key, segments.slice(0, 2).join('.'), algorithm),
segments[2]
);
};
}
exports.jwtAlgorithms = {
HS256: {
sign: jwtHmacSigner('sha256'),
verify: jwtHmacVerifier('sha256')
},
HS384: {
sign: jwtHmacSigner('sha384'),
verify: jwtHmacVerifier('sha384')
},
HS512: {
sign: jwtHmacSigner('sha512'),
verify: jwtHmacVerifier('sha512')
},
none: {
sign: function (key) {
'use strict';
if (key) {
throw new Error('Can not sign message with key using algorithm "none"!');
}
return '';
},
verify: function (key) {
'use strict';
// see https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
return !key;
}
}
};
exports.jwtCanonicalAlgorithmName = function (algorithm) {
'use strict';
if (algorithm && typeof algorithm === 'string') {
if (exports.jwtAlgorithms.hasOwnProperty(algorithm.toLowerCase())) {
return algorithm.toLowerCase();
}
if (exports.jwtAlgorithms.hasOwnProperty(algorithm.toUpperCase())) {
return algorithm.toUpperCase();
}
}
throw new Error(
'Unknown algorithm "'
+ algorithm
+ '". Only the following algorithms are supported at this time: '
+ Object.keys(exports.jwtAlgorithms).join(', ')
);
};
exports.jwtEncode = function (key, message, algorithm) {
'use strict';
algorithm = algorithm ? exports.jwtCanonicalAlgorithmName(algorithm) : 'HS256';
var header = {typ: 'JWT', alg: algorithm}, segments = [];
segments.push(jwtUrlEncode(new Buffer(JSON.stringify(header)).toString('base64')));
segments.push(jwtUrlEncode(new Buffer(JSON.stringify(message)).toString('base64')));
segments.push(jwtUrlEncode(exports.jwtAlgorithms[algorithm].sign(key, segments)));
return segments.join('.');
};
////////////////////////////////////////////////////////////////////////////////
/// @brief Decodes JSON Web Token
////////////////////////////////////////////////////////////////////////////////
function jwtUrlDecode(str) {
'use strict';
while ((str.length % 4) !== 0) {
str += '=';
}
return str.replace(/\-/g, '+').replace(/_/g, '/');
}
exports.jwtDecode = function (key, token, noVerify) {
'use strict';
if (!token) {
return null;
}
var segments = token.split('.');
if (segments.length !== 3) {
throw new Error('Wrong number of JWT segments!');
}
var headerSeg = new Buffer(jwtUrlDecode(segments[0]), 'base64').toString();
var messageSeg = new Buffer(jwtUrlDecode(segments[1]), 'base64').toString();
segments[2] = new Buffer(jwtUrlDecode(segments[2]), 'base64').toString('hex');
if (!noVerify) {
var header = JSON.parse(headerSeg);
header.alg = exports.jwtCanonicalAlgorithmName(header.alg);
if (!exports.jwtAlgorithms[header.alg].verify(key, segments)) {
throw new Error('Signature verification failed!');
}
}
return JSON.parse(messageSeg);
};
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @}\\|/\\*jslint"
// End: