All files / src/encryption ec.ts

95.45% Statements 84/88
83.33% Branches 15/18
100% Functions 11/11
96.47% Lines 82/85

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      1x   1x 1x 1x 1x 1x 1x   1x                                 19x 19x 19x             15x 15x 15x             36x 36x             17x     17x 17x 544x   17x               36x 36x 36x                 1x 38x   38x 35x 3x     3x 3x                                   1x   19x   19x   19x 19x 19x 19x   19x   19x       19x   19x       19x     19x   19x                                         1x   17x 17x 17x 17x           17x 17x   17x   17x 17x   17x     17x 17x 17x 2x   15x       15x 12x   3x                             1x     7x 7x 7x 7x 7x 7x 7x   7x                   12x 9x 9x                       1x       12x 12x 12x 12x   12x    
 
// TODO: elliptic is only used here for secp256k1 opts. This can be replaced with a faster,
//       slimmer lib. 
import { ec as EllipticCurve } from 'elliptic'
import { BN } from '../bn'
import { randomBytes } from './cryptoRandom'
import { FailedDecryptionError } from '../errors'
import { getPublicKeyFromPrivate } from '../keys'
import { createSha2Hash } from './sha2Hash'
import { createHmacSha256 } from './hmacSha256'
import { createCipher } from './aesCipher'
 
const ecurve = new EllipticCurve('secp256k1')
 
/**
* @ignore
*/
export type CipherObject = {
  iv: string,
  ephemeralPK: string,
  cipherText: string,
  mac: string,
  wasString: boolean
}
 
/**
* @ignore
*/
async function aes256CbcEncrypt(iv: Buffer, key: Buffer, plaintext: Buffer): Promise<Buffer> {
  const cipher = await createCipher()
  const result = await cipher.encrypt('aes-256-cbc', key, iv, plaintext)
  return result
}
 
/**
* @ignore
*/
async function aes256CbcDecrypt(iv: Buffer, key: Buffer, ciphertext: Buffer): Promise<Buffer> {
  const cipher = await createCipher()
  const result = await cipher.decrypt('aes-256-cbc', key, iv, ciphertext)
  return result
}
 
/**
* @ignore
*/
async function hmacSha256(key: Buffer, content: Buffer) {
  const hmacSha256 = await createHmacSha256()
  return hmacSha256.digest(key, content)
}
 
/**
* @ignore
*/
function equalConstTime(b1: Buffer, b2: Buffer) {
  Iif (b1.length !== b2.length) {
    return false
  }
  let res = 0
  for (let i = 0; i < b1.length; i++) {
    res |= b1[i] ^ b2[i]  // jshint ignore:line
  }
  return res === 0
}
 
/**
* @ignore
*/
async function sharedSecretToKeys(sharedSecret: Buffer) {
  // generate mac and encryption key from shared secret
  const sha2Hash = await createSha2Hash()
  const hashedSecret = await sha2Hash.digest(sharedSecret, 'sha512')
  return {
    encryptionKey: hashedSecret.slice(0, 32),
    hmacKey: hashedSecret.slice(32)
  }
}
 
/**
* @ignore
*/
export function getHexFromBN(bnInput: BN) {
  const hexOut = bnInput.toString('hex')
 
  if (hexOut.length === 64) {
    return hexOut
  } else Eif (hexOut.length < 64) {
    // pad with leading zeros
    // the padStart function would require node 9
    const padding = '0'.repeat(64 - hexOut.length)
    return `${padding}${hexOut}`
  } else {
    throw new Error('Generated a > 32-byte BN for encryption. Failing.')
  }
}
 
/**
 * Encrypt content to elliptic curve publicKey using ECIES
 * @param {String} publicKey - secp256k1 public key hex string
 * @param {String | Buffer} content - content to encrypt
 * @return {Object} Object containing (hex encoded):
 *  iv (initialization vector), cipherText (cipher text),
 *  mac (message authentication code), ephemeral public key
 *  wasString (boolean indicating with or not to return a buffer or string on decrypt)
 * 
 * @private
 * @ignore
 */
export async function encryptECIES(publicKey: string, content: string | Buffer): 
  Promise<CipherObject> {
  const isString = (typeof (content) === 'string')
  // always copy to buffer
  const plainText = content instanceof Buffer ? Buffer.from(content) : Buffer.from(content)
 
  const ecPK = ecurve.keyFromPublic(publicKey, 'hex').getPublic()
  const ephemeralSK = ecurve.genKeyPair()
  const ephemeralPK = ephemeralSK.getPublic()
  const sharedSecret = ephemeralSK.derive(ecPK) as BN
 
  const sharedSecretHex = getHexFromBN(sharedSecret)
 
  const sharedKeys = await sharedSecretToKeys(
    Buffer.from(sharedSecretHex, 'hex')
  )
 
  const initializationVector = randomBytes(16)
 
  const cipherText = await aes256CbcEncrypt(
    initializationVector, sharedKeys.encryptionKey, plainText
  )
 
  const macData = Buffer.concat([initializationVector,
                                 Buffer.from(ephemeralPK.encode('array', true)),
                                 cipherText])
  const mac = await hmacSha256(sharedKeys.hmacKey, macData)
 
  return {
    iv: initializationVector.toString('hex'),
    ephemeralPK: ephemeralPK.encode('hex', true),
    cipherText: cipherText.toString('hex'),
    mac: mac.toString('hex'),
    wasString: isString
  }
}
 
/**
 * Decrypt content encrypted using ECIES
 * @param {String} privateKey - secp256k1 private key hex string
 * @param {Object} cipherObject - object to decrypt, should contain:
 *  iv (initialization vector), cipherText (cipher text),
 *  mac (message authentication code), ephemeralPublicKey
 *  wasString (boolean indicating with or not to return a buffer or string on decrypt)
 * @return {Buffer} plaintext
 * @throws {FailedDecryptionError} if unable to decrypt
 * @private
 * @ignore
 */
export async function decryptECIES(privateKey: string, cipherObject: CipherObject): 
  Promise<Buffer | string> {
  const ecSK = ecurve.keyFromPrivate(privateKey, 'hex')
  let ephemeralPK = null
  try {
    ephemeralPK = ecurve.keyFromPublic(cipherObject.ephemeralPK, 'hex').getPublic()
  } catch (error) {
    throw new FailedDecryptionError('Unable to get public key from cipher object. '
      + 'You might be trying to decrypt an unencrypted object.')
  }
 
  const sharedSecret = ecSK.derive(ephemeralPK)
  const sharedSecretBuffer = Buffer.from(getHexFromBN(sharedSecret), 'hex')
 
  const sharedKeys = await sharedSecretToKeys(sharedSecretBuffer)
 
  const ivBuffer = Buffer.from(cipherObject.iv, 'hex')
  const cipherTextBuffer = Buffer.from(cipherObject.cipherText, 'hex')
 
  const macData = Buffer.concat([ivBuffer,
                                 Buffer.from(ephemeralPK.encode('array', true)),
                                 cipherTextBuffer])
  const actualMac = await hmacSha256(sharedKeys.hmacKey, macData)
  const expectedMac = Buffer.from(cipherObject.mac, 'hex')
  if (!equalConstTime(expectedMac, actualMac)) {
    throw new FailedDecryptionError('Decryption failed: failure in MAC check')
  }
  const plainText = await aes256CbcDecrypt(
    ivBuffer, sharedKeys.encryptionKey, cipherTextBuffer
  )
 
  if (cipherObject.wasString) {
    return plainText.toString()
  } else {
    return plainText
  }
}
 
/**
 * Sign content using ECDSA
 *
 * @param {String} privateKey - secp256k1 private key hex string
 * @param {Object} content - content to sign
 * @return {Object} contains:
 * signature - Hex encoded DER signature
 * public key - Hex encoded private string taken from privateKey
 * @private
 * @ignore
 */
export async function signECDSA(privateKey: string, content: string | Buffer): Promise<{ 
  publicKey: string, signature: string 
}> {
  const contentBuffer = content instanceof Buffer ? content : Buffer.from(content)
  const ecPrivate = ecurve.keyFromPrivate(privateKey, 'hex')
  const publicKey = getPublicKeyFromPrivate(privateKey)
  const sha2Hash = await createSha2Hash()
  const contentHash = await sha2Hash.digest(contentBuffer)
  const signature = ecPrivate.sign(contentHash)
  const signatureString = signature.toDER('hex')
 
  return {
    signature: signatureString,
    publicKey
  }
}
 
/**
* @ignore
*/
function getBuffer(content: string | ArrayBuffer | Buffer) {
  if (content instanceof Buffer) return content
  else Iif (content instanceof ArrayBuffer) return Buffer.from(content)
  else return Buffer.from(content)
}
 
/**
 * Verify content using ECDSA
 * @param {String | Buffer} content - Content to verify was signed
 * @param {String} publicKey - secp256k1 private key hex string
 * @param {String} signature - Hex encoded DER signature
 * @return {Boolean} returns true when signature matches publickey + content, false if not
 * @private
 * @ignore
 */
export async function verifyECDSA(
  content: string | ArrayBuffer | Buffer,
  publicKey: string,
  signature: string) {
  const contentBuffer = getBuffer(content)
  const ecPublic = ecurve.keyFromPublic(publicKey, 'hex')
  const sha2Hash = await createSha2Hash()
  const contentHash = await sha2Hash.digest(contentBuffer)
 
  return ecPublic.verify(contentHash, <any>signature)
}