00001 import os
00002
00003 from cryptography import x509
00004 from cryptography.exceptions import InvalidSignature
00005 from cryptography.hazmat.backends import default_backend
00006 from cryptography.hazmat.primitives import serialization
00007 from cryptography.hazmat.primitives import hashes
00008 from cryptography.hazmat.primitives import hmac
00009 from cryptography.hazmat.primitives.asymmetric import padding
00010 from cryptography.hazmat.primitives.ciphers import Cipher
00011 from cryptography.hazmat.primitives.ciphers import algorithms
00012 from cryptography.hazmat.primitives.ciphers import modes
00013
00014
00015 def load_certificate(path):
00016 _, ext = os.path.splitext(path)
00017 with open(path, "rb") as f:
00018 if ext == ".pem":
00019 return x509.load_pem_x509_certificate(f.read(), default_backend())
00020 else:
00021 return x509.load_der_x509_certificate(f.read(), default_backend())
00022
00023
00024 def x509_from_der(data):
00025 if not data:
00026 return None
00027 return x509.load_der_x509_certificate(data, default_backend())
00028
00029
00030 def load_private_key(path):
00031 _, ext = os.path.splitext(path)
00032 with open(path, "rb") as f:
00033 if ext == ".pem":
00034 return serialization.load_pem_private_key(f.read(), password=None, backend=default_backend())
00035 else:
00036 return serialization.load_der_private_key(f.read(), password=None, backend=default_backend())
00037
00038
00039 def der_from_x509(certificate):
00040 if certificate is None:
00041 return b""
00042 return certificate.public_bytes(serialization.Encoding.DER)
00043
00044
00045 def sign_sha1(private_key, data):
00046 signer = private_key.signer(
00047 padding.PKCS1v15(),
00048 hashes.SHA1()
00049 )
00050 signer.update(data)
00051 return signer.finalize()
00052
00053
00054 def verify_sha1(certificate, data, signature):
00055 verifier = certificate.public_key().verifier(
00056 signature,
00057 padding.PKCS1v15(),
00058 hashes.SHA1())
00059 verifier.update(data)
00060 verifier.verify()
00061
00062
00063 def encrypt_basic256(public_key, data):
00064 ciphertext = public_key.encrypt(
00065 data,
00066 padding.OAEP(
00067 mgf=padding.MGF1(algorithm=hashes.SHA256()),
00068 algorithm=hashes.SHA256(),
00069 label=None)
00070 )
00071 return ciphertext
00072
00073
00074 def encrypt_rsa_oaep(public_key, data):
00075 ciphertext = public_key.encrypt(
00076 data,
00077 padding.OAEP(
00078 mgf=padding.MGF1(algorithm=hashes.SHA1()),
00079 algorithm=hashes.SHA1(),
00080 label=None)
00081 )
00082 return ciphertext
00083
00084
00085 def encrypt_rsa15(public_key, data):
00086 ciphertext = public_key.encrypt(
00087 data,
00088 padding.PKCS1v15()
00089 )
00090 return ciphertext
00091
00092
00093 def decrypt_rsa_oaep(private_key, data):
00094 text = private_key.decrypt(
00095 data,
00096 padding.OAEP(
00097 mgf=padding.MGF1(algorithm=hashes.SHA1()),
00098 algorithm=hashes.SHA1(),
00099 label=None)
00100 )
00101 return text
00102
00103
00104 def decrypt_rsa15(private_key, data):
00105 text = private_key.decrypt(
00106 data,
00107 padding.PKCS1v15()
00108 )
00109 return text
00110
00111
00112 def cipher_aes_cbc(key, init_vec):
00113 return Cipher(algorithms.AES(key), modes.CBC(init_vec), default_backend())
00114
00115
00116 def cipher_encrypt(cipher, data):
00117 encryptor = cipher.encryptor()
00118 return encryptor.update(data) + encryptor.finalize()
00119
00120
00121 def cipher_decrypt(cipher, data):
00122 decryptor = cipher.decryptor()
00123 return decryptor.update(data) + decryptor.finalize()
00124
00125
00126 def hmac_sha1(key, message):
00127 hasher = hmac.HMAC(key, hashes.SHA1(), backend=default_backend())
00128 hasher.update(message)
00129 return hasher.finalize()
00130
00131
00132 def sha1_size():
00133 return hashes.SHA1.digest_size
00134
00135
00136 def p_sha1(secret, seed, sizes=()):
00137 """
00138 Derive one or more keys from secret and seed.
00139 (See specs part 6, 6.7.5 and RFC 2246 - TLS v1.0)
00140 Lengths of keys will match sizes argument
00141 """
00142 full_size = 0
00143 for size in sizes:
00144 full_size += size
00145
00146 result = b''
00147 accum = seed
00148 while len(result) < full_size:
00149 accum = hmac_sha1(secret, accum)
00150 result += hmac_sha1(secret, accum + seed)
00151
00152 parts = []
00153 for size in sizes:
00154 parts.append(result[:size])
00155 result = result[size:]
00156 return tuple(parts)
00157
00158
00159 def x509_name_to_string(name):
00160 parts = ["{0}={1}".format(attr.oid._name, attr.value) for attr in name]
00161 return ', '.join(parts)
00162
00163
00164 def x509_to_string(cert):
00165 """
00166 Convert x509 certificate to human-readable string
00167 """
00168 if cert.subject == cert.issuer:
00169 issuer = ' (self-signed)'
00170 else:
00171 issuer = ', issuer: {0}'.format(x509_name_to_string(cert.issuer))
00172
00173 return "{0}{1}, {2} - {3}".format(x509_name_to_string(cert.subject), issuer, cert.not_valid_before, cert.not_valid_after)
00174
00175
00176 if __name__ == "__main__":
00177
00178 cert = load_certificate("../examples/server_cert.pem")
00179
00180 rsa_privkey = load_private_key("../examples/mykey.pem")
00181
00182 from IPython import embed
00183 embed()