BlueWallet/blue_modules/encryption.js

23 lines
859 B
JavaScript
Raw Normal View History

const CryptoJS = require('crypto-js');
2018-03-30 20:31:10 +02:00
module.exports.encrypt = function (data, password) {
2019-11-29 00:59:06 +01:00
if (data.length < 10) throw new Error('data length cant be < 10');
const ciphertext = CryptoJS.AES.encrypt(data, password);
2018-03-30 20:31:10 +02:00
return ciphertext.toString();
};
module.exports.decrypt = function (data, password) {
const bytes = CryptoJS.AES.decrypt(data, password);
2018-04-01 01:16:42 +02:00
let str = false;
try {
str = bytes.toString(CryptoJS.enc.Utf8);
} catch (e) {}
2019-11-29 00:59:06 +01:00
2020-11-22 10:18:05 +01:00
// for some reason, sometimes decrypt would succeed with incorrect password and return random couple of characters.
2019-11-29 00:59:06 +01:00
// at least in nodejs environment. so with this little hack we are not alowing to encrypt data that is shorter than
// 10 characters, and thus if decrypted data is less than 10 characters we assume that decrypt actually failed.
if (str.length < 10) return false;
2018-04-01 01:16:42 +02:00
return str;
2018-03-30 20:31:10 +02:00
};