sicksync
Version:
Don’t accept the available as the preferable. Go extra mile with extra speed.
60 lines (45 loc) • 1.42 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CryptHelper = undefined;
var _crypto = require('crypto');
var _crypto2 = _interopRequireDefault(_crypto);
var _constants = require('../conf/constants');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class CryptHelper {
constructor(secret) {
this.secret = secret;
}
_cryptHelper(text, isEncrypt) {
const cryptMethod = isEncrypt ? 'createCipher' : 'createDecipher';
const finalParam = isEncrypt ? 'hex' : 'utf8';
const cipherArgs = isEncrypt ? [text, 'utf8', 'hex'] : [text, 'hex', 'utf8'];
const cipher = _crypto2.default[cryptMethod](_constants.CRYPT_ALGO, this.secret);
let result = cipher.update.apply(cipher, cipherArgs);
result += cipher.final(finalParam);
return result;
}
encrypt(text) {
return this._cryptHelper(text, true);
}
decrypt(text) {
return this._cryptHelper(text, false);
}
stringifyAndEncrypt(data, withEncryption) {
const stringifiedData = JSON.stringify(data);
if (withEncryption) {
return this.encrypt(stringifiedData);
} else {
return stringifiedData;
}
}
decryptAndParse(msg, withEncryption) {
if (withEncryption) {
msg = this.decrypt(msg);
}
return JSON.parse(msg);
}
}
exports.CryptHelper = CryptHelper;
exports.default = CryptHelper;
;