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 45

critical=False,

# Sign the CSR with our private key.

).sign(key, hashes.SHA256(), default_backend())

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

f.write(csr.public_bytes(serialization.Encoding.PEM))

You can use the openssl command to view the CSR, as shown here:

$ openssl req -text -in csr.pem

Certificate Request: Data: Version: 0 (0x0) Subject: C=US, ST=CA,

L=San Francisco, O=Python Cryptography, CN=8gwifi.org Subject Public

Key Info: Public Key Algorithm: rsaEncryption RSA Public Key: (2048

bit) Modulus (2048 bit): Encrypted RSA key generated with the code

$ cat /tmp/rsakey.pem -----BEGIN RSA PRIVATE KEY----- Proc-Type:

4,ENCRYPTED DEK-Info: AES-256-CBC,EA2EB61CCC7A2FFD9D83D9D103B74F69

nuslMfQNj17cAdwCKWtWhcXCtOqpk6ii0SmxcuUgJWg5iUujN4p6LYHbWkalUTvi

...... -----END RSA PRIVATE KEY----- Generated CSR in the PEM

format $ cat /tmp/csr.pem -----BEGIN CERTIFICATE REQUEST-----

MIIC0jCCAboCAQAwZTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQH

DA1TYW4gRnJhbmNpc2NvMRwwGgYDVQQKDBNQeXRob24gQ3J5cHRvZ3JhcGh5MRMw

EQYDVQQDDAo4Z3dpZmkub3JnMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC

..................... -----END CERTIFICATE REQUEST-----

Generating a Self-Signed Certificate

In cryptography and computer security, a self-signed certificate is an identity

certificate that is signed by the same entity whose identity it certifies.

Examine the following Python code. In the example, you will create a selfsigned

certificate named certificate.pem. When generating the self-signed

certificates, the issuer and the signer are the same:

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

import datetime

# Generate Key (RSA,DSA,EC)

encryptedpass = b"Ilik32Cod3"

key = rsa.generate_private_key( public_exponent=65537, key_size=2048,

backend=default_backend() )

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

Saved successfully!

Ooh no, something went wrong!