What should the length of public key on ECDH be?

喜你入骨 提交于 2019-12-13 20:22:21

问题


I am working on a project. Implemented ECDH with C++(Botan library) now I am trying to implement ECDH on Android app and I will try to connect Android to Windows and will check if the shared secret keys are identical. My problem is related to Java implementation, it generates a longer public key than I expected.

As far as I know or learn from here,

If it is a 256-bit curve (secp256k1), keys will be:

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

// 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));

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


回答1:


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


来源:https://stackoverflow.com/questions/57209127/what-should-the-length-of-public-key-on-ecdh-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!