python-pkcs11 icon indicating copy to clipboard operation
python-pkcs11 copied to clipboard

Change DSA encoding to SubjectPublicKeyInfo

Open maxwolfe opened this issue 4 years ago • 1 comments

Currently DSA public keys are encoded as integers because RFC 3279 defines DSA public key encoding in that way. Unfortunately most Python crypto libraries don't natively support this (ex. load_der_public_key).

My suggestion is to use the SubjectPublicKeyInfo ASN1 definition from RFC 5280 to encode the DSA public key in a format that is more universally implemented in other crypto libraries. The proposed change would look something like this:

from asn1crypto.keys import (
    DSAParams,
    PublicKeyAlgorithm,
    PublicKeyAlgorithmId,
    PublicKeyInfo,
)


def encode_dsa_public_key(key):
    """
    Encode DSA public key into RFC 5280 DER-encoded format.

    :param PublicKey key: public key
    :rtype: bytes
    """

    algorithm = PublicKeyAlgorithm()
    algorithm["algorithm"] = PublicKeyAlgorithmId("dsa")
    algorithm["parameters"] = DSAParams({
        'g': int.from_bytes(key[Attribute.BASE], byteorder='big'),
        'p': int.from_bytes(key[Attribute.PRIME], byteorder='big'),
        'q': int.from_bytes(key[Attribute.SUBPRIME], byteorder='big'),
    })

    asn1 = PublicKeyInfo()
    asn1["algorithm"] = algorithm
    asn1["public_key"] = Integer(int.from_bytes(key[Attribute.VALUE], byteorder='big'))

    return asn1.dump()

Let me know if you think this is the correct way to solve the problem, or if you have other ideas for how this should be handled. I'm open to creating a PR for this if you feel this solution is the correct approach.

maxwolfe avatar May 04 '21 03:05 maxwolfe

So I wouldn't replace encode_dsa_public_key and instead I would say write a generic encode_public_key that was able to generate a PublicKeyInfo for many types of keys that could be tested against load_der_public_key.

PR accepted :)

danni avatar May 04 '21 07:05 danni