All files / src/modules crypto.js

100% Statements 12/12
100% Branches 2/2
100% Functions 5/5
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 479x           34x 34x               47x 47x         10x 10x 10x     3x           8x         34x     9x            
const sjcl = require('sjcl');
 
// PRIVATE
 
// Encrypts the EOS private key with the derived key
function encryptWithKey(unencrypted, key) {
  const encrypted = JSON.parse(sjcl.encrypt(key, unencrypted, { mode: 'gcm' }));
  return JSON.stringify(encrypted);
}
 
// PUBLIC
 
// Derive the key used for encryption/decryption
function deriveKey(password, salt) {
  // NOTE Passing in at least an empty string for the salt, will prevent cached keys, which can lead to false positives in the test suite
  const { key } = sjcl.misc.cachedPbkdf2(password, { iter: 1000, salt: salt || '' });
  return key;
}
 
// Decrypts the encrypted EOS private key with the derived key
function decryptWithKey(encrypted, key) {
  try {
    const encryptedData = JSON.stringify(Object.assign(JSON.parse(encrypted), { mode: 'gcm' }));
    return sjcl.decrypt(key, encryptedData);
  } catch (err) {
    // console.error('Decryption Error:', err);
    return '';
  }
}
 
// Decrypts the encrypted EOS private key with wallet password, and salt
function decrypt(encrypted, password, salt) {
  return decryptWithKey(encrypted, deriveKey(password, salt));
}
 
// Encrypts the EOS private key with wallet password, and salt
function encrypt(unencrypted, password, salt) {
  return encryptWithKey(unencrypted, deriveKey(password, salt));
}
 
module.exports = {
  decrypt,
  decryptWithKey,
  deriveKey,
  encrypt
};