Untitled
unknown
python
3 years ago
2.4 kB
9
Indexable
""" Implementing a certificate authority for educational purpose
"""
from pprint import pprint
import hmac, hashlib
import rsa
dict_bikeys = {}
certif_repo = {}
def make_hash(content, pub_key):
pub_key_as_bytes = str.encode(str(pub_key))
hmac_obj = hmac.HMAC(pub_key_as_bytes, str.encode(content), digestmod=hashlib.sha512)
return hmac_obj.hexdigest()
def cypher_pub(message, pub_key):
return rsa.encrypt(message, pub_key)
def uncypher_priv(cyphered_message, priv_key):
return rsa.decrypt(cyphered_message, priv_key)
def create_bikeys():
""" return (pubkey, privkey)
"""
return rsa.newkeys(512)
def request_certif_signing(subject_name, subject_pub_key, ca_name):
certif_content = create_certif_content(subject_name)
certif_signature = sign_certif(certif_content, ca_name)
publish_certif(subject_name, certif_content, certif_signature)
return certif_content, certif_signature
def create_certif_content(subject_name):
return subject_name
def publish_certif(subject_name, certif_content, certif_signature):
certif_repo[subject_name] = (certif_content, certif_signature)
def sign_certif(certif_content, ca_name):
hash_certif = make_hash(certif_content, get_pub_key(ca_name))
return cypher_pub(hash_certif, get_priv_key(ca_name))
def get_pub_key(name):
pub_key, _ = dict_bikeys[name]
return pub_key
def get_priv_key(name):
_, priv_key = dict_bikeys[name]
return priv_key
def check_certificate(subject_name, subject_pub_key):
certif_content, certif_signature = certif_repo[subject_name]
hash_certif_received = uncypher_priv(certif_signature, subject_pub_key)
hash_certif_local = make_hash(certif_content, subject_pub_key)
print("Hash for received (certif_content:{}): {}".format(certif_content, hash_certif_received))
print("Hash for local (name:{}): {}".format(subject_name, hash_certif_local))
return hash_certif_received == hash_certif_local
dict_bikeys = {
"Alice": create_bikeys(),
"Bob": create_bikeys(),
"CA_1": create_bikeys(), # only one for now
# "CA_2": create_bikeys(),
# "CA_Root": create_bikeys(),
}
request_certif_signing("Alice", get_pub_key("Alice"), "CA_1")
request_certif_signing("Bob", get_pub_key("Bob"), "CA_1")
# pprint(dict_bikeys)
pprint("certif_repo")
pprint(certif_repo)
assert check_certificate("Bob", get_pub_key("Bob"))Editor is loading...