Skip to content

Commit e64ac86

Browse files
committed
Load PRIVATE_KEY from .env to PEM-formatted
1. Deserializes the PEM-formatted PRIVATE_KEY to RSA private key object 2. Generate RSA public key object from RSA private key object 3. Serialize the public key from RSA object to PEM-formatted
1 parent d7c6678 commit e64ac86

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

tools/events-automation/.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.env
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import jwt
2+
import os
3+
import datetime
4+
5+
from dotenv import load_dotenv
6+
from cryptography.hazmat.primitives import serialization
7+
from cryptography.hazmat.backends import default_backend
8+
9+
# Automate loading environment variables in Python script, make them accessible to the project
10+
load_dotenv()
11+
12+
def get_PEM_private_key():
13+
# Load the PRIVATE_KEY in PEM-formatted string from .env to bytes
14+
pem_bytes = (os.getenv('PRIVATE_KEY', "")).encode()
15+
return pem_bytes
16+
17+
def get_RSA_private_key():
18+
# Deserializes/Loads the private key from PEM-formatted bytes to an RSA private key object, so we could perform cryptographic operations, such as signing data
19+
private_key = serialization.load_pem_private_key(
20+
get_PEM_private_key(), password=None, backend=default_backend()
21+
)
22+
return private_key
23+
24+
def get_RSA_public_key():
25+
# Get the corresponding RSA public key object from private_key
26+
public_key = get_RSA_private_key().public_key()
27+
return public_key
28+
29+
def get_PEM_public_key():
30+
# Serialize the public key from RSA object to PEM format, to verify digital signatures
31+
pem_bytes = (get_RSA_public_key().public_bytes(
32+
encoding=serialization.Encoding.PEM,
33+
format=serialization.PublicFormat.SubjectPublicKeyInfo
34+
)).decode()
35+
return pem_bytes

0 commit comments

Comments
 (0)