ECDH上的公钥长度应为多少? [英] What should the length of public key on ECDH be?
问题描述
我正在做一个项目.现在用C ++(Botan库)实现ECDH,我试图在Android应用上实现ECDH,我将尝试将Android连接到Windows,并检查共享密钥是否相同.我的问题与Java实现有关,它生成的公钥比我预期的更长.
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.
据我所知或从这里学习
如果是256位曲线(secp256k1),则关键点为:
If it is a 256-bit curve (secp256k1), keys will be:
公共:32字节* 2 +1 = 65(未压缩) 私有:32个字节
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));
我希望输出(ourPk的len)为65,但实际输出为91.
I expect the output (len of ourPk) 65, but the actual one is 91.
推荐答案
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);
输出为:
ourPk len is 91
EC key length : 65
这篇关于ECDH上的公钥长度应为多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!