Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Jiu-hong opened this issue Apr 9, 2025 · 1 comment

Comments

@Jiu-hong
Copy link

Jiu-hong commented Apr 9, 2025

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.

@tomato42
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants