"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

 About This Book

 Running Python Code Online

 Python on macOS Computers

 Python on Linux Computers

 Built-in Data Types

 Variables, Operations and Expressions

 Statements - Execution Units

 Function Statement and Function Call

 Iterators and Generators

 List, Set and Dictionary Comprehensions

 Classes and Instances

 Modules and Module Files

 Packages and Package Directories

 "sys" and "os" Modules

 "pathlib" - Object-Oriented Filesystem Paths

 "pip" - Package Installer for Python

 SciPy.org - Python Libraries for Science

 pandas - Data Analysis and Manipulation

 Communicating with HTTPS Servers

 tinyec - Tiny Library for ECC

Generating EC Public-Private Keys

 "cryptography.hazmat.primitives.asymmetric.ec" - Generate EC Keys

"serialization.load_pem_private_key()" - Load EC Private Key

 "Crypto.PublicKey.ECC" - Generate EC Keys

 Anaconda - Python Environment Manager

 Jupyter Notebook and JupyterLab

 References

 Full Version in PDF/EPUB