diff --git a/encryption.js b/encryption.js index 1a0df246..c403af88 100644 --- a/encryption.js +++ b/encryption.js @@ -1,6 +1,7 @@ let CryptoJS = require('crypto-js'); module.exports.encrypt = function(data, password) { + if (data.length < 10) throw new Error('data length cant be < 10'); let ciphertext = CryptoJS.AES.encrypt(data, password); return ciphertext.toString(); }; @@ -11,5 +12,11 @@ module.exports.decrypt = function(data, password) { try { str = bytes.toString(CryptoJS.enc.Utf8); } catch (e) {} + + // for some reason, sometimes decrypt would succeed with wrong password and return random couple of characters. + // 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; + return str; }; diff --git a/screen/selftest.js b/screen/selftest.js index 8fcdeca5..aa34ac8e 100644 --- a/screen/selftest.js +++ b/screen/selftest.js @@ -202,13 +202,12 @@ export default class Selftest extends Component { } // - - let crypted = encryption.encrypt('data', 'password'); + const data2encrypt = 'really long data string'; + let crypted = encryption.encrypt(data2encrypt, 'password'); let decrypted = encryption.decrypt(crypted, 'password'); - if (decrypted !== 'data' && crypted && decrypted) { - errorMessage += 'encryption lib is not ok; '; - isOk = false; + if (decrypted !== data2encrypt && crypted && decrypted) { + throw new Error('encryption lib is not ok'); } // diff --git a/tests/unit/encryption.js b/tests/unit/encryption.js index 73834f89..67f4e6aa 100644 --- a/tests/unit/encryption.js +++ b/tests/unit/encryption.js @@ -5,19 +5,28 @@ let c = require('../../encryption') describe('unit - encryption', function () { it('encrypts and decrypts', function () { - let crypted = c.encrypt('data', 'password'); - let decrypted = c.decrypt(crypted, 'password'); + const data2encrypt = 'really long data string bla bla really long data string bla bla really long data string bla bla'; + const crypted = c.encrypt(data2encrypt, 'password'); + const decrypted = c.decrypt(crypted, 'password'); assert.ok(crypted); assert.ok(decrypted); - assert.equal(decrypted, 'data'); - assert.ok(crypted !== 'data'); + assert.equal(decrypted, data2encrypt); + assert.ok(crypted !== data2encrypt); let decryptedWithBadPassword try { decryptedWithBadPassword = c.decrypt(crypted, 'passwordBad'); } catch (e) {} assert.ok(!decryptedWithBadPassword) + + let exceptionRaised = false; + try { + c.encrypt('yolo', 'password'); + } catch (_) { + exceptionRaised = true; + } + assert.ok(exceptionRaised); }) it('handles ok malformed data', function() {