piokuc
piokuc

Reputation: 26194

Load openssl Ed25519 private key in PEM format into Python ed25519.SigningKey

I have some keys generated with openssl:

openssl genpkey -algorithm Ed25519 -out private_key.pem

and I would like to use them to generate ed25519 signatures in Python. I found the module ed25519 but I can't see a way to load the PEM file generated as above into ed25519.SigningKey.

How can I do it?

Upvotes: 0

Views: 2158

Answers (2)

AFOC
AFOC

Reputation: 844

Using the cryptography library (the linked ed25519 library looks abandoned at this point):

from cryptography.hazmat.primitives import serialization

with open('private_key.pem', 'rb') as f:
    # returns Ed25519PrivateKey
    ed_priv = serialization.load_pem_private_key(f.read(), password=None)
    
signature = ed_priv.sign(b"my authenticated message") 

For other methods see https://cryptography.io/en/latest/hazmat/primitives/asymmetric/ed25519/

Upvotes: 1

Thaddeus Albers
Thaddeus Albers

Reputation: 4192

https://pypi.org/project/ed25519/ recommends the use of https://github.com/pyca/pynacl instead.

Reference: https://pypi.org/project/ed25519/

Not Recommended For New Applications:

Use pynacl Instead For new applications, I recommend you use [pynacl (https://github.com/pyca/pynacl) instead of this repository. PyNaCl is larger and takes longer to build (it contains the complete NaCl/libsodium library, not just the ed25519 portion), but it is well-maintained by the diligent and conscientious PyCA team, whereas I’ve allowed this repository to languish. PyNaCl is also about 10-20 times faster.

To create signatures using ed25519 see https://pynacl.readthedocs.io/en/stable/signing/#example

Signer’s perspective (SigningKey)

import nacl.encoding
import nacl.signing

# Generate a new random signing key
signing_key = nacl.signing.SigningKey.generate()

# Sign a message with the signing key
signed = signing_key.sign(b"Attack at Dawn")

# Obtain the verify key for a given signing key
verify_key = signing_key.verify_key

# Serialize the verify key to send it to a third party
verify_key_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder)

Verifier’s perspective (VerifyKey)

import nacl.signing

# Create a VerifyKey object from a hex serialized public key
verify_key = nacl.signing.VerifyKey(verify_key_hex,
                                    encoder=nacl.encoding.HexEncoder)

# Check the validity of a message's signature
# The message and the signature can either be passed separately or
# concatenated together.  These are equivalent:
verify_key.verify(signed)
verify_key.verify(signed.message, signed.signature)

# Alter the signed message text
forged = signed[:-1] + bytes([int(signed[-1]) ^ 1])
# Will raise nacl.exceptions.BadSignatureError, since the signature check
# is failing
verify_key.verify(forged)

Upvotes: -3

Related Questions