All files datona-crypto.js

94.81% Statements 73/77
66.67% Branches 4/6
100% Functions 20/20
95.89% Lines 70/73

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271                                                  1x 1x 1x 1x 1x 1x 1x 1x                               26x 23x 23x 23x             252x 249x 249x                     6x 4x 3x 3x       4x 2x 1x 1x                     1x                                                         2x 2x   2x               9x 7x 4x 4x               11x 7x               268x 261x 261x 256x 256x 256x 256x 256x   5x                 549x 549x                       2x   2x 2x 2x 2x 2x 2x 2x 2x 2x                           6x 4x 2x 2x                       23x 23x 23x                 5x 3x       5x 3x                           253x 253x 253x                 256x 256x          
"use strict";
 
/*
 * Datona Crypto Library
 *
 * datona-lib cryptographic features
 *
 * Copyright (C) 2020 Datona Labs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */
 
const errors = require('./errors');
const assert = require('./assertions');
const ecdsa = require('secp256k1');
const CryptoJS = require('crypto-js');
const FS = (typeof window === 'undefined') ? require('fs') : window.FS;
const keccak256 = require('js-sha3').keccak256;
const rlp = require('rlp');
const randomBytes = require('crypto').randomBytes;
 
 
/*
 * Classes
 */
 
/*
 * Encapsulates a private key and provides cryptographic functions that use it
 */
class Key {
 
  /*
   * Constructs the instance with the given private key
   */
  constructor(privateKey) {
    assert.isPrivateKey(privateKey, "privateKey");
    this.privateKey = Buffer.from(privateKey, 'hex');
    this.publicKey = ecdsa.publicKeyCreate(this.privateKey, false);
    this.address = publicKeyToAddress(this.publicKey);
  }
 
  /*
   * Signs the given hash with this key
   */
  sign(hash) {
    assert.isHash(hash, "hash");
    const signature = ecdsa.sign(Buffer.from(hash, 'hex'), this.privateKey);
    return toDatonaSignature(signature);
  }
 
 
  /*
   * Encrypts the given data for the given key using the Elliptic Curve Integrated Encryption Scheme
   *   - The key derivation function used is the standard datona crypto hash function.
   *   - The encryption scheme used is AES-GCM.
   * ECIES has been selected instead of an asymmetric scheme like RSA for performance reasons.
   */
  encrypt(publicKeyTo, data) {
    assert.isInstanceOf(publicKeyTo, "public key", Buffer);
    assert.isPresent(data, "data");
    const sharedSecret = ecdsa.ecdh(publicKeyTo, this.privateKey).toString('hex');
    return CryptoJS.AES.encrypt(data,hash(sharedSecret)).toString();
  }
 
  decrypt(publicKeyFrom, data) {
    assert.isInstanceOf(publicKeyFrom, "public key", Buffer);
    assert.isPresent(data, "data");
    const sharedSecret = ecdsa.ecdh(publicKeyFrom, this.privateKey).toString('hex');
    return CryptoJS.AES.decrypt(data,hash(sharedSecret)).toString(CryptoJS.enc.Utf8);
  }
 
}
 
 
 
/*
 * Exports
 */
 
module.exports = {
  generateKey: generateKey,
  sign: sign,
  verify: verify,
  recover: recover,
  getSignatory: recover,
  calculateContractAddress: calculateContractAddress,
  publicKeyToAddress: publicKeyToAddress,
  hexToUint8Array: hexToUint8Array,
  uint8ArrayToHex: uint8ArrayToHex,
  hash: hash,
  fileToHash: fileToHash,
  Key: Key,
  Buffer: Buffer  // export to give javascript visibility in browser
};
 
 
 
/*
 * External Functions
 */
 
 
 /*
  * Generates a new Key object with a random private key.  NB: This function does
  * not use a true random source.  Use only for experimental and test purposes.
  */
function generateKey() {
  var privateKey;
  do {
    privateKey = randomBytes(32);
  } while (!ecdsa.privateKeyVerify(privateKey));
  return new Key(privateKey.toString('hex'));
}
 
 
/*
 * Signs the given hash using the given private key
 */
function sign(hash, privateKey) {
  assert.isHash(hash, "hash");
  assert.isPrivateKey(privateKey, "privateKey");
  const signature = ecdsa.sign(Buffer.from(hash, 'hex'), Buffer.from(privateKey, 'hex'));
  return toDatonaSignature(signature);
}
 
 
/*
 * Verifies that the signatory of the given hash and signature matches the given address
 */
function verify(hash, signature, address) {
  assert.isAddress(address, "address");
  return recover(hash, signature) === address;
}
 
 
/*
 * Recovers the address of the signatory of the given hash and signature
 */
function recover(hash, signature) {
  if (!assert.isHash(hash)) throw new errors.InvalidHashError("hash is missing or invalid");
  try {
    assert.isHexString(signature, "signature");
    const sig = fromDatonaSignature(signature);
    const publicKey = ecdsa.recover(Buffer.from(hash, 'hex'), sig.signature, sig.recovery, false);
    const publicKeyBuf = Buffer.from(publicKey, 'hex').slice(1); // Remove leading 0x04
    const hashOfPublicKey = keccak256(publicKeyBuf);
    return "0x" + Buffer.from(hashOfPublicKey, 'hex').slice(-20).toString('hex');
  } catch (error) {
    throw new errors.InvalidSignatureError(error.message, error.details);
  }
}
 
 
/*
 * Generates a keccak256 hash of the given data string
 */
function hash(data) {
  try {
    return keccak256(data);
  } catch (error) {
    throw new errors.HashingError("failed to hash data: " + error.message, data);
  }
}
 
 
/*
 * Returns a promise to generate a keccak256 hash of the given file.
 * If the nonce string is given, it is appended to the file.
 */
function fileToHash( file, nonce ){
  return new Promise(
    function( resolve, reject ){
      try {
        const hash = new keccak256.create();
        const fd = FS.createReadStream(file);
        fd.on('data', function(data) { hash.update(data); });
        fd.on('error', function(err){ reject( new errors.FileSystemError(err) ); });
        fd.on('close', function() {
          Iif (nonce) hash.update(nonce);
          hash.digest();
          resolve(hash.hex());
        });
      }
      catch(err){
        reject( new errors.FileSystemError(err) );
      }
    });
}
 
 
/*
 * Generates a contract address
 */
function calculateContractAddress(ownerAddress, nonce) {
  assert.isAddress(ownerAddress, "calculateContractAddress ownerAddress");
  assert.isNumber(nonce, "calculateContractAddress nonce");
  try {
    return "0x"+keccak256(rlp.encode([ownerAddress, nonce])).substring(24);
  }
  catch (error) {
    throw new errors.CryptographicError("Failed to calculate contract address: "+error.message);
  }
}
 
 
/*
 * Calculates the address associated with a public key
 */
function publicKeyToAddress(publicKey) {
  assert.isInstanceOf(publicKey, "publicKey", Uint8Array);
  const addressBuf = hash(publicKey.slice(1)).slice(-20 * 2);
  return "0x" + addressBuf.toString('hex');
}
 
 
/*
 * Hex conversion functions
 */
 
function hexToUint8Array(hexString) {
  assert.isHexString(hexString, 'hexString');
  return Buffer.from(hexString, 'hex');
}
 
function uint8ArrayToHex(buffer) {
  assert.isInstanceOf(buffer, "buffer", Uint8Array);
  return Buffer.from(buffer).toString('hex');
}
 
 
/*
 * Internal Functions
 */
 
 
/*
 * converts a signature produced by the secp256k1 library (with it's s and r values) to a
 * Datona Signature string
 */
function toDatonaSignature(sig) {
  var recovery = Buffer.alloc(1);
  recovery[0] = sig.recovery;
  return sig.signature.toString('hex') + recovery.toString('hex');
}
 
 
/*
 * converts a Datona Signature string into a signature object compatible with the
 * secp256k1 library
 */
function fromDatonaSignature(sigStr) {
  const sigBuffer = Buffer.from(sigStr, 'hex');
  return {
    signature: sigBuffer.slice(0, -1),
    recovery: sigBuffer[sigBuffer.length - 1]
  };
}