0

I've generated a public key using elliptic curves, but whenever I get the encoding of the key, it changes. I would like to use the encoding for a public address of a blockchain I am implementing. See below

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;

class Scratch {
    public static void main(String[] args) throws Exception {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
        ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1");
        keyGen.initialize(ecSpec);
        KeyPair kp = keyGen.generateKeyPair();

        PublicKey k = kp.getPublic();
        byte[] one = k.getEncoded();
        byte[] two = k.getEncoded();

        System.out.println(one);
        System.out.println(two);

    }
}

With output

[B@4eec7777
[B@3b07d329

Does anyone know why this is happening? My guess is that it is the expected behavior and I am just misunderstanding something fundamental here.

1 Answers1

0

You are printing the memory address of the byte[], not the key itself. You can't "print" a byte array because it is binary data, you need to encode it somehow first. Hex and base64 are both good encodings for displaying binary data. For memory, other blockchain implementations like to use base58.

Here is an example using base64:

String b64Str = Base64.getEncoder().encodeToString(one);
System.out.println(b64Str);
Luke Joshua Park
  • 9,527
  • 5
  • 27
  • 44
  • I don't know about all blockchains, but bitcoin uses the _address_ which is a _hash_ of only the public _point_ -- not the publickey encoding returned by JCE, which is the ASN.1 structure `SubjectPublicKeyInfo` defined by X.509 and more easily available in RFC3279 -- and conventionally _displays_ it for human use in base58 (with a 4-byte redundancy check). – dave_thompson_085 Aug 08 '18 at 01:49
  • @dave_thompson_085 Ahh yes, I forgot about base58, I just knew it wasn't base64. Thanks for the correction. – Luke Joshua Park Aug 08 '18 at 01:50