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 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 42x 42x 42x 13x 13x 13x 38x 38x 15x 15x 15x 480x 15x 38x 38x 1x 3x 3x 3x 1x 39x 39x 39x 1x 7x 7x 1x 7x 7x 7x 7x 1x 3x 3x 3x 3x 1x 7x 7x 7x 6x 1x 1x 7x 4x 3x 3x 1x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 22x 1x 1x 23x 23x 1x 23x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2x 13x 13x 10x 3x 1x 7x 7x 7x 7x 7x 7x 7x 9x 6x 6x 1x 9x 9x 9x 9x | import { ec as EllipticCurve } from 'elliptic' import * as BN from 'bn.js' import { randomBytes } from './cryptoRandom' import { FailedDecryptionError } from '../errors' import { getPublicKeyFromPrivate } from '../keys' import { hashSha256Sync, hashSha512Sync } from './sha2Hash' import { createHmacSha256 } from './hmacSha256' import { createCipher } from './aesCipher' import { getAesCbcOutputLength, getBase64OutputLength } from '../utils' const ecurve = new EllipticCurve('secp256k1') /** * Controls how the encrypted data buffer will be encoded as a string in the JSON payload. * Options: * `hex` -- the legacy default, file size increase 100% (2x). * `base64` -- file size increased ~33%. * @ignore */ export type CipherTextEncoding = 'hex' | 'base64' /** * @ignore */ export type CipherObject = { iv: string, ephemeralPK: string, cipherText: string, /** If undefined then hex encoding is used for the `cipherText` string. */ cipherTextEncoding?: CipherTextEncoding, mac: string, wasString: boolean } /** * @ignore */ export type SignedCipherObject = { /** Hex encoded DER signature (up to 144 chars) */ signature: string, /** Hex encoded public key (66 char length) */ publicKey: string, /** The stringified json of a `CipherObject` */ cipherText: string } /** * @ignore */ export 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 */ function sharedSecretToKeys(sharedSecret: Buffer): { encryptionKey: Buffer; hmacKey: Buffer; } { // generate mac and encryption key from shared secret const hashedSecret = hashSha512Sync(sharedSecret) return { encryptionKey: hashedSecret.slice(0, 32), hmacKey: hashedSecret.slice(32) } } /** * Hex encodes a 32-byte BN.js instance. * The result string is zero padded and always 64 characters in length. * @ignore */ export function getHexFromBN(bnInput: BN): string { const hexOut = bnInput.toString('hex', 64) Eif (hexOut.length === 64) { return hexOut } else if (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.') } } /** * Returns a big-endian encoded 32-byte BN.js instance. * The result Buffer is zero padded and always 32 bytes in length. * @ignore */ export function getBufferFromBN(bnInput: BN): Buffer { const result = bnInput.toArrayLike(Buffer, 'be', 32) Iif (result.byteLength !== 32) { throw new Error('Generated a 32-byte BN for encryption. Failing.') } return result } /** * Get details about the JSON envelope size overhead for ciphertext payloads. * @ignore */ export function getCipherObjectWrapper(opts: { wasString: boolean, cipherTextEncoding: CipherTextEncoding, }): { /** The stringified JSON string of an empty `CipherObject`. */ payloadShell: string, /** Total string length of all the `CipherObject` values that always have constant lengths. */ payloadValuesLength: number, } { // Placeholder structure of the ciphertext payload, used to determine the // stringified JSON overhead length. const shell: CipherObject = { iv: '', ephemeralPK: '', mac: '', cipherText: '', wasString: !!opts.wasString, } if (opts.cipherTextEncoding === 'base64') { shell.cipherTextEncoding = 'base64' } // Hex encoded 16 byte buffer. const ivLength = 32 // Hex encoded, compressed EC pubkey of 33 bytes. const ephemeralPKLength = 66 // Hex encoded 32 byte hmac-sha256. const macLength = 64 return { payloadValuesLength: ivLength + ephemeralPKLength + macLength, payloadShell: JSON.stringify(shell) } } /** * Get details about the JSON envelope size overhead for signed ciphertext payloads. * @param payloadShell - The JSON stringified empty `CipherObject` * @ignore */ export function getSignedCipherObjectWrapper(payloadShell: string): { /** The stringified JSON string of an empty `SignedCipherObject`. */ signedPayloadValuesLength: number; /** Total string length of all the `SignedCipherObject` values * that always have constant lengths */ signedPayloadShell: string; } { // Placeholder structure of the signed ciphertext payload, used to determine the // stringified JSON overhead length. const shell: SignedCipherObject = { signature: '', publicKey: '', cipherText: payloadShell } // Hex encoded DER signature, up to 72 byte length. const signatureLength = 144 // Hex encoded 33 byte public key. const publicKeyLength = 66 return { signedPayloadValuesLength: signatureLength + publicKeyLength, signedPayloadShell: JSON.stringify(shell) } } /** * Fast function that determines the final ASCII string byte length of the * JSON stringified ECIES encrypted payload. * @ignore */ export function eciesGetJsonStringLength(opts: { contentLength: number, wasString: boolean, sign: boolean, cipherTextEncoding: CipherTextEncoding }): number { const { payloadShell, payloadValuesLength } = getCipherObjectWrapper(opts) // Calculate the AES output length given the input length. const cipherTextLength = getAesCbcOutputLength(opts.contentLength) // Get the encoded string length of the cipherText. let encodedCipherTextLength: number if (!opts.cipherTextEncoding || opts.cipherTextEncoding === 'hex') { encodedCipherTextLength = (cipherTextLength * 2) } else Eif (opts.cipherTextEncoding === 'base64') { encodedCipherTextLength = getBase64OutputLength(cipherTextLength) } else { throw new Error(`Unexpected cipherTextEncoding "${opts.cipherTextEncoding}"`) } if (!opts.sign) { // Add the length of the JSON envelope, ciphertext length, and length of const values. return payloadShell.length + payloadValuesLength + encodedCipherTextLength } else { // Get the signed version of the JSON envelope const { signedPayloadShell, signedPayloadValuesLength } = getSignedCipherObjectWrapper(payloadShell) // Add length of the JSON envelope, ciphertext length, and length of the const values. return signedPayloadShell.length + signedPayloadValuesLength + payloadValuesLength + encodedCipherTextLength } } /** * Encrypt content to elliptic curve publicKey using ECIES * @param publicKey - secp256k1 public key hex string * @param content - content to encrypt * @return Object containing: * iv (initialization vector, hex encoding), * cipherText (cipher text either hex or base64 encoded), * mac (message authentication code, hex encoded), * ephemeral public key (hex encoded), * wasString (boolean indicating with or not to return a buffer or string on decrypt) * @private * @ignore */ export async function encryptECIES(publicKey: string, content: Buffer, wasString: boolean, cipherTextEncoding?: CipherTextEncoding): Promise<CipherObject> { const ecPK = ecurve.keyFromPublic(publicKey, 'hex').getPublic() const ephemeralSK = ecurve.genKeyPair() const ephemeralPK = Buffer.from(ephemeralSK.getPublic().encodeCompressed()) const sharedSecret = ephemeralSK.derive(ecPK) as BN const sharedSecretBuffer = getBufferFromBN(sharedSecret) const sharedKeys = sharedSecretToKeys(sharedSecretBuffer) const initializationVector = randomBytes(16) const cipherText = await aes256CbcEncrypt( initializationVector, sharedKeys.encryptionKey, content ) const macData = Buffer.concat([initializationVector, ephemeralPK, cipherText]) const mac = await hmacSha256(sharedKeys.hmacKey, macData) let cipherTextString: string if (!cipherTextEncoding || cipherTextEncoding === 'hex') { cipherTextString = cipherText.toString('hex') } else Eif (cipherTextEncoding === 'base64') { cipherTextString = cipherText.toString('base64') } else { throw new Error(`Unexpected cipherTextEncoding "${cipherTextEncoding}"`) } const result: CipherObject = { iv: initializationVector.toString('hex'), ephemeralPK: ephemeralPK.toString('hex'), cipherText: cipherTextString, mac: mac.toString('hex'), wasString: !!wasString } if (cipherTextEncoding && cipherTextEncoding !== 'hex') { result.cipherTextEncoding = cipherTextEncoding } return result } /** * 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) as BN const sharedSecretBuffer = getBufferFromBN(sharedSecret) const sharedKeys = sharedSecretToKeys(sharedSecretBuffer) const ivBuffer = Buffer.from(cipherObject.iv, 'hex') let cipherTextBuffer: Buffer Eif (!cipherObject.cipherTextEncoding || cipherObject.cipherTextEncoding === 'hex') { cipherTextBuffer = Buffer.from(cipherObject.cipherText, 'hex') } else if (cipherObject.cipherTextEncoding === 'base64') { cipherTextBuffer = Buffer.from(cipherObject.cipherText, 'base64') } else { throw new Error(`Unexpected cipherTextEncoding "${cipherObject.cipherText}"`) } const macData = Buffer.concat([ivBuffer, Buffer.from(ephemeralPK.encodeCompressed()), 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 function signECDSA(privateKey: string, content: string | Buffer): { publicKey: string, signature: string } { const contentBuffer = content instanceof Buffer ? content : Buffer.from(content) const ecPrivate = ecurve.keyFromPrivate(privateKey, 'hex') const publicKey = getPublicKeyFromPrivate(privateKey) const contentHash = hashSha256Sync(contentBuffer) const signature = ecPrivate.sign(contentHash) const signatureString: string = 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 function verifyECDSA( content: string | ArrayBuffer | Buffer, publicKey: string, signature: string): boolean { const contentBuffer = getBuffer(content) const ecPublic = ecurve.keyFromPublic(publicKey, 'hex') const contentHash = hashSha256Sync(contentBuffer) return ecPublic.verify(contentHash, <any>signature) } |