OpenSSL in Python: Keys and Certificates

Guard The Center

Mi'kail Eli'yah

--

Configuration

hash_algorithm = "sha256"
timestamp_epoch_time_start = 0
timestamp_epoch_time_end = 10*365*24*60*60
key_length_RSA = 2048
"""
10*365*24*60*60 = 315360000
GMT: Sunday, December 30, 1979 12:00:00 AM
0
GMT: Thursday, January 1, 1970 12:00:00 AM
"""
"""
import time
# Convert Epoch time to Unix Timestamp
epoch_time = 1644018562
unix_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epoch_time))
print(f"Unix Timestamp: {unix_time}")
# Convert Unix Timestamp to Epoch time
unix_time = '2022-02-04 09:36:02'
epoch_time = int(time.mktime(time.strptime(unix_time, '%Y-%m-%d %H:%M:%S')))
print(f"Epoch Time: {epoch_time}")
"""
key_file_name = 'key_site_00.pem'
cert_file_name = 'cert_site_00.pem'
port_number = 10000
data_chunk_size_in_bytes_per_session = 1024
cert_serial_number = 11099011message = b"Hello, world!"county = "US"
state = "California"
city = "San Francisco"
name_organization = "Org U"
name_department = "Dept X"

Certificate Generation

#!pip install pyOpenSSL
from OpenSSL import crypto, SSL
import time

# Generate private key
key = crypto.PKey()
key.generate_key(crypto.TYPE_RSA, key_length_RSA)

# Create a certificate signing request for key exchange
req = crypto.X509Req()
req.get_subject().CN = "Key Exchange Certificate"
req.set_pubkey(key)
req.sign(key, hash_algorithm)
kx_csr = crypto.dump_certificate_request(crypto.FILETYPE_PEM, req)

# Create a self-signed certificate for encryption
cert_enc = crypto.X509()
cert_enc.get_subject().CN = "Encryption Certificate"
cert_enc.set_serial_number(int(time.time())) # or cert_serial_number
cert_enc.gmtime_adj_notBefore(timestamp_epoch_time_start)
cert_enc.gmtime_adj_notAfter(timestamp_epoch_time_end)
cert_enc.set_issuer(cert_enc.get_subject())
cert_enc.set_pubkey(key)
cert_enc.sign(key, hash_algorithm)
enc_cert = crypto.dump_certificate(crypto.FILETYPE_PEM, cert_enc)

# Create a self-signed certificate for message signing
cert_sign = crypto.X509()
cert_sign.get_subject().CN = "Signing Certificate"
cert_sign.set_serial_number(int(time.time())) # or cert_serial_number
cert_sign.gmtime_adj_notBefore(timestamp_epoch_time_start)
cert_sign.gmtime_adj_notAfter(timestamp_epoch_time_end)…

--

--