0

I am looking for a dart package in order to implement key exchange protocol (Elliptic-curve Diffie–Hellman) in a Flutter application.

  • app generates a key pair during login and sends the public key to server (so a new key pair is generated for every login)
  • server sends back its public key that it just generated
  • app generates a secret key from its private key and server's public key
  • app includes the hmac of all subsequent messages sent to the server

I took a look at pointycastle, which has supported Diffie–Hellman. But I don't find any method where to generate a secret key. This is what java does to generate:

 KeyAgreement a = KeyAgreement.getInstance("ECDH", "SC");
 a.init(mProvisionerPrivaetKey);
 a.doPhase(publicKey, true);

Wonder if there's some clue you found to generate a secret key from its private key and server's public key in dart.

AndyDing
  • 1
  • 1

1 Answers1

0

This is how to generate a Java compatible shared secret from a local EC key pair and the server's public point using pointycastle. (Note that Java's KeyAgreement only uses the x co-ordinate of the point - y is unused. I'm not familiar with the SC provider, which may do things differently.)

Uint8List sharedSecret(AsymmetricKeyPair localPair, ECPoint remotePublicPoint) {
  var ss = remotePublicPoint * (localPair.privateKey as ECPrivateKey).d;
  return hex.decode(toHex(ss.x.toBigInteger()));
}

toHex is a utility that prints a BigInt to hex, making sure that there are an even number of hex digits.

String toHex(BigInt bi) {
  var hex = bi.toRadixString(16);
  return (hex.length & 1 == 0) ? hex : '0$hex';
}

hex.decode is from package:convert (notice - not dart:convert) so be sure to add it to pubspec.yaml and import it: import 'package:convert/convert.dart';

Finally, to parse the server's public point from hex in the form aaaaaa,bbbbbb use:

ECPoint parsePoint(String s) {
  var parts = s.split(',');
  return domainParams.curve.createPoint(
    BigInt.parse(parts[0], radix: 16),
    BigInt.parse(parts[1], radix: 16),
  );
}

where domainParams is your curve, for example:

var domainParams = ECCurve_secp256k1();
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
  • do you have any idea on this https://stackoverflow.com/questions/63151318/aes-encryption-in-flutter-not-working-properly – Uday Jul 31 '20 at 04:39