1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
"""
Key handling utilities for Diffie-Hellman keys.
"""
from asn1crypto.algos import DHParameters
from asn1crypto.core import Integer
from . import biginteger
from ..constants import Attribute
from ..exceptions import AttributeTypeInvalid
def decode_dh_domain_parameters(der):
"""
Decode DER-encoded Diffie-Hellman domain parameters.
:param bytes der: DER-encoded parameters
:rtype: dict(Attribute,*)
"""
params = DHParameters.load(der)
return {
Attribute.BASE: biginteger(params['g']),
Attribute.PRIME: biginteger(params['p']),
}
def encode_dh_domain_parameters(obj):
"""
Encode DH domain parameters into DER-encoded format.
Calculates the subprime if it isn't available.
:param DomainParameters obj: domain parameters
:rtype: bytes
"""
asn1 = DHParameters({
'g': int.from_bytes(obj[Attribute.BASE], byteorder='big'),
'p': int.from_bytes(obj[Attribute.PRIME], byteorder='big'),
})
return asn1.dump()
def encode_dh_public_key(key):
"""
Encode DH public key into RFC 3279 DER-encoded format.
:param PublicKey key: public key
:rtype: bytes
"""
asn1 = Integer(int.from_bytes(key[Attribute.VALUE], byteorder='big'))
return asn1.dump()
def decode_dh_public_key(der):
"""
Decode a DH public key from RFC 3279 DER-encoded format.
Returns a `biginteger` encoded as bytes.
:param bytes der: DER-encoded public key
:rtype: bytes
"""
asn1 = Integer.load(der)
return biginteger(asn1)
|