diff --git a/packages/crypto/src/lib/crypto.ts b/packages/crypto/src/lib/crypto.ts index 95a4984506..834d4c75f5 100644 --- a/packages/crypto/src/lib/crypto.ts +++ b/packages/crypto/src/lib/crypto.ts @@ -43,8 +43,7 @@ export const loadModules = (): Promise => { if (!globalThis.jestTesting) { log( - `✅ [BLS SDK] wasmExports loaded. ${ - Object.keys(exports).length + `✅ [BLS SDK] wasmExports loaded. ${Object.keys(exports).length } functions available. Run 'wasmExports' in the console to see them.` ); } @@ -66,8 +65,7 @@ export const loadModules = (): Promise => { if (!globalThis.jestTesting) { log( - `✅ [ECDSA SDK ${env}] wasmECDSA loaded. ${ - Object.keys(wasmECDSA).length + `✅ [ECDSA SDK ${env}] wasmECDSA loaded. ${Object.keys(wasmECDSA).length } functions available. Run 'wasmECDSA' in the console to see them.` ); } @@ -80,8 +78,7 @@ export const loadModules = (): Promise => { if (!globalThis.jestTesting) { log( - `✅ [SEV SNP Utils SDK] wasmSevSnpUtils loaded. ${ - Object.keys(exports).length + `✅ [SEV SNP Utils SDK] wasmSevSnpUtils loaded. ${Object.keys(exports).length } functions available. Run 'wasmSevSnpUtils' in the console to see them.` ); } @@ -104,6 +101,7 @@ export const unloadModules = () => { /** * Encrypt data with a BLS public key. + * We are using G1 for encryption and G2 for signatures * * @param publicKey hex-encoded string of the BLS public key to encrypt with * @param data Uint8Array of the data to encrypt @@ -114,12 +112,33 @@ export const encrypt = ( publicKey: string, data: Uint8Array, identity: Uint8Array -): string => { - return blsSdk.encrypt( - publicKey, - uint8arrayToString(data, 'base64'), - uint8arrayToString(identity, 'base64') - ); +): Promise => { + + const publicKey = Buffer.from(publicKeyHex, 'hex'); + + /** + * Our system uses BLS12-381 on the G1 curve for encryption. + * However, on the SDK side (this function), we expect the public key + * to use the G2 curve for signature purposes, hence the switch on public key length. + * + * The G2 curve, `Bls12381G2`, is typically associated with signature generation/verification, + * while G1 is associated with encryption. Here, the length of the public key determines how + * we handle the encryption and the format of the returned encrypted message. + */ + if (publicKeyHex.replace('0x', '').length !== 96) { + throw new InvalidParamType( + { + info: { + publicKeyHex, + }, + }, + `Invalid public key length. Expecting 96 characters, got ${publicKeyHex.replace('0x', '').length} instead.` + ); + } + return Buffer.from( + await blsEncrypt('Bls12381G2', publicKey, message, identity) + ).toString('base64'); + }; /**