EC Cryptography Tutorials - Herong's Tutorial Examples - v1.04, by Herong Yang
"serialization.load_pem_private_key()" - Load EC Private Key
This section provides a tutorial example on how to use 'cryptography.hazmat.primitives.serialization.load_pem_private_key' method to load an EC private key in PEM format in Python scripts.
If you want to read an EC private key in PEM format, you can use the cryptography.hazmat.primitives.module. Here is a Python example script that loads an EC private key:
# cryptography-hazmat-ec-load.py
# Copyright (c) 2025, HerongYang.com, All Rights Reserved.
#
import sys
if (len(sys.argv) < 2):
print("Usage: python cryptography-hazmat-ec-load.py file")
exit()
file = sys.argv[1]
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
with open(file, "rb") as key_file:
private_key = serialization.load_pem_private_key(
key_file.read(), None
)
if isinstance(private_key, ec.EllipticCurvePrivateKey):
print("Curve name: "+private_key.curve.__class__.__name__)
print("Key size: "+str(private_key.key_size))
print(f"x: {private_key.private_numbers().public_numbers.x}")
print(f"y: {private_key.private_numbers().public_numbers.y}")
print(f"d: {private_key.private_numbers().private_value}")
else:
raise TypeError
Save the EC private key generated from the last tutorial in a file called private-key.pem and run the above script:
herong$ python3 cryptography-hazmat-ec-load.py private-key.pem Curve name: SECP256R1 Key size: 256 x: 1448598621669265146687495365245166001695582165426594859805879... y: 3746487251185212638022777276660681179127648368273248695396648... d: 2771254253714437992124662222726178157117638306617714749456695...
Table of Contents
Geometric Introduction to Elliptic Curves
Algebraic Introduction to Elliptic Curves
Abelian Group and Elliptic Curves
Discrete Logarithm Problem (DLP)
Generators and Cyclic Subgroups
tinyec - Python Library for ECC
ECDH (Elliptic Curve Diffie-Hellman) Key Exchange
ECDSA (Elliptic Curve Digital Signature Algorithm)
ECES (Elliptic Curve Encryption Scheme)
"cryptography.hazmat.primitives.asymmetric.ec" - Generate EC Keys
►"serialization.load_pem_private_key()" - Load EC Private Key