Skip to content

sk.to_pem() cannot create the same pem file from SigningKey.from_pem(fstream.read(), hashlib.sha256) #361

@Jiu-hong

Description

@Jiu-hong

The pem file

-----BEGIN EC PRIVATE KEY-----
MC4CAQEEIIX0Wk/h+GvE8RkARl4qZp+J4Ex1hjG/ZCi7mVov37teoAcGBSuBBAAK
-----END EC PRIVATE KEY-----

My code

    with open(fpath) as fstream:
        sk = SigningKey.from_pem(fstream.read(), hashlib.sha256)
        file = sk.to_pem()
        print(file)

This is the generates pem file

-----BEGIN EC PRIVATE KEY-----
MHQCAQEEIIX0Wk/h+GvE8RkARl4qZp+J4Ex1hjG/ZCi7mVov37teoAcGBSuBBAAKoUQDQgAEs+tq\n5A4hqUNrlWqoo69bczY0DPxuwDXbeuxqT/HNoi9L38c8MzsSEearJzvLBrC5d6Dt/3x16vji/xAw\nONnEKQ==
-----END EC PRIVATE KEY-----

which isn't the same as the original pem file.

Can you help advise how to generate the same file ?
Thank you.

Activity

tomato42

tomato42 commented on Apr 14, 2025

@tomato42
Member

specify that you want to use compressed point encoding:

python-ecdsa/src/ecdsa/keys.py

Lines 1173 to 1203 in 2a6593d

def to_pem(
self,
point_encoding="uncompressed",
format="ssleay",
curve_parameters_encoding=None,
):
"""
Convert the private key to the :term:`PEM` format.
See :func:`~SigningKey.from_pem` method for format description.
Only the named curve format is supported.
The public key will be included in generated string.
The PEM header will specify ``BEGIN EC PRIVATE KEY`` or
``BEGIN PRIVATE KEY``, depending on the desired format.
:param str point_encoding: format to use for encoding public point
:param str format: either ``ssleay`` (default) or ``pkcs8``
:param str curve_parameters_encoding: format of encoded curve
parameters, default depends on the curve, if the curve has
an associated OID, ``named_curve`` format will be used,
if no OID is associated with the curve, the fallback of
``explicit`` parameters will be used.
:return: PEM encoded private key
:rtype: bytes
.. warning:: The PEM is encoded to US-ASCII, it needs to be
re-encoded if the system is incompatible (e.g. uses UTF-16)
"""

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @tomato42@Jiu-hong

        Issue actions

          sk.to_pem() cannot create the same pem file from SigningKey.from_pem(fstream.read(), hashlib.sha256) · Issue #361 · tlsfuzzer/python-ecdsa