-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtools.js
95 lines (83 loc) · 2.2 KB
/
tools.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
'use strict'
var crypto = require('crypto');
var bcrypt;
try {
bcrypt = require('bcrypt');
if (bcrypt && typeof bcrypt.compare !== 'function') {
bcrypt = require('bcryptjs');
}
} catch (err) {
bcrypt = require('bcryptjs');
}
var SALT_WORK_FACTOR = 10;
exports.hashPwd = function (plain) {
var salt = bcrypt.genSaltSync(SALT_WORK_FACTOR);
return bcrypt.hashSync(plain, salt);
};
exports.checkPwd = function (plain, password, next) {
bcrypt.compare(plain, password, function (err, isMatch) {
if (err) return next(err);
next(null, isMatch);
});
}
let resWarp = function (err, data, msg) {
return {
error: !!err,
data: data,
message: msg || (err ? err.message : '')
}
}
exports.resWarp = resWarp;
exports.resSuccess = function (data, msg) {
return exports.resWarp(null, data, msg)
}
exports.resData = function (data) {
return resWarp(null, data, null)
}
exports.resMsg = function (msg) {
return resWarp(null, null, msg)
};
exports.resErrMsg = function (msg) {
return resWarp(msg, null, msg)
};
/**
* aes加密
* @param data 待加密内容
* @param key 必须为32位私钥
* @returns {string}
*/
exports.encryption = function (data, key, iv) {
iv = iv || "";
var clearEncoding = 'utf8';
var cipherEncoding = 'base64';
var cipherChunks = [];
var cipher = crypto.createCipheriv('aes-256-ecb', key, iv);
cipher.setAutoPadding(true);
cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
cipherChunks.push(cipher.final(cipherEncoding));
return cipherChunks.join('');
}
/**
* aes解密
* @param data 待解密内容
* @param key 必须为32位私钥
* @returns {string}
*/
exports.decryption = function (data, key, iv) {
if (!data) {
return "";
}
iv = iv || "";
var clearEncoding = 'utf8';
var cipherEncoding = 'base64';
var cipherChunks = [];
var decipher = crypto.createDecipheriv('aes-256-ecb', key, iv);
decipher.setAutoPadding(true);
cipherChunks.push(decipher.update(data, cipherEncoding, clearEncoding));
cipherChunks.push(decipher.final(clearEncoding));
return cipherChunks.join('');
}
exports.keyFmt = function (key) {
key = Array.from({length: 32}).map(()=>0).join('') + key;
return key.substr(key.length - 32);
}