Skip to content
Draft
Show file tree
Hide file tree
Changes from 20 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/request-node/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
"@requestnetwork/utils": "0.54.0",
"chalk": "4.1.0",
"cors": "2.8.5",
"dotenv": "8.2.0",
"dotenv": "16.5.0",
"ethers": "5.7.2",
"express": "4.21.0",
"graphql": "16.8.1",
Expand Down
2 changes: 1 addition & 1 deletion packages/smart-contracts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"@types/mocha": "8.2.3",
"@types/node": "18.11.9",
"chai": "4.3.4",
"dotenv": "10.0.0",
"dotenv": "16.5.0",
"ethereum-waffle": "3.4.4",
"ethers": "5.7.2",
"ganache-cli": "6.12.0",
Expand Down
6 changes: 4 additions & 2 deletions packages/utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@
"test:watch": "yarn test --watch"
},
"dependencies": {
"@ecies/ciphers": "0.2.3",
"@noble/curves": "1.8.1",
"@noble/hashes": "1.7.1",
"@requestnetwork/types": "0.54.0",
"@toruslabs/eccrypto": "4.0.0",
"eciesjs": "0.4.14",
"ethers": "5.7.2",
"secp256k1": "4.0.4",
"tslib": "2.5.0"
},
"devDependencies": {
Expand Down
4 changes: 2 additions & 2 deletions packages/utils/src/crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ import {
import {
ecDecrypt,
ecEncrypt,
getAddressFromPrivateKey,
getAddressFromPublicKey,
ecRecover,
ecSign,
getAddressFromPrivateKey,
getAddressFromPublicKey,
} from './crypto/ec-utils';
import { deepSort } from './utils';

Expand Down
4 changes: 2 additions & 2 deletions packages/utils/src/crypto/crypto-wrapper.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { createCipheriv, createDecipheriv, randomBytes as cryptoRandomBytes } from 'crypto';

/**
* Functions to manage native crypto functions of nodeJs
* Functions to manage native crypto functions of Node.js
*/
export {
decryptWithAes256cbc,
Expand Down Expand Up @@ -77,7 +77,7 @@ async function encryptWithAes256gcm(data: Buffer, key: Buffer): Promise<Buffer>
/**
* Decrypts an encrypted buffer using AES-256-cbc plus a random Initialization Vector (IV)
*
* @param encrypted the data to decrypt
* @param encryptedAndIv the data to decrypt
* @param key key of the encryption
*
* @returns Promise resolving a buffer containing the data decrypted
Expand Down
81 changes: 81 additions & 0 deletions packages/utils/src/crypto/ec-utils-legacy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { PrivateKey, PublicKey } from 'eciesjs';
import { secp256k1 } from '@noble/curves/secp256k1';
import { sha256, sha512 } from '@noble/hashes/sha2';
import { aes256cbc } from '@ecies/ciphers/aes';
import { hmac } from '@noble/hashes/hmac';

/**
* Decrypt the `eccrypto` way: using ECIES with AES-CBC-MAC and SHA-512 derivation.
* Migrated from https://github.com/torusresearch/eccrypto/blob/923ebc03e5be016a7ee27a04d8c3b496ee949bfa/src/index.ts#L264
* but using `@noble/curves` instead of `elliptics`
*/
export const ecDecryptLegacy = (privateKey: string, dataHex: string, padding = false): string => {
const { iv, ephemPublicKey, mac, ciphertext } = legacyAes256CbcMacSplit(dataHex);
const receiverPrivateKey = PrivateKey.fromHex(privateKey.replace(/^0x/, ''));
const sharedKey = deriveSharedKeyWithSha512(receiverPrivateKey, ephemPublicKey, padding);
const encryptionKey = sharedKey.subarray(0, 32);
const macKey = sharedKey.subarray(32);
const dataToMac = Buffer.concat([iv, ephemPublicKey.toBytes(false), ciphertext]);
const macGood = hmacSha256Verify(macKey, dataToMac, mac);
if (!macGood) {
if (!padding) {
return ecDecryptLegacy(privateKey, dataHex, true);
}
throw new Error('The encrypted data is not well formatted');
}
const decrypted = aes256cbc(encryptionKey, iv).decrypt(ciphertext);
return Buffer.from(decrypted).toString();
};

const hmacSha256Verify = (key: Uint8Array, msg: Uint8Array, sig: Uint8Array): boolean => {
const expectedSig = hmac(sha256, key, msg);
return equalConstTime(expectedSig, sig);
};

// Compare two buffers in constant time to prevent timing attacks.
const equalConstTime = (b1: Uint8Array, b2: Uint8Array): boolean => {
if (b1.length !== b2.length) {
return false;
}
let res = 0;
for (let i = 0; i < b1.length; i++) {
res |= b1[i] ^ b2[i];
}
return res === 0;
};
Comment on lines +30 to +45
Copy link
Member Author

@alexandre-abrioux alexandre-abrioux Apr 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

By using the Web Crypto API (available in Node.js and in browsers) this whole code (both methods hmacSha256Verify + equalConstTime) could be replaced by a single line:

globalThis.crypto.subtle.verify("HMAC", key, sig, msg)

Pros:

  • no need to use a library (@noble/hashes)
  • the Web Crypto API is async so non-thread blocking

Cons

  • the Web Crypto API is async so the calling code needs to be async too (but that's OK since ecEncrypt and ecDecrypt were already async in the previous implementation)
    - the Web Crypto API is only available in secure context (= HTTPS) (this could be a pain point in localhost environments)

Let me know if you would prefer it, I can easily make the switch.


const deriveSharedKeyWithSha512 = (
privateKey: PrivateKey,
publicKey: PublicKey,
padding = false,
): Uint8Array => {
const sharedPoint = secp256k1.getSharedSecret(privateKey.secret, publicKey.toBytes());
const paddedBytes = padding ? sharedPoint.subarray(1) : sharedPoint.subarray(2);
const hash = sha512.create().update(paddedBytes).digest();
return new Uint8Array(hash);
};

/**
* Split a legacy-encrypted hex string to its AES-CBC-MAC params.
* See legacy way of generating an encrypted strings with the `@toruslabs/eccrypto` > `elliptic` library:
* https://github.com/RequestNetwork/requestNetwork/blob/4597d373b0284787273471cf306dd9b849c9f76a/packages/utils/src/crypto/ec-utils.ts#L141
*/
const legacyAes256CbcMacSplit = (dataHex: string) => {
const buffer = Buffer.from(dataHex, 'hex');

const ivSize = 16;
const ephemPublicKeySize = 33;
const ephemPublicKeyEnd = ivSize + ephemPublicKeySize;
const macSize = 32;
const macEnd = ephemPublicKeyEnd + macSize;

const ephemPublicKeyStr = buffer.subarray(ivSize, ephemPublicKeyEnd);
const ephemPublicKey = new PublicKey(ephemPublicKeyStr);

return {
iv: buffer.subarray(0, ivSize),
ephemPublicKey,
mac: buffer.subarray(ephemPublicKeyEnd, macEnd),
ciphertext: buffer.subarray(macEnd),
};
};
142 changes: 37 additions & 105 deletions packages/utils/src/crypto/ec-utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { publicKeyConvert, ecdsaRecover } from 'secp256k1';
import { ethers } from 'ethers';
import { Ecies, decrypt, encrypt } from '@toruslabs/eccrypto';
import { decrypt, ECIES_CONFIG, encrypt, PublicKey } from 'eciesjs';
import {
computeAddress,
hexlify,
joinSignature,
recoverPublicKey,
SigningKey,
} from 'ethers/lib/utils';
import { ecDecryptLegacy } from './ec-utils-legacy';

/**
* Function to manage Elliptic-curve cryptography
Expand All @@ -14,6 +20,11 @@ export {
ecSign,
};

ECIES_CONFIG.ellipticCurve = 'secp256k1';
ECIES_CONFIG.isEphemeralKeyCompressed = false;
ECIES_CONFIG.symmetricAlgorithm = 'aes-256-gcm';
ECIES_CONFIG.symmetricNonceLength = 16;

/**
* Function to derive the address from an EC private key
*
Expand All @@ -26,7 +37,7 @@ function getAddressFromPrivateKey(privateKey: string): string {
if (!privateKey.match(/^0x/)) {
privateKey = `0x` + privateKey;
}
return ethers.utils.computeAddress(ethers.utils.hexlify(privateKey));
return computeAddress(hexlify(privateKey));
} catch (e) {
if (
e.message === 'private key length is invalid' ||
Expand All @@ -48,36 +59,30 @@ function getAddressFromPrivateKey(privateKey: string): string {
*/
function getAddressFromPublicKey(publicKey: string): string {
try {
return ethers.utils.computeAddress(compressPublicKey(publicKey));
const compressedKey = PublicKey.fromHex(publicKey).toHex(true);
return computeAddress(`0x${compressedKey}`);
} catch (e) {
if (
e.message === 'public key length is invalid' ||
e.message === 'Expected public key to be an Uint8Array with length [33, 65]' ||
e.code === 'INVALID_ARGUMENT'
) {
if (e.code === 'INVALID_ARGUMENT' || e.message === 'second arg must be public key') {
throw new Error('The public key must be a string representing 64 bytes');
}
throw e;
}
}

/**
* Function ecSigndata with ECDSA
* Function ecSign data with ECDSA
*
* @param privateKey the private key used to sign the message
* @param data the data to sign
*
* @returns the signature
*/
function ecSign(privateKey: string, data: string): string {
try {
const signingKey = new ethers.utils.SigningKey(privateKey);
return ethers.utils.joinSignature(signingKey.signDigest(data));
const signingKey = new SigningKey(privateKey);
return joinSignature(signingKey.signDigest(data));
} catch (e) {
if (
e.message === 'private key length is invalid' ||
e.message === 'Expected private key to be an Uint8Array with length 32' ||
e.code === 'INVALID_ARGUMENT'
) {
if (e.code === 'INVALID_ARGUMENT') {
throw new Error('The private key must be a string representing 32 bytes');
}
throw e;
Expand All @@ -94,30 +99,9 @@ function ecSign(privateKey: string, data: string): string {
*/
function ecRecover(signature: string, data: string): string {
try {
signature = signature.replace(/^0x/, '');
data = data.replace(/^0x/, '');
// split into v-value and sig
const sigOnly = signature.substring(0, signature.length - 2); // all but last 2 chars
const vValue = signature.slice(-2); // last 2 chars

const recoveryNumber = vValue === '1c' ? 1 : 0;

return ethers.utils.computeAddress(
Buffer.from(
ecdsaRecover(
new Uint8Array(Buffer.from(sigOnly, 'hex')),
recoveryNumber,
new Uint8Array(Buffer.from(data, 'hex')),
false,
),
),
);
return computeAddress(recoverPublicKey(data, signature));
} catch (e) {
if (
e.message === 'signature length is invalid' ||
e.message === 'Expected signature to be an Uint8Array with length 64' ||
e.code === 'INVALID_ARGUMENT'
) {
if (e.code === 'INVALID_ARGUMENT') {
throw new Error('The signature must be a string representing 66 bytes');
}
throw e;
Expand All @@ -130,26 +114,13 @@ function ecRecover(signature: string, data: string): string {
* @param publicKey the public key to encrypt with
* @param data the data to encrypt
*
* @returns the encrypted data
* @returns the encrypted data as a hex string
*/
async function ecEncrypt(publicKey: string, data: string): Promise<string> {
function ecEncrypt(publicKey: string, data: string): string {
try {
// encrypts the data with the publicKey, returns the encrypted data with encryption parameters (such as IV..)
const compressed = compressPublicKey(publicKey);
const encrypted = await encrypt(Buffer.from(compressed), Buffer.from(data));

// Transforms the object with the encrypted data into a smaller string-representation.
return Buffer.concat([
encrypted.iv,
publicKeyConvert(encrypted.ephemPublicKey),
encrypted.mac,
encrypted.ciphertext,
]).toString('hex');
return encrypt(publicKey, Buffer.from(data)).toString('hex');
} catch (e) {
if (
e.message === 'public key length is invalid' ||
e.message === 'Expected public key to be an Uint8Array with length [33, 65]'
) {
if (e.message === 'second arg must be public key') {
throw new Error('The public key must be a string representing 64 bytes');
}
throw e;
Expand All @@ -160,62 +131,23 @@ async function ecEncrypt(publicKey: string, data: string): Promise<string> {
* Function to decrypt data with a public key
*
* @param privateKey the private key to decrypt with
* @param data the data to decrypt
* @param dataHex the hex data to decrypt
*
* @returns the decrypted data
*/
async function ecDecrypt(privateKey: string, data: string): Promise<string> {
function ecDecrypt(privateKey: string, dataHex: string): string {
try {
const buf = await decrypt(Buffer.from(privateKey.replace(/^0x/, ''), 'hex'), eciesSplit(data));
return buf.toString();
return decrypt(privateKey.replace(/^0x/, ''), Buffer.from(dataHex, 'hex')).toString();
} catch (e) {
if (
e.message === 'Bad private key' ||
e.message === 'Expected private key to be an Uint8Array with length 32'
) {
if (e.message.startsWith('invalid Point')) {
return ecDecryptLegacy(privateKey, dataHex);
}
if (e.message === 'Invalid private key') {
throw new Error('The private key must be a string representing 32 bytes');
}
if (
e.message === 'public key length is invalid' ||
e.message === 'Expected public key to be an Uint8Array with length [33, 65]' ||
e.message === 'Bad MAC' ||
e.message === 'bad MAC after trying padded' ||
e.message === 'the public key could not be parsed or is invalid' ||
e.message === 'Public Key could not be parsed'
) {
if (e.message === 'second arg must be public key') {
throw new Error('The encrypted data is not well formatted');
}
throw e;
}
}

/**
* Converts a public key to its compressed form.
*/
function compressPublicKey(publicKey: string): Uint8Array {
publicKey = publicKey.replace(/^0x/, '');
// if there are more bytes than the key itself, it means there is already a prefix
if (publicKey.length % 32 === 0) {
publicKey = `04${publicKey}`;
}
return publicKeyConvert(Buffer.from(publicKey, 'hex'));
}

/**
* Split an encrypted string to ECIES params
* inspired from https://github.com/pubkey/eth-crypto/blob/master/src/ecDecrypt-with-private-key.js
*/
const eciesSplit = (str: string): Ecies => {
const buf = Buffer.from(str, 'hex');

const ephemPublicKeyStr = buf.toString('hex', 16, 49);

return {
iv: Buffer.from(buf.toString('hex', 0, 16), 'hex'),
mac: Buffer.from(buf.toString('hex', 49, 81), 'hex'),
ciphertext: Buffer.from(buf.toString('hex', 81, buf.length), 'hex'),
ephemPublicKey: Buffer.from(
publicKeyConvert(new Uint8Array(Buffer.from(ephemPublicKeyStr, 'hex')), false),
),
};
};
Loading