forked from rickyes/jasypt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jasypt.js
95 lines (81 loc) · 2.33 KB
/
jasypt.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';
const crypto = require('crypto');
const assert = require('assert');
const Encryptor = require('./encryptor');
const util = require('./util');
const cacher = require('./cache');
class Jasypt {
constructor(opts = {}) {
this._encryptor = new Encryptor();
this._encryptor.setAlgorithm('PBEWithMD5AndDES');
this.salt = opts.salt || crypto.randomBytes(8);
this.iterations = opts.iterations || 1000;
this.password = '';
}
getCacheKey(key) {
return `${this.salt}_${this.iterations}_${this.password}_${key}`;
}
/**
* 设置秘钥
* @param {String} password 秘钥
*/
setPassword(password) {
assert(!util.isEmpty(util), 'Password cannot be set empty');
this.password = password;
}
/**
* 加密
* @param {String} message 需要加密的文本
*/
encrypt(message) {
if (util.isEmpty(message)) {
return null;
}
return this._encryptor.encrypt(message, this.password, this.salt, this.iterations);
}
/**
* 解密
* @param {String} encryptedMessage 需要解密的文本
*/
decrypt(encryptedMessage) {
if (util.isEmpty(encryptedMessage)) {
return null;
}
const cacheKey = this.getCacheKey(encryptedMessage);
if (cacher.has(cacheKey)) return cacher.get(cacheKey);
const value = this._encryptor.decrypt(encryptedMessage, this.password, this.iterations);
cacher.set(cacheKey, value);
return value;
}
/**
* 解密对象里含有ENC(xxxx)格式的value
* @param {Object} obj 入参配置对象
*/
decryptConfig (obj) {
if (!util.isType('Object', obj)) {
return;
}
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
const value = obj[key];
if (util.isType('Object', value)) {
this.decryptConfig(value);
} else if (util.isType('String', value)) {
if (value.indexOf('ENC(') === 0 && value.lastIndexOf(')') === value.length - 1) {
const encryptMsg = value.substring(4, value.length - 1);
obj[key] = this.decrypt(encryptMsg);
}
} else if (util.isType('Array', value)) {
for (const item of value) {
if (util.isType('Object', item)) {
this.decryptConfig(item);
}
}
} else {
continue;
}
}
}
}
}
module.exports = Jasypt;