forked from NetEase/lordofpomelo
/
token.js
42 lines (40 loc) · 1.14 KB
/
token.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
var crypto = require('crypto');
/**
* Create token by uid. Encrypt uid and timestamp to get a token.
*
* @param {String} uid user id
* @param {String|Number} timestamp
* @param {String} pwd encrypt password
* @return {String} token string
*/
module.exports.create = function(uid, timestamp, pwd) {
var msg = uid + '|' + timestamp;
var cipher = crypto.createCipher('aes256', pwd);
var enc = cipher.update(msg, 'utf8', 'hex');
enc += cipher.final('hex');
return enc;
};
/**
* Parse token to validate it and get the uid and timestamp.
*
* @param {String} token token string
* @param {String} pwd decrypt password
* @return {Object} uid and timestamp that exported from token. null for illegal token.
*/
module.exports.parse = function(token, pwd) {
var decipher = crypto.createDecipher('aes256', pwd);
var dec;
try {
dec = decipher.update(token, 'hex', 'utf8');
dec += decipher.final('utf8');
} catch(err) {
console.error('[token] fail to decrypt token. %j', token);
return null;
}
var ts = dec.split('|');
if(ts.length !== 2) {
// illegal token
return null;
}
return {uid: ts[0], timestamp: Number(ts[1])};
};