-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecdsaKeyGen.py
More file actions
49 lines (39 loc) · 1.64 KB
/
Copy pathecdsaKeyGen.py
File metadata and controls
49 lines (39 loc) · 1.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
def generate_key_pair():
private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
public_key = private_key.public_key()
return private_key, public_key
def save_key_to_pem_file(key, file_name):
with open(file_name, 'wb') as f:
if isinstance(key, ec.EllipticCurvePrivateKey):
pem_key = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
elif isinstance(key, ec.EllipticCurvePublicKey):
pem_key = key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
else:
raise ValueError("Invalid key type")
f.write(pem_key)
def main():
private_key_file = 'private_key.pem'
public_key_file = 'public_key.pem'
# check if the key files already exist
if not os.path.exists(private_key_file):
private_key, public_key = generate_key_pair()
# Save the keys to PEM format files
save_key_to_pem_file(private_key, private_key_file)
save_key_to_pem_file(public_key, public_key_file)
print("Private key saved to private_key.pem")
print("Public key saved to public_key.pem")
else:
print("Private key file already exists, skipping key generation.")
if __name__ == "__main__":
main()