forked from befinal/node-tenpay
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.js
50 lines (42 loc) · 1.84 KB
/
util.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
const crypto = require('crypto');
const xml2js = require('xml2js');
exports.decrypt = (encryptedData, key, iv = '') => {
let decipher = crypto.createDecipheriv('aes-256-ecb', key, iv);
decipher.setAutoPadding(true);
let decoded = decipher.update(encryptedData, 'base64', 'utf8');
decoded += decipher.final('utf8');
return decoded;
}
exports.md5 = (str, encoding = 'utf8') => crypto.createHash('md5').update(str, encoding).digest('hex');
exports.sha256 = (str, key, encoding = 'utf8') => crypto.createHmac('sha256', key).update(str, encoding).digest('hex');
exports.encryptRSA = (key, hash) => crypto.publicEncrypt(key, new Buffer(hash)).toString('base64');
exports.checkXML = str => {
let reg = /^(<\?xml.*\?>)?(\r?\n)*<xml>(.|\r?\n)*<\/xml>$/i;
return reg.test(str.trim());
}
exports.getFullDate = () => {
const str = new Date();
let YYYY = str.getFullYear();
let MM = ('00' + (str.getMonth() + 1)).substr(-2);
let DD = ('00' + str.getDate()).substr(-2);
return YYYY + MM + DD;
}
exports.toQueryString = (obj) => Object.keys(obj)
.filter(key => key !== 'sign' && obj[key] !== undefined && obj[key] !== '')
.sort()
.map(key => key + '=' + obj[key])
.join('&');
exports.generate = (length = 16) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let noceStr = '', maxPos = chars.length;
while (length--) noceStr += chars[Math.random() * maxPos |0];
return noceStr;
}
exports.buildXML = (obj, rootName = 'xml') => {
const opt = {xmldec: null, rootName, allowSurrogateChars: true, cdata: true};
return new xml2js.Builder(opt).buildObject(obj);
}
exports.parseXML = (xml) => new Promise((resolve, reject) => {
const opt = {trim: true, explicitArray: false, explicitRoot: false};
xml2js.parseString(xml, opt, (err, res) => err ? reject(new Error('XMLDataError')) : resolve(res || {}));
})