All files / src encrypt.ts

97.14% Statements 68/70
80% Branches 8/10
100% Functions 6/6
97.14% Lines 68/70

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                            2x   2x 2x 2x 2x   2x 2x 2x 2x             2x             2x 2x     2x 2x 2x 2x 2x     2x       2x   2x             2x 2x   2x           2x               3x 3x     3x 3x 3x   3x     3x       3x   3x 3x             1x   2x         1x   1x           2x         18x                                     2x         10x 10x 10x 10x 10x   10x 10x 10x 10x   10x                   2x 12x 12x 10x 1x     9x     2x                   12x   12x 9x           8x         7x 7x 6x   4x     2x   2x  
/*
 * Copyright © 2019 Lisk Foundation
 *
 * See the LICENSE file at the top-level directory of this distribution
 * for licensing information.
 *
 * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
 * no part of this software, including this file, may be copied, modified,
 * propagated, or distributed except according to the terms contained in the
 * LICENSE file.
 *
 * Removal or modification of this copyright notice is prohibited.
 *
 */
import * as crypto from 'crypto';
 
import { bufferToHex, hexToBuffer } from './buffer';
import { convertPrivateKeyEd2Curve, convertPublicKeyEd2Curve } from './convert';
import { getPrivateAndPublicKeyBytesFromPassphrase } from './keys';
import { box, getRandomBytes, openBox } from './nacl';
 
const PBKDF2_ITERATIONS = 1e6;
const PBKDF2_KEYLEN = 32;
const PBKDF2_HASH_FUNCTION = 'sha256';
const ENCRYPTION_VERSION = '1';
 
export interface EncryptedMessageWithNonce {
	readonly encryptedMessage: string;
	readonly nonce: string;
}
 
export const encryptMessageWithPassphrase = (
	message: string,
	passphrase: string,
	recipientPublicKey: string,
): EncryptedMessageWithNonce => {
	const {
		privateKeyBytes: senderPrivateKeyBytes,
	} = getPrivateAndPublicKeyBytesFromPassphrase(passphrase);
	const convertedPrivateKey = Buffer.from(
		convertPrivateKeyEd2Curve(senderPrivateKeyBytes),
	);
	const recipientPublicKeyBytes = hexToBuffer(recipientPublicKey);
	const messageInBytes = Buffer.from(message, 'utf8');
	const nonceSize = 24;
	const nonce = getRandomBytes(nonceSize);
	const publicKeyUint8Array = convertPublicKeyEd2Curve(recipientPublicKeyBytes);
 
	// This cannot be reproduced, but external library have type union with null
	Iif (publicKeyUint8Array === null) {
		throw new Error('given public key is not a valid Ed25519 public key');
	}
 
	const convertedPublicKey = Buffer.from(publicKeyUint8Array);
 
	const cipherBytes = box(
		messageInBytes,
		nonce,
		convertedPublicKey,
		convertedPrivateKey,
	);
 
	const nonceHex = bufferToHex(nonce);
	const encryptedMessage = bufferToHex(cipherBytes);
 
	return {
		nonce: nonceHex,
		encryptedMessage,
	};
};
 
export const decryptMessageWithPassphrase = (
	cipherHex: string,
	nonce: string,
	passphrase: string,
	senderPublicKey: string,
): string => {
	const {
		privateKeyBytes: recipientPrivateKeyBytes,
	} = getPrivateAndPublicKeyBytesFromPassphrase(passphrase);
	const convertedPrivateKey = Buffer.from(
		convertPrivateKeyEd2Curve(recipientPrivateKeyBytes),
	);
	const senderPublicKeyBytes = hexToBuffer(senderPublicKey);
	const cipherBytes = hexToBuffer(cipherHex);
	const nonceBytes = hexToBuffer(nonce);
 
	const publicKeyUint8Array = convertPublicKeyEd2Curve(senderPublicKeyBytes);
 
	// This cannot be reproduced, but external library have type union with null
	Iif (publicKeyUint8Array === null) {
		throw new Error('given public key is not a valid Ed25519 public key');
	}
 
	const convertedPublicKey = Buffer.from(publicKeyUint8Array);
 
	try {
		const decoded = openBox(
			cipherBytes,
			nonceBytes,
			convertedPublicKey,
			convertedPrivateKey,
		);
 
		return Buffer.from(decoded).toString();
	} catch (error) {
		if (
			error.message.match(
				/bad nonce size|nonce must be a buffer of size crypto_box_NONCEBYTES/,
			)
		) {
			throw new Error('Expected nonce to be 24 bytes.');
		}
		throw new Error(
			'Something went wrong during decryption. Is this the full encrypted message?',
		);
	}
};
 
const getKeyFromPassword = (
	password: string,
	salt: Buffer,
	iterations: number,
): Buffer =>
	crypto.pbkdf2Sync(
		password,
		salt,
		iterations,
		PBKDF2_KEYLEN,
		PBKDF2_HASH_FUNCTION,
	);
 
export interface EncryptedPassphraseObject {
	readonly cipherText: string;
	readonly iterations?: number;
	readonly iv: string;
	readonly salt: string;
	readonly tag: string;
	readonly version: string;
	// tslint:disable-next-line no-mixed-interface
	readonly [key: string]: string | number | undefined;
}
 
const encryptAES256GCMWithPassword = (
	plainText: string,
	password: string,
	iterations: number = PBKDF2_ITERATIONS,
): EncryptedPassphraseObject => {
	const IV_BUFFER_SIZE = 12;
	const SALT_BUFFER_SIZE = 16;
	const iv = crypto.randomBytes(IV_BUFFER_SIZE);
	const salt = crypto.randomBytes(SALT_BUFFER_SIZE);
	const key = getKeyFromPassword(password, salt, iterations);
 
	const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
	const firstBlock = cipher.update(plainText, 'utf8');
	const encrypted = Buffer.concat([firstBlock, cipher.final()]);
	const tag = cipher.getAuthTag();
 
	return {
		iterations,
		cipherText: encrypted.toString('hex'),
		iv: iv.toString('hex'),
		salt: salt.toString('hex'),
		tag: tag.toString('hex'),
		version: ENCRYPTION_VERSION,
	};
};
 
const getTagBuffer = (tag: string): Buffer => {
	const TAG_BUFFER_SIZE = 16;
	const tagBuffer = hexToBuffer(tag, 'Tag');
	if (tagBuffer.length !== TAG_BUFFER_SIZE) {
		throw new Error('Tag must be 16 bytes.');
	}
 
	return tagBuffer;
};
 
const decryptAES256GCMWithPassword = (
	encryptedPassphrase: EncryptedPassphraseObject,
	password: string,
): string => {
	const {
		iterations = PBKDF2_ITERATIONS,
		cipherText,
		iv,
		salt,
		tag,
	} = encryptedPassphrase;
 
	const tagBuffer = getTagBuffer(tag);
	const key = getKeyFromPassword(
		password,
		hexToBuffer(salt, 'Salt'),
		iterations,
	);
 
	const decipher = crypto.createDecipheriv(
		'aes-256-gcm',
		key,
		hexToBuffer(iv, 'IV'),
	);
	decipher.setAuthTag(tagBuffer);
	const firstBlock = decipher.update(hexToBuffer(cipherText, 'Cipher text'));
	const decrypted = Buffer.concat([firstBlock, decipher.final()]);
 
	return decrypted.toString();
};
 
export const encryptPassphraseWithPassword = encryptAES256GCMWithPassword;
 
export const decryptPassphraseWithPassword = decryptAES256GCMWithPassword;