2015-08-16 01:37:27 +02:00
|
|
|
//crypt.js
|
2015-08-16 13:42:14 +02:00
|
|
|
/**
|
|
|
|
* Module for encrypting and decrypting strings.
|
|
|
|
* @module crypt
|
2015-08-16 13:48:08 +02:00
|
|
|
* @author Bram van der Veen <96aa48@gmail.com>
|
2015-08-16 13:42:14 +02:00
|
|
|
*/
|
2015-08-16 01:37:27 +02:00
|
|
|
|
|
|
|
//Import first-party modules.
|
2016-06-18 15:06:51 +02:00
|
|
|
const crypto = require('crypto');
|
2015-07-21 15:01:11 +02:00
|
|
|
|
2015-08-31 08:32:21 +02:00
|
|
|
//Import self-written modules.
|
2016-06-18 15:06:51 +02:00
|
|
|
const config = require('./configuration');
|
2015-08-31 08:32:21 +02:00
|
|
|
|
2016-06-18 15:06:51 +02:00
|
|
|
//Set local constants.
|
|
|
|
const encoding = 'utf8';
|
|
|
|
const cryptEncoding = 'hex';
|
|
|
|
const algo = 'aes192';
|
|
|
|
const passwd = config().encryptionKey;
|
2015-07-21 15:01:11 +02:00
|
|
|
|
2015-08-16 01:37:27 +02:00
|
|
|
/**
|
|
|
|
* Function for encrypting a string.
|
|
|
|
* @param {String} str - String that you want to encrypt.
|
|
|
|
* @return {String} encryptArray - Encrypted string.
|
|
|
|
*/
|
|
|
|
function encrypt(str) {
|
2016-06-18 15:06:51 +02:00
|
|
|
let cipher = crypto.createCipher(algo, passwd);
|
|
|
|
let encryptArray = [];
|
2015-08-16 01:37:27 +02:00
|
|
|
|
|
|
|
encryptArray.push(cipher.update(str, encoding, cryptEncoding));
|
|
|
|
encryptArray.push(cipher.final(cryptEncoding));
|
|
|
|
|
|
|
|
return encryptArray.join('');
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Function to decrypt a string.
|
|
|
|
* @param {String} str - String you want to decrypt
|
2015-08-16 13:48:08 +02:00
|
|
|
* @return {String} The decrypted string.
|
2015-08-16 01:37:27 +02:00
|
|
|
*/
|
|
|
|
function decrypt(str) {
|
2016-06-18 15:06:51 +02:00
|
|
|
let decipher = crypto.createDecipher(algo, passwd);
|
|
|
|
let decryptArray = [];
|
2015-08-16 01:37:27 +02:00
|
|
|
|
|
|
|
try {
|
|
|
|
decryptArray.push(decipher.update(str, cryptEncoding, encoding));
|
|
|
|
decryptArray.push(decipher.final(encoding));
|
|
|
|
|
|
|
|
return decryptArray.join('');
|
|
|
|
}
|
|
|
|
catch (err) {
|
|
|
|
return str.join('');
|
2015-07-21 15:01:11 +02:00
|
|
|
}
|
|
|
|
}
|
2015-08-16 01:37:27 +02:00
|
|
|
|
|
|
|
//Export the functions as a module.
|
|
|
|
module.exports = {
|
|
|
|
'encrypt': encrypt,
|
|
|
|
'decrypt': decrypt
|
|
|
|
}
|