All files / crypto/src ECDH.js

21.74% Statements 5/23
100% Branches 0/0
0% Functions 0/2
21.74% Lines 5/23

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                  1x 1x 1x 1x                                                                                                                                   1x  
/**
 * Copyright (c) Benjamin Ansbach - all rights reserved.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
 
'use strict';
 
const Sha = require('@pascalcoin-sbx/common').Sha;
const BC = require('@pascalcoin-sbx/common').BC;
const AES = require('./AES');
const elliptic = require('elliptic/lib/elliptic/ec/index');
 
/**
 * AES encryption / decryption for PascalCoin.
 */
class ECDH {
  /**
   * Encrypts the given data with the given public key.
   *
   * @param {BC|Buffer|Uint8Array|String} data
   * @param {PublicKey} publicKey
   * @returns {BC}
   */
  static encrypt(publicKey, data) {
    data = BC.from(data);
    let ecCurve = elliptic(publicKey.curve.name);
    let tempKey = ecCurve.genKeyPair();
    let pubkey = ecCurve.keyFromPublic(publicKey.ecdh.buffer);
    let sharedSecret = tempKey.derive(pubkey.getPublic());
    let secrectkey = Sha.sha512(new BC(sharedSecret.toArray()));
 
    let encryptedData = AES.encryptZeroPadding(
      secrectkey.slice(0, 32),
      data,
      new Uint8Array(16)
    );
 
    return {
      data: encryptedData,
      key: secrectkey.slice(32, 64),
      publicKey: new BC(tempKey.getPublic(true, 'buffer'))
    };
  }
 
  /**
   * Decrypts the given data.
   *
   * @param {PrivateKey} privateKey
   * @param {BC|Buffer|Uint8Array|String} publicKey
   * @param {BC|Buffer|Uint8Array|String} data
   * @returns {BC}
   */
  static decrypt(privateKey, publicKey, data, origMsgLength) {
    publicKey = BC.from(publicKey);
    data = BC.from(data);
    let ecCurve = elliptic(privateKey.curve.name);
    let ecPrivateKey = ecCurve.keyFromPrivate(privateKey.key.buffer);
    let ecPublicKey = ecCurve.keyFromPublic(publicKey.buffer);
    let sharedSecret = ecPrivateKey.derive(ecPublicKey.getPublic());
    let secrectKey = Sha.sha512(new BC(Buffer.from(sharedSecret.toArray())));
 
    let decryptedData = AES.decryptZero(
      secrectKey.slice(0, 32),
      data,
      new Uint8Array(16)
    );
 
    let decryptedDataWithPaddingRemoved = decryptedData.slice(0, origMsgLength);
 
    return {
      data: decryptedDataWithPaddingRemoved,
      key: secrectKey.slice(32, 32)
    };
  }
}
 
module.exports = ECDH;