I followed this url to create a X509 certificate. And the code is:
from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
from time import gmtime, mktime
CERT_FILE = "selfsigned.crt"
KEY_FILE = "private.key"
def create_self_signed_cert():
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_<wbr>RSA, 1024)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = "UK"
cert.get_subject().ST = "London"
cert.get_subject().L = "London"
cert.get_subject().O = "Dummy Company Ltd"
cert.get_subject().OU = "Dummy Company Ltd"
cert.get_subject().CN = gethostname()
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10*<wbr>365*24*60*60)
cert.set_issuer(cert.get_<wbr>subject())
cert.set_pubkey(k)
cert.sign(k, 'sha1')
open(CERT_FILE, "wt").write(
crypto.dump_certificate(<wbr>crypto.FILETYPE_PEM, cert))
open(KEY_FILE, "wt").write(
crypto.dump_privatekey(crypto.<wbr>FILETYPE_PEM, k))
create_self_signed_cert()
But there is something wrong with the code when I run it. Could someone tell me what the meaning of <wbr>? There is a SyntaxError in cert.gmtime_adj_notAfter(10*<wbr>365*24*60*60). Thx.
A version which works with python3
from OpenSSL import crypto, SSL
def cert_gen(
emailAddress="emailAddress",
commonName="commonName",
countryName="NT",
localityName="localityName",
stateOrProvinceName="stateOrProvinceName",
organizationName="organizationName",
organizationUnitName="organizationUnitName",
serialNumber=0,
validityStartInSeconds=0,
validityEndInSeconds=10*365*24*60*60,
KEY_FILE = "private.key",
CERT_FILE="selfsigned.crt"):
#can look at generated file using openssl:
#openssl x509 -inform pem -in selfsigned.crt -noout -text
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 4096)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = countryName
cert.get_subject().ST = stateOrProvinceName
cert.get_subject().L = localityName
cert.get_subject().O = organizationName
cert.get_subject().OU = organizationUnitName
cert.get_subject().CN = commonName
cert.get_subject().emailAddress = emailAddress
cert.set_serial_number(serialNumber)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(validityEndInSeconds)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha512')
with open(CERT_FILE, "wt") as f:
f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf-8"))
with open(KEY_FILE, "wt") as f:
f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf-8"))
cert_gen()
Just remove <wbr>. So stupid I am.
This is a really useful question; as the referenced link is now dead; and this is one of the first results for searching for "python create ssl certificate".
I would add to it though, that "open(xxx, "wt").write()" is asking for problems later. By not explicitly closing the file, you may find that the garbage collector hasn't run when you try to actually use the file - resulting in a failure.
it's better to use:
with open(xxx, "w") as f:
f.write()
which will ensure that the file is closed when you're done.
Related
I'm trying to make a program that fetches someone's MAC Address from their machine, encrypts it, and then copies it to their clipboard. However, all of the encryption methods I see generate a fresh key and thus can't be deciphered without knowing the specific key that was used to encrypt the address. Is there a way to use one key to encrypt everything so all addresses can be decrypted with a single key, and a fresh key is not generated every single time?
you can try it, using Fernet Lib:
from cryptography.fernet import Fernet
# IMPORTANT: The encryption key must be binary, so the prefix 'b' before the string
# To create a random binary key, use 'generate_key' method as below:
# new_key = Fernet.generate_key()
crypto_key = b'dTlQeWw2u5oMoFPHXQ7vQHPaQUEiD71SYzWeJJAQQUk='
mac = '00:33:A4:D9:F1:E1'
fernet = Fernet(crypto_key)
enc_mac = fernet.encrypt(mac.encode())
dec_mac = fernet.decrypt(enc_mac).decode()
print(f'Fixed encryption key: {crypto_key}')
print('Original MAC string: ', mac)
print('Encrypted MAC string: ', enc_mac)
print('Decrypted MAC string: ', dec_mac)
You are describing asymmetric encryption here.
That exists and is a thing, yes. It works by by having a public key for encryption, and a private key for decryption.
There are multiple algorithms that implement that, like RSA.
RSA is supported by the python library cryptography.
A tutorial on how to use it can be found for example here:
https://nitratine.net/blog/post/asymmetric-encryption-and-decryption-in-python/
Working example
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization, hashes
# Generate keys. This only has to be done once.
# Store the keys somewhere and distribute them with the program.
def generate_keys():
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
private_key_string = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
public_key_string = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return (public_key_string, private_key_string)
# This is just for demonstration.
# In practice, don't generate them every time.
# Only generate them once and store them in a string or a file.
(public_key_string, private_key_string) = generate_keys()
# REMOTE COMPUTER
# Only use the public key here, the private key has to stay private.
public_key = serialization.load_pem_public_key(public_key_string, backend=default_backend())
mac_address = "01:23:45:67:89:AB"
mac_address_encrypted = public_key.encrypt(
mac_address.encode(),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
# LOCAL SERVER
# Use private keys here to decrypt the MAC address
private_key = serialization.load_pem_private_key(private_key_string, password=None, backend=default_backend())
mac_address_decrypted = private_key.decrypt(
mac_address_encrypted,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
).decode()
print(mac_address_decrypted)
https://ideone.com/0eEyU6
You can use Import RSA library rsa
installing :
pip install rsa
Then encrypt the byte string with the public key.
Then the encrypted string can be decrypted with the private key.
The public key can only be used for encryption and the private can only be used for decryption
for examle:
import rsa
publicKey, privateKey = rsa.newkeys(512)
message = "Salio" #this is MAC Address
encMessage = rsa.encrypt(message.encode(), publicKey)
print("encrypted: ", encMessage)
decMessage = rsa.decrypt(encMessage, privateKey).decode()
print("decrypted : ", decMessage)
import base64
import os.path
from shutil import copyfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.backends.openssl.rsa import _RSAPublicKey, _RSAPrivateKey
from asym_crypto_yaml import (decrypt_value, encrypt_value, Encrypted,
load_private_key_from_file, load_public_key_from_file,
generate_new_private_key, generate_new_public_key,
load, dump, NUMBER_OF_BYTES_PER_ENCRYPTED_CHUNK, KEY_CHUNK_SIZE,
SUPPORTED_KEY_SIZES, generate_private_key_to_file, generate_private_key_to_file, generate_public_key_to_file,
encrypt_value_and_print ,add_secret_to_yaml_file, decrypt_yaml_file_and_write_encrypted_file_to_disk,
reencrypt_secrets_and_write_to_yaml_file)
from functools import reduce
def test_add_secret_to_yaml_file():
private_key_output_filename = "/home/asy/private_key.private"
public_key_output_filename = "/home/asy/public_key.public"
private_key = generate_private_key_to_file(private_key_output_filename)
public_key = generate_public_key_to_file(private_key_output_filename, public_key_output_filename)
yaml_file_fixture = "/home/asy/saml.yml"
yaml_file_to_append_to = "/home/asy/saml_du.yml"
test_key_to_encrypt = ['FACEBOOK_APP_ID', 'FACEBOOK_APP_SECRET', 'AWS_S3_BUCKET', 'SECRET_TOKEN', 'TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET',
'TWITTER_OAUTH_TOKEN', 'TWITTER_OAUTH_TOKEN_SECRET', 'LINKEDIN_API_KEY', 'LINKEDIN_SECRET_KEY']
print ("################################ENCRYPT YAML########################################")
before_dict = None
with open(yaml_file_to_append_to, "r") as f:
before_dict = load(f)
# Encrypt data in yml file
for test_key in test_key_to_encrypt:
print ('Encrypted key is:', test_key)
print ('Encrypted value is:', before_dict[test_key])
add_secret_to_yaml_file(test_key, before_dict[test_key], public_key_output_filename, yaml_file_to_append_to)
print ("################################DECRYPT YAML########################################")
before_dict = None
with open(yaml_file_to_append_to, "r") as f:
before_dict = load(f)
# Decrypt data from yml file (Using same function)
for test_key_value in test_key_to_encrypt:
print ('key is', before_dict[test_key_value])
test_encrypted_key_value = decrypt_value(before_dict[test_key_value], private_key)
print ("decrypt data", test_encrypted_key_value)
#
def decrypt_data():
private_key_output_filename = "/home/asy/private_key.private"
public_key_output_filename = "/home/asy/public_key.public"
private_key = generate_private_key_to_file(private_key_output_filename)
public_key = generate_public_key_to_file(private_key_output_filename, public_key_output_filename)
yaml_file_to_append_to = "/home/asy/saml_du.yml"
test_key_to_encrypt = ['FACEBOOK_APP_ID', 'FACEBOOK_APP_SECRET', 'AWS_S3_BUCKET', 'SECRET_TOKEN', 'TWITTER_CONSUMER_KEY', 'TWITTER_CONSUMER_SECRET',
'TWITTER_OAUTH_TOKEN', 'TWITTER_OAUTH_TOKEN_SECRET', 'LINKEDIN_API_KEY', 'LINKEDIN_SECRET_KEY']
print ("################################DECRYPT YAML########################################")
before_dict = None
with open(yaml_file_to_append_to, "r") as f:
before_dict = load(f)
for test_key_value in test_key_to_encrypt:
print ('key is', test_key_value)
print ('value is', before_dict[test_key_value])
test_encrypted_key_value = decrypt_value(before_dict[test_key_value], private_key)
print ("decrypt data", test_encrypted_key_value)
if __name__ == "__main__":
test_add_secret_to_yaml_file()
# decrypt_data()
sample yml file:
SECRET_TOKEN: "d4e5783de1c74c7a4e3a27578df6gdgf6g786g8df7g6g87d6fgb709"
FACEBOOK_APP_ID: "35864341"
FACEBOOK_APP_SECRET: "759a1e7sd7fvyfsd473"
TWITTER_CONSUMER_KEY: "1UrRKJDF8SD7FSDF3S"
TWITTER_CONSUMER_SECRET: "5W7TE8KJJk787bnG0s"
TWITTER_OAUTH_TOKEN: "716397744-3rHXFkFkjKjkjK78PQ5"
TWITTER_OAUTH_TOKEN_SECRET: "DuDJKFSD89SDFD"
LINKEDIN_API_KEY: "2vjkJKjk4"
LINKEDIN_SECRET_KEY: "5KLSJDFsE"
GMAIL_USERNAME: "username#gmail.com"
GMAIL_PASSWORD: "PASSWORD"
AWS_ACCESS_KEY_ID: "ASDKLSDJFIA"
AWS_SECRET_ACCESS_KEY: "7ASDFJksdfjskdlf87sdfKb"
AWS_S3_BUCKET: "bucket"
development:
MAILER_HOST: "localhost:3000"
test:
MAILER_HOST: "localhost:3000"
production:
MAILER_HOST: "domain.com"
I am using "asym_crypto_yaml" yaml package to write encrypted value in .yml file.
I am not able to decrypt value from different decrypt function (decrypt_data()).
Above code only decrypt value if I execute code first time. But from second time its giving "encryption/decryption error".
My objective is to decrypt data from yml file. Little help will be appreciated.
The error is triggered because the private key used in decrypt_data() for decryption does not belong to the public key used in test_add_secret_to_yaml_file() to perform the encryption. Therefore, decryption with this private key fails.
The problem can be solved by using in decrypt_data() the private key of the key pair generated in test_add_secret_to_yaml_file(). To do this, remove the generate_private_key_to_file() and generate_public_key_to_file() calls (to generate and store a key pair) in decrypt_data(). The required private key can be loaded with load_private_key_from_file() from the file where it was stored in test_add_secret_to_yaml_file().
This ValueError: Encryption/decryption failed. Error is also thrown by the hazmat class when the data you want to encrypt is too large for the size of key that you generated. Try again by using larger key size like this.
private_key = rsa.generate_private_key(public_exponent=65537, key_size = 4096)
but keep in mind it will increase time to generate key, that is one of the biggest disadvantage of RSA encryption algorithm.
I would like to do some SSL certificate conversions using python, specifically between:
PEM <--> PFX
PEM <--> P7B
I already have a solution for PEM <--> DER.
Namely:
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.x509 import (
load_der_x509_certificate,
load_pem_x509_certificate,
)
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
cert = form.cleaned_data.get('file')
der_file = pem_to_der(cert)
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
cert = form.cleaned_data.get('file')
pem_file = der_to_pem(cert)
def pem_to_der(cert):
try:
cert_to_der = load_pem_x509_certificate(cert.read(),
default_backend())
except ValueError:
return False
return cert_to_der.public_bytes(serialization.Encoding.DER)
def der_to_pem(cert):
try:
cert_to_der = load_der_x509_certificate(cert.read(),
default_backend())
except ValueError:
return False
return cert_to_der.public_bytes(serialization.Encoding.PEM)
I do have a solution using subprocess.call, as in:
def pem_to_pfx(private_key_path, cert_path, name, passwd):
return subprocess.call("openssl pkcs12 -export -out " + "tmp/"
+ name + ".pfx" + " -password pass:" + passwd + " -inkey "
+ private_key_path + " -in " + cert_path, shell=True)
but I would prefer to avoid this.
Anybody know of a way to do these conversions using the python module cryptography?
cryptography does not currently support serialization to PKCS12/PFX or PKCS7 (although it can parse PKCS12). The project determines development priorities via user reports with concrete use cases so please file an issue!
As a stopgap you can produce PKCS12 using pyOpenSSL (which uses cryptography's bindings), but we'd prefer to build a good API that you can directly use without an additional dependency.
from OpenSSL import crypto, SSL
from socket import gethostname
from pprint import pprint
from time import gmtime, mktime
CERT_FILE = "selfsigned.crt"
KEY_FILE = "private.key"
def create_self_signed_cert():
# create a key pair
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 1024)
# create a self-signed cert
cert = crypto.X509()
cert.get_subject().C = "UK"
cert.get_subject().ST = "London"
cert.get_subject().L = "London"
cert.get_subject().O = "Dummy Company Ltd"
cert.get_subject().OU = "Dummy Company Ltd"
cert.get_subject().CN = gethostname()
cert.set_serial_number(1000)
cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(10*365*24*60*60)
cert.set_issuer(cert.get_subject())
cert.set_pubkey(k)
cert.sign(k, 'sha1')
open(CERT_FILE, "wt").write(
crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
open(KEY_FILE, "wt").write(
crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
create_self_signed_cert()
I am trying to create self certificate but its displaying error :
crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
TypeError: write() argument must be str, not bytes
please help me.
I think os.write() will be able to write the buffer returned by crypto.dump_certificate :
import os
f = os.open(CERT_FILE)
os.write(f, crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
os.close(f)
In python 3 I used decode
open(CERT_FILE, "wt").write(
crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode())
open(KEY_FILE, "wt").write(
crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode())
You may use "write binary" file open mode
by replacing the value "wt" with "wb" in open(FILE, "wt").
I am creating a certificate signed by own self-signed root authority. This is used to serve a domain hosted as a local app, which is mapped to a localhost address by /etc/hosts file. When the website is requested inside the browser my local app (written in flask) serves the app content while supplying the self-signed certificates I created for the domain. I have code written in Python's Cryptography module, and it follows these basic steps:
a) create a self-signed root authority with its own .CRT and .KEY
b) generate a CSR corresponding to my domain name after generating a separate private key for it
c) have my certificate authority sign the CSR and generate the certificate.
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.serialization import load_der_private_key
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
import datetime
import uuid
import os
import sys
import subprocess
def generate_root_CA():
"""
a) generate rootCA key
b) generate rootCA crt
"""
##generating root key
root_private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend())
##self-sign and generate the root certificate
root_public_key = root_private_key.public_key()
builder = x509.CertificateBuilder()
builder = builder.subject_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u'Test CA'),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Org'),
x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Testing unit'),
]))
builder = builder.issuer_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, u'Test CA'),
]))
builder = builder.not_valid_before(datetime.datetime.today() - datetime.timedelta(days=1))
builder = builder.not_valid_after(datetime.datetime(2019, 12, 31))
builder = builder.serial_number(int(uuid.uuid4()))
builder = builder.public_key(root_public_key)
builder = builder.add_extension(
x509.BasicConstraints(ca=True, path_length=None), critical=True,)
root_certificate = builder.sign(
private_key=root_private_key, algorithm=hashes.SHA256(),
backend=default_backend()
)
##write to disk
with open("rootCA.key", "wb") as f:
f.write(root_private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.BestAvailableEncryption(b"passphrase")
))
with open("rootCA.crt", "wb") as f:
f.write(root_certificate.public_bytes(
encoding=serialization.Encoding.PEM,
))
return root_private_key, root_certificate
def generate_key():
"""
a) generate key for the certificate being created
"""
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
return key
def generate_csr(key, domain_name):
"""
generate csr for the client certificate
"""
csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
# Provide various details about who we are.
x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"MA"),
x509.NameAttribute(NameOID.LOCALITY_NAME, u"Boston"),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Org"),
x509.NameAttribute(NameOID.COMMON_NAME, domain_name),
])).add_extension(
x509.SubjectAlternativeName([
x509.DNSName(domain_name),
x509.DNSName(u"www." + domain_name),
]),
critical=False,
# Sign the CSR with our private key.
).sign(key, hashes.SHA256(), default_backend())
# Write our CSR out to disk.
with open(domain_name + ".csr", "wb") as f:
f.write(csr.public_bytes(serialization.Encoding.PEM))
return csr
def sign_certificate_request(csr, rootkey, rootcrt, client_key, domain_name):
"""
generate the certificate based on the csr created
"""
crt = x509.CertificateBuilder().subject_name(
csr.subject
).issuer_name(
rootcrt.subject
).public_key(
csr.public_key()
).serial_number(
uuid.uuid4().int # pylint: disable=no-member
).not_valid_before(
datetime.datetime.utcnow()
).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=2)
).add_extension(
extension=x509.KeyUsage(
digital_signature=True, key_encipherment=True, content_commitment=True,
data_encipherment=False, key_agreement=False, encipher_only=False, decipher_only=False, key_cert_sign=False, crl_sign=False
),
critical=True
).add_extension(
extension=x509.BasicConstraints(ca=False, path_length=None),
critical=True
).add_extension(
extension=x509.AuthorityKeyIdentifier.from_issuer_public_key(rootkey.public_key()),
critical=False
).sign(
private_key=rootkey,
algorithm=hashes.SHA256(),
backend=default_backend()
)
with open(domain_name + ".crt", 'wb') as f:
f.write(crt.public_bytes(encoding=serialization.Encoding.PEM))
def main():
domain_name = "domain.org"
root_key, root_crt = generate_root_CA()
domain_key = generate_key()
csr = generate_csr(domain_key, domain_name)
sign_certificate_request(csr, root_key, root_crt, domain_key, domain_name)
if __name__ == "__main__":
main()
In Chrome, however I am getting the 'ERR: CERT_COMMON_NAME_INVALID' error. Reading up online, it seems that for this to go away, one needs to specify ones domain name within the Subject Alternative Field inside the CSR request, and it has to match the Common Name. That, however, is being already done inside the code (as can be seen in the generate_csr function). Additionally, I've imported the root certificate inside Chrome's root store. Could anyone help what could be the error over here?
Extensions in the CSR are not automatically copied into the certificate. You'll need to explicitly call add_extension with the SubjectAlternativeName object again in sign_certificate_request.