1

I am working on a project to implement ECDH on an Android app and My problem is related to Java implementation, it generates a longer public key than I expected.

// Generate ephemeral ECDH keypair
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
kpg.initialize(256);
KeyPair kp = kpg.generateKeyPair();
byte[] ourPk = kp.getPublic().getEncoded();
System.out.println("ourPk len is " + ourPk.length);
// Display our public key
console.printf("Public Key: %s%n", printHexBinary(ourPk));

As far as I know or learn from here, if it is a 256-bit curve (secp256k1), keys will be:

Public key: 32 bytes * 2 + 1 = 65 (uncompressed)
Private key: 32 bytes

I expect the output (len of ourPk) 65, but the actual one is 91.

Terminou
  • 49
  • 6
  • What you get here is DER encoded subject public key info. You would have to extract the key from this der object. – Michał Krzywański Jul 25 '19 at 19:43
  • please refer to [RFC5480](https://tools.ietf.org/html/rfc5480#page-3) – Michał Krzywański Jul 25 '19 at 19:46
  • JCE KPG{"EC"}.initialize(256) uses secp256R1 (aka P-256 or prime256v1, part of former Suite B and widely used for TLS) **NOT secp256K1** (used for bitcoin). Although these curves have the same size representations they are not compatible or interoperable. For secp256k1 use `java.security.spec.ECGenParameterSpec` (see javadoc). – dave_thompson_085 Jul 26 '19 at 01:50

1 Answers1

3

As pointed out in comments you should refer to RFC5480 and its sections 2 and 2.2. kp.getPublic().getEncoded() will return DER encoded subject public key info. To extract EC public key from it - have a look at this code. I am using BouncyCastle library for DER objects handling :

Security.addProvider(new BouncyCastleProvider());
KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
kpg.initialize(256);
KeyPair kp = kpg.generateKeyPair();
byte[] ourPk = kp.getPublic().getEncoded();
System.out.println("ourPk len is " + ourPk.length);

ASN1Sequence sequence = DERSequence.getInstance(ourPk);

DERBitString subjectPublicKey = (DERBitString) sequence.getObjectAt(1);

byte[] subjectPublicKeyBytes = subjectPublicKey.getBytes();

System.out.println("EC key length : " + subjectPublicKeyBytes.length);

The output is :

ourPk len is 91
EC key length : 65
Community
  • 1
  • 1
Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
  • 1
    Or `/*org.bouncycastle.asn1.x509.*/SubjectPublicKeyInfo .getInstance(ourPk) .getPublicKeyData() .getOctets()`. Or to live dangerously without BC, `Arrays.copyOfRange(ourPk,26,ourPk.length)` – dave_thompson_085 Jul 26 '19 at 01:52
  • Hi @Michal Is there any possibility to get same output without using the BouncyCastle and then how can I generate public key from generated hex – Umar Ata Dec 16 '21 at 08:16