dartflutterpointycastle

Obtain hex string from the ECPrivateKey and ECPublicKey objects


I'm trying to use pointy castle to generate a public and private keypair using the secp256k1 curve. I think i have successfully created an AsymmetricKeyPair composed of an ECPrivateKey and ECPublicKey but i can't obtain their corresponding hex strings (something like this:

private: ee792658c8eb1f8c3d2010ee6bc2ea328bb584fbecbfb17cf0f9103d122a8716,

public: 041b3f87beb2559aa3ca1c1d9ebb9447e4842d21cf0c70db103acc0db27ea8c27536fc2b1405b8a16a460ca089b01de8c556825927b4890b7236e357787f3e6d54).

When i try to print the keys, all i get is "Instance of 'ECPrivateKey'" and "Instance of 'ECPublicKey'" whether i use .toString() or not.

I have been looking around everywhere for a way to do this but i can't find one, is it even possible?

Here's my code:

SecureRandom secureRandom = new SecureRandom("Fortuna");
var random = new Random.secure();
List<int> seeds = [];
for (int i = 0; i < 32; i++) {
  seeds.add(random.nextInt(255));
}
secureRandom.seed(new KeyParameter(new Uint8List.fromList(seeds)));

var domainParams = new ECDomainParameters("secp256k1");

var ecParams = new ECKeyGeneratorParameters(domainParams);
var params = new ParametersWithRandom<ECKeyGeneratorParameters>(
    ecParams, secureRandom);

var keyGenerator = new ECKeyGenerator();
keyGenerator.init(params);

AsymmetricKeyPair keypair = keyGenerator.generateKeyPair();

ECPrivateKey privateKey = keypair.privateKey;
ECPublicKey publicKey = keypair.publicKey;

print(privateKey);
print(privateKey.toString());

print(publicKey);
print(publicKey.toString());

Solution

  • The private key and public point are member variables of their respective keys:

      ECPrivateKey privateKey = keypair.privateKey;
      ECPublicKey publicKey = keypair.publicKey;
    
      // in decimal
      print(privateKey.d);
      print(publicKey.Q.x);
      print(publicKey.Q.y);
    
      // in hex
      print(privateKey.d.toRadixString(16));
      print(publicKey.Q.x.toBigInteger().toRadixString(16));
      print(publicKey.Q.y.toBigInteger().toRadixString(16));