Skip to content

Change DSA encoding to SubjectPublicKeyInfo #124

@maxwolfe

Description

@maxwolfe

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions