07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 2 ■ Cryptographic Protocols and Perfect Secrecy 43

authority as CA B. If Alice does not know or trust CA B , then Bob’s certificate is

useless to her; the same will hold true for Bob and his knowledge or trust of

Alice’s CA A. In order to provide a solution to this issue, you can construct a

certificate chain. If CA A certifies CA B with a certificate CA A <<CA B >> and CA B

certifies CA A ’s public key with a certificate CA B <<CA A >>, then both Alice and

Bob can check their certificates by checking a certificate chain. Assume Alice

is presented with CA B <<Bob>> and attempts to look up if there is a certificate

CA A <<CA B >>. She checks the chain: CA A <<CA B >>, CA B <<Bob>>. Certificate

chains are not limited to just the two certificates.

You can use Python to create X.509 certificates. The following code will generate

two certificates: rsakey.pem and csr.pen. The rsakey.pem is a private key

that is encrypted using the super-secret password Ilik32Cod3 and will then use

the private key to generate a public key. We then generate a certificate signing

request (CSR) using a number of custom attributes. Feel free to change these

up as they will not affect the example.

from cryptography.hazmat.backends import default_backend

from cryptography.hazmat.primitives import serialization

from cryptography.hazmat.primitives.asymmetric import rsa

from cryptography import x509

from cryptography.x509.oid import NameOID

from cryptography.hazmat.primitives import hashes

#Generate Key (RSA,DSA,EC)

encryptedpass = b"Ilik32Cod3"

key = rsa.generate_private_key(

public_exponent=65537,

key_size=2048,

backend=default_backend()

)

with open("rsakey.pem", "wb") as f:

f.write(key.private_bytes(

encoding=serialization.Encoding.PEM,

format=serialization.PrivateFormat.TraditionalOpenSSL,

encryption_algorithm=serialization.BestAvailableEncryption(encrypted

pass),

))

# Generate CSR

csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([

x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),

x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"NC"),

x509.NameAttribute(NameOID.LOCALITY_NAME, u"Raleigh"),

x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Python Cryptography"),

x509.NameAttribute(NameOID.COMMON_NAME, u"shannonbray.us"),

])).add_extension(

x509.SubjectAlternativeName([

x509.DNSName(u"shannonbray.us"),

]),

critical=False,

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!