Skip to content

Commit da1190e

Browse files
browgeorge
andcommitted
perf(mobile): compute NIP-44 ECDH with native libsecp256k1
ecdhSharedSecret used pointycastle's BigInt point multiplication, which is slow (about 5.9 ms on an iPhone SE) and not constant time. It now calls libsecp256k1's secp256k1_ecdh with a raw-x hash callback, wiping the decoded secret key afterwards. Co-authored-by: george <973be878edd6d4f79692a3827f20a6f7fe0ed0362f269ff6b6ba8867033d7d8e@sprout-oss.stage.blox.sqprod.co> Signed-off-by: Tom Brow <[email protected]>
1 parent 8161a7c commit da1190e

2 files changed

Lines changed: 93 additions & 29 deletions

File tree

‎mobile/lib/shared/crypto/ecdh.dart‎

Lines changed: 14 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,28 @@
11
import 'dart:math' as math;
22
import 'dart:typed_data';
33

4-
import 'package:pointycastle/ecc/curves/secp256k1.dart';
4+
import 'package:buzz_secp256k1/buzz_secp256k1.dart' as secp256k1;
55

66
/// Compute secp256k1 ECDH shared secret (raw x-coordinate, unhashed).
77
///
88
/// Both [privateKeyHex] and [publicKeyHex] are 64-char lowercase hex strings
9-
/// (32 bytes each). The public key is an x-only BIP-340 key.
9+
/// (32 bytes each). The public key is an x-only BIP-340 key, lifted to even Y.
1010
///
11-
/// Returns the 32-byte x-coordinate of the shared point.
11+
/// Returns the 32-byte x-coordinate of the shared point, computed in constant
12+
/// time by libsecp256k1. Throws [ArgumentError] when either key is invalid.
1213
Uint8List ecdhSharedSecret(String privateKeyHex, String publicKeyHex) {
13-
final params = ECCurve_secp256k1();
14-
15-
// Parse private key scalar.
16-
final d = BigInt.parse(privateKeyHex, radix: 16);
17-
18-
// Lift x-only public key to a full curve point (assume even y / prefix 02).
19-
final xBytes = hexToBytes(publicKeyHex);
20-
final compressed = Uint8List(33);
21-
compressed[0] = 0x02; // even y
22-
compressed.setRange(1, 33, xBytes);
23-
final pubPoint = params.curve.decodePoint(compressed);
24-
if (pubPoint == null) {
25-
throw ArgumentError('Invalid public key: cannot decode point');
14+
if (privateKeyHex.length != 64 || publicKeyHex.length != 64) {
15+
throw ArgumentError('ECDH keys must be 64 hex characters');
2616
}
27-
28-
// Scalar multiplication: shared = d * Q
29-
final shared = pubPoint * d;
30-
if (shared == null || shared.isInfinity) {
31-
throw StateError('ECDH produced point at infinity');
17+
final secretKey = hexToBytes(privateKeyHex);
18+
try {
19+
return secp256k1.ecdhX(
20+
secretKey: secretKey,
21+
publicKey: hexToBytes(publicKeyHex),
22+
);
23+
} finally {
24+
secretKey.fillRange(0, secretKey.length, 0);
3225
}
33-
34-
// Extract 32-byte x-coordinate (big-endian, zero-padded).
35-
return bigIntTo32Bytes(shared.x!.toBigInteger()!);
3626
}
3727

3828
/// Generate secure random bytes.
@@ -58,8 +48,3 @@ Uint8List hexToBytes(String hex) {
5848
String bytesToHex(Uint8List bytes) {
5949
return bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
6050
}
61-
62-
Uint8List bigIntTo32Bytes(BigInt value) {
63-
final hexStr = value.toRadixString(16).padLeft(64, '0');
64-
return hexToBytes(hexStr);
65-
}
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import 'dart:math';
2+
import 'dart:typed_data';
3+
4+
import 'package:buzz/shared/crypto/ecdh.dart';
5+
import 'package:buzz/shared/crypto/nip44.dart';
6+
import 'package:flutter_test/flutter_test.dart';
7+
import 'package:nostr/nostr.dart' as nostr;
8+
import 'package:pointycastle/ecc/curves/secp256k1.dart';
9+
10+
/// The previous pure-Dart ECDH, kept as a reference implementation.
11+
Uint8List _referenceEcdh(String privateKeyHex, String publicKeyHex) {
12+
final params = ECCurve_secp256k1();
13+
final compressed = Uint8List(33)
14+
..[0] = 0x02
15+
..setRange(1, 33, hexToBytes(publicKeyHex));
16+
final shared =
17+
params.curve.decodePoint(compressed)! *
18+
BigInt.parse(privateKeyHex, radix: 16);
19+
return hexToBytes(
20+
shared!.x!.toBigInteger()!.toRadixString(16).padLeft(64, '0'),
21+
);
22+
}
23+
24+
String _randomSecretKey(Random rng) {
25+
while (true) {
26+
final hex = List.generate(
27+
32,
28+
(_) => rng.nextInt(256).toRadixString(16).padLeft(2, '0'),
29+
).join();
30+
try {
31+
nostr.Keys(hex);
32+
return hex;
33+
} on Object {
34+
// Out of range for secp256k1; draw again.
35+
}
36+
}
37+
}
38+
39+
void main() {
40+
test('matches the previous pure-Dart ECDH for random key pairs', () {
41+
final rng = Random(44);
42+
for (var i = 0; i < 32; i++) {
43+
final secretKey = _randomSecretKey(rng);
44+
final peer = nostr.Keys(_randomSecretKey(rng)).public;
45+
expect(
46+
ecdhSharedSecret(secretKey, peer),
47+
_referenceEcdh(secretKey, peer),
48+
);
49+
}
50+
});
51+
52+
test('NIP-44 v2 conversation key vector', () {
53+
expect(
54+
bytesToHex(
55+
getConversationKey(
56+
'0000000000000000000000000000000000000000000000000000000000000001',
57+
'c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5',
58+
),
59+
),
60+
'c41c775356fd92eadc63ff5a0dc1da211b268cbea22316767095b2871ea1412d',
61+
);
62+
});
63+
64+
test('rejects invalid keys', () {
65+
final valid = nostr.Keys('1' * 64).public;
66+
for (final (secretKey, publicKey) in [
67+
('0' * 64, valid),
68+
('1' * 64, '0' * 64),
69+
('1' * 62, valid),
70+
('1' * 64, valid.substring(2)),
71+
]) {
72+
expect(
73+
() => ecdhSharedSecret(secretKey, publicKey),
74+
throwsArgumentError,
75+
reason: '$secretKey / $publicKey',
76+
);
77+
}
78+
});
79+
}

0 commit comments

Comments
 (0)