Skip to content

Instantly share code, notes, and snippets.

@thecipherBlock
Created May 12, 2022 11:30
Show Gist options
  • Save thecipherBlock/237171155fdbaa0a6ced098eef45a728 to your computer and use it in GitHub Desktop.
Save thecipherBlock/237171155fdbaa0a6ced098eef45a728 to your computer and use it in GitHub Desktop.
Convert secp256k1 privateKey to ethereum address in dart
import 'dart:typed_data';
import 'package:pointycastle/digests/keccak.dart';
import 'package:pointycastle/ecc/api.dart';
import 'package:pointycastle/ecc/curves/secp256k1.dart';
BigInt decodeToBigInt(List<int> magnitude) {
BigInt result;
if (magnitude.length == 1) {
result = BigInt.from(magnitude[0]);
} else {
result = BigInt.from(0);
for (var i = 0; i < magnitude.length; i++) {
var item = magnitude[magnitude.length - i - 1];
result |= (BigInt.from(item) << (8 * i));
}
}
if (result != BigInt.zero) {
return result.toUnsigned(result.bitLength);
}
return BigInt.zero;
}
Uint8List getPubAddressFromPrivKey(Uint8List privBytes) {
BigInt privKeyInUnsignedInt = decodeToBigInt(privBytes);
final ECDomainParameters params = ECCurve_secp256k1();
final publicKey = (params.G * privKeyInUnsignedInt)!;
Uint8List publicKeyBytes =
Uint8List.view(publicKey.getEncoded(false).buffer, 1);
final KeccakDigest keccakDigest = KeccakDigest(256);
Uint8List hashed = keccakDigest.process(publicKeyBytes);
return hashed.sublist(12, 32);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment