简体   繁体   中英

How to get raw key data from DHPublicKey?

I followed instructions for generating private/public keys from DH group in https://cryptography.io/en/latest/hazmat/primitives/asymmetric/dh/ and I was able to get to this:

>>> p=0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF
>>> g=2
>>>
>>>
>>> pn = dh.DHParameterNumbers(p, g)
>>> params = pn.parameters(default_backend())
>>> priv = params.generate_private_key()
>>> pub = priv.public_key()
>>> pub.key_size
2048
>>> raw = pub.public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo)
>>> len(raw)
552

I expect key length 256 bytes (as pub.key_size suggests) but I can't find any way to get actual raw key data. As per docs public_bytes() accepts only SubjectPublicKeyInfo format for DHPublicKey .

How do I get actual key data with correct length?

The example on the page you link shows you a superior way to generate a shared secret, but if you must get the raw public key bytes then

y = pub.public_numbers().y    # y is a python int
pub_bytes = y.to_bytes(2048 // 8, 'big')

will get them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM