def __decrypt(self, salt, nonce, name, encrypted_sumoregion, encrypted_accesskeyid, encrypted_accesskey): # generate a hash from the salt we were sent to be used in decryption # self.iterations is set in __init__ kdf = PBKDF2HMAC(algorithm=hashes.SHA3_512(), length=32, salt=salt, iterations=self.iterations, backend=default_backend()) # here's our encryption key key = kdf.derive(self.password) cipher = AESGCM(key) # these are returned as byte objects sumoregion = cipher.decrypt(nonce, encrypted_sumoregion, None) accesskeyid = cipher.decrypt(nonce, encrypted_accesskeyid, None) accesskey = cipher.decrypt(nonce, encrypted_accesskey, None) # This method should always return strings, so we have to decode the results from the cypher data = { 'name': name, 'sumoregion': base64.urlsafe_b64decode(sumoregion).decode(self.system_encoding), 'accesskeyid': base64.urlsafe_b64decode(accesskeyid).decode(self.system_encoding), 'accesskey': base64.urlsafe_b64decode(accesskey).decode(self.system_encoding) } return data
def __init__(self): # The package version. self.__version__ = "0.1.0" # The default text encoding when we encode/decode between 'str' and 'bytes'. self.encoding = "utf8" # The hash algorithm used in all the procedures # The output length in Bytes can be obtained with '.digest_size'. self.hash_algorithm = hashes.SHA3_512() # The length in Bytes of the keys used to encrypt/decrypt. self.key_length = 32 # The number of iterations when using a Key Derivation Function (KDF). self.kdf_iterations = 1000000 # Function to generate salts (as raw bytes). self.salt = lambda: os.urandom(self.key_length) # The file extension used to save encrypted files. self.extension = "ctl" # In case we change the encrypted data structure in the future, we will append to the encrypted message # an encryption version. In this way we can support compatibility with data enctypted with old versions. self._enc_version = 1 # TAGS used to determine how to process the decrypted data. # bytes:raw bytes string | str:text string | file:a file | dir:a directory self._sources = {"bytes": 1, "str": 2, "file": 3, "dir": 4} # The reverse mapping of the sources. self._sources_r = {v: k for k, v in self._sources.items()}
class TestSHA3512(object): test_sha3_512 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), ["SHA3_512LongMsg.rsp", "SHA3_512ShortMsg.rsp"], hashes.SHA3_512(), )
def __encrypt(self, name, sumoregion, accesskeyid, accesskey): # generate a salt for hash creation, which we pass back to be stored alongside the encrypted data # it'll be needed for decryption later salt = os.urandom(16) # generate a hash from that salt. self.iterations is set in __init__ kdf = PBKDF2HMAC( algorithm=hashes.SHA3_512(), length=32, salt=salt, iterations=self.iterations, backend=default_backend() ) encoded_hash = base64.urlsafe_b64encode(kdf.derive(self.password)) cipher = Fernet(encoded_hash) # the cipher requires bytes, not strings, so we're doing some encoding here encrypted_sumoregion = cipher.encrypt(base64.urlsafe_b64encode(sumoregion.encode(self.system_encoding))) encrypted_accesskeyid = cipher.encrypt(base64.urlsafe_b64encode(accesskeyid.encode(self.system_encoding))) encrypted_accesskey = cipher.encrypt(base64.urlsafe_b64encode(accesskey.encode(self.system_encoding))) # we return byte objects, not strings data = {'name': name, 'encrypted_sumoregion': encrypted_sumoregion, 'encrypted_accesskeyid': encrypted_accesskeyid, 'encrypted_accesskey': encrypted_accesskey, 'salt': salt } return data
def get_algorithm(self): if self.bits == 224: return hashes.SHA3_224() elif self.bits == 256: return hashes.SHA3_256() elif self.bits == 384: return hashes.SHA3_384() elif self.bits == 521: return hashes.SHA3_512()
def create_key(password): salt = get_salt() kdf = PBKDF2HMAC(algorithm=hashes.SHA3_512(), length=32, salt=salt, iterations=iterations, backend=default_backend()) key = base64.urlsafe_b64encode(kdf.derive(password.encode())) return key
def save_key(self,pk1,pk): salt= os.urandom(32) pem1= pk.private_bytes( encoding=serilization.Encoding.PEM, format=serilization.PrivateFormat.TraditionalOpenssl, ecryption_algorithm= hashes.SHA3_512() length= 64 iteration=100000 ) with open(self.file0, 'wb') as pem1_out
def start_hmac(key,who): global CSUIT alg,modo,dige = CSUIT[who].split("_") if(dige == "SHA256"): digest = hashes.SHA256() elif(dige == "SHA512"): digest = hashes.SHA512() elif(dige == "SHA3256"): digest = hashes.SHA3_256() elif(dige == "SHA3512"): digest = hashes.SHA3_512() return hmac.HMAC(key, digest, backend=default_backend())
def get_hashing_algorithm(): print('Odaberite algoritam za RSA enkripciju: a) SHA-2\tb) SHA-3') alg = input('[a/b]? : ') if alg == 'a': print('Odaberite veličinu za SHA-2: a) SHA-256\tb) SHA-512') size = input('[a/b]? : ') hashing_algorithm = hashes.SHA256() if size == 'a' else hashes.SHA512() else: print('Odaberite veličinu za SHA-3: a) SHA3-256\tb) SHA3-512') size = input('[a/b]? : ') hashing_algorithm = hashes.SHA3_256( ) if size == 'a' else hashes.SHA3_512() return hashing_algorithm
async def SHA3_512(message): message = message.encode() kdf = PBKDF2HMAC( algorithm=hashes.SHA3_512(), length=hashLen, salt= b'\xe7\xde\xc1\xf0\x81\x99\xde}\xa4\xb50u;&\x06\xe7\xa4\xbfn\xbc', iterations=hashIter, backend=default_backend()) output = base64.urlsafe_b64encode(kdf.derive(message)) return (output)
def myDecryptHMAC(k, hKey, IV, ct, t): backend = default_backend() g = hmac.HMAC(hKey, hashes.SHA3_512(), backend=backend) g.update(ct) g.verify(t) c = Cipher(algorithms.AES(k), modes.CBC(IV), backend=backend) decrypt = c.decryptor() pt = decrypt.update(ct) + decrypt.finalize() unPad = padding.PKCS7(256).unpadder() m = unPad.update(pt) m += unPad.finalize() return m
def myEncryptHMAC(m, k, hKey): if (len(k) < 32): print('Error, key must be 32 bytes') else: IV = os.urandom(16) backend = default_backend() pad = padding.PKCS7(256).padder() p_data = pad.update(m) p_data += pad.finalize() cipher = Cipher(algorithms.AES(k), modes.CBC(IV), backend=backend) encryptor = cipher.encryptor() ct = encryptor.update(p_data) + encryptor.finalize() h = hmac.HMAC(hKey, hashes.SHA3_512(), backend=default_backend()) h.update(ct) t = h.finalize() return ct, IV, t
def __encrypt(self, name, sumoregion, accesskeyid, accesskey): # generate a salt for hash creation, which we pass back to be stored alongside the encrypted data # it'll be needed for decryption later salt = os.urandom(64) # generate a hash from that salt. self.iterations is set in __init__ kdf = PBKDF2HMAC(algorithm=hashes.SHA3_512(), length=32, salt=salt, iterations=self.iterations, backend=default_backend()) # here's our encryption key key = kdf.derive(self.password) print(sys.getsizeof(key)) # we also need to generate a random initialization vector nonce = os.urandom(12) cipher = AESGCM(key) # the cipher requires bytes, not strings, so we're doing some encoding here encrypted_sumoregion = cipher.encrypt( nonce, base64.urlsafe_b64encode(sumoregion.encode(self.system_encoding)), None) encrypted_accesskeyid = cipher.encrypt( nonce, base64.urlsafe_b64encode(accesskeyid.encode(self.system_encoding)), None) encrypted_accesskey = cipher.encrypt( nonce, base64.urlsafe_b64encode(accesskey.encode(self.system_encoding)), None) # we return byte objects, not strings data = { 'name': name, 'encrypted_sumoregion': encrypted_sumoregion, 'encrypted_accesskeyid': encrypted_accesskeyid, 'encrypted_accesskey': encrypted_accesskey, 'salt': salt, 'nonce': nonce } return data
TTP_SIGbytes = conn.recv(256) TTP_SIG = int.from_bytes(TTP_SIGbytes, 'big') print("Client: TTP_SIG = " + str(TTP_SIG)) sys.stdout.flush() # VERIFY TTP_SIG # join Server_N and Server_e to form Server_PK server_PKbytes = b"".join([server_Nbytes, server_ebytes]) #join server_S and server_PK to prepare for hasing toHash = b"".join([Sbytes, server_PKbytes]) # hash (Server_N||server_PK) to get t t = hashes.Hash(hashes.SHA3_512(), backend=default_backend()) t.update(toHash) tbytes = t.finalize() # hash tbytes to get tprimebytes tprime = hashes.Hash(hashes.SHA3_512(), backend=default_backend()) tprime.update(tbytes) tprimebytes = tprime.finalize() # concatenate t and t prime (tconcnattprime) tconcattprime = b"".join([tbytes, tprimebytes]) # turn it back into an int and mod by TTP_N ttprimeint = int.from_bytes(tconcattprime,'big') ttprimeint = ttprimeint % TTP_N
import os import sys import sympy import random import socket import secrets from math import gcd from sympy.core.numbers import mod_inverse from cryptography.hazmat.primitives import hashes, hmac, padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend HOST = "127.0.4.18" BACKEND = default_backend() digest512 = hashes.Hash(hashes.SHA3_512(), BACKEND) def safeprime(): bits = 512 maximum = 1 << bits q = secrets.randbits(bits - 1) | (1 << (bits - 2)) if (q != 2): # rule out even numbers, excluding 2 q |= 1 while True: #check if entire range has been exhausted if sympy.isprime(q): cand = (q << 1) + 1
from .utils import wycheproof_tests _DIGESTS = { "SHA-1": hashes.SHA1(), "SHA-224": hashes.SHA224(), "SHA-256": hashes.SHA256(), "SHA-384": hashes.SHA384(), "SHA-512": hashes.SHA512(), # Not supported by OpenSSL for RSA signing "SHA-512/224": None, "SHA-512/256": None, "SHA3-224": hashes.SHA3_224(), "SHA3-256": hashes.SHA3_256(), "SHA3-384": hashes.SHA3_384(), "SHA3-512": hashes.SHA3_512(), } def should_verify(backend, wycheproof): if wycheproof.valid: return True if wycheproof.acceptable: return not wycheproof.has_flag("MissingNull") return False @wycheproof_tests( "rsa_signature_test.json",
class CryptoUtils: pwd_context = CryptContext(schemes=["pbkdf2_sha256"], default="pbkdf2_sha256", pbkdf2_sha256__default_rounds=30000) algorithms = { "sha256": hashes.SHA256(), "sha224": hashes.SHA224(), "sha384": hashes.SHA256(), "sha512": hashes.SHA256(), "blake2b": hashes.BLAKE2b(64), "blake2s": hashes.BLAKE2s(32), "sha3_256": hashes.SHA3_256(), "sha3_224": hashes.SHA3_224(), "sha3_384": hashes.SHA3_384(), "sha3_512": hashes.SHA3_512() } @staticmethod def hash(password): return CryptoUtils.pwd_context.hash(password) @staticmethod def check_hash(password, hashed): return CryptoUtils.pwd_context.verify(password, hashed) @staticmethod def make_key(password, algorithm, salt): if algorithm not in CryptoUtils.algorithms: raise casket.invalid_algorithm("Algorithm %s is not supported." % (algorithm)) kdf = PBKDF2HMAC(algorithm=CryptoUtils.algorithms[algorithm], length=32, salt=salt, iterations=100000, backend=default_backend()) return base64.urlsafe_b64encode(kdf.derive(password)) @staticmethod def encrypt_password(master_pswd, plain_pswd, salt=os.urandom(16), algorithm="sha256"): key = CryptoUtils.make_key(master_pswd.encode("utf-8"), algorithm, salt) cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt(plain_pswd.encode("utf-8")) enc_pswd = base64.b64encode(salt).decode('utf-8') + cipher_text.decode( 'utf-8') return enc_pswd @staticmethod def decrypt_password(master_pswd, enc_pswd, algorithm="sha256"): salt = base64.b64decode(enc_pswd[:24].encode("utf-8")) key = CryptoUtils.make_key(master_pswd.encode("utf-8"), algorithm, salt) cipher_suite = Fernet(key) plain_text = cipher_suite.decrypt(enc_pswd[24:].encode("utf-8")) plain_text_utf8 = plain_text.decode("utf-8") return plain_text_utf8 @staticmethod def get_salt(encrypted_string): return base64.b64decode(encrypted_string[:24].encode("utf-8"))
def make_key(salt, maspas): enpas = maspas.encode() pb = pbk(algorithm=hashes.SHA3_512(), length=32, salt=salt, iterations=100000, backend=df()) return base64.urlsafe_b64encode(pb.derive(enpas))
) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA3384(object): test_sha3_384 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), [ "SHA3_384LongMsg.rsp", "SHA3_384ShortMsg.rsp", ], hashes.SHA3_384(), ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported(hashes.SHA3_512()), skip_message="Does not support SHA3_512", ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA3512(object): test_sha3_512 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), [ "SHA3_512LongMsg.rsp", "SHA3_512ShortMsg.rsp", ], hashes.SHA3_512(), )
def client_protocol( ip: str, port: int, dh: DH_params, ttp_key: RSA_key, \ username: str, pw: str, s: bytes, file_bytes: bytes ) -> \ Optional[tuple[int,int]]: """Generate the shared key and send the file, from the client side. IMPORTANT: don't forget to send 'p'! PARAMETERS ========== ip: The IP address to connect to, as a string. port: The port to connect to, as an int. dh: A DH_params object. ttp_key: An RSA_key object. username: The username to register, as a string. pw: The password, as a string. s: The salt, a bytes object 16 bytes long. Must match what the server sends back. file_bytes: The plaintext to send to the server, as a bytes object. RETURNS ======= If successful, return a tuple of the form (a, K_client), where both a and K_client are integers. If not, return None. """ try: sock = create_socket(ip, port) # if sock==None: # return None p = 'p'.encode('utf-8') send(sock, p) usernameUTF = username.encode('utf-8') send(sock, int_to_bytes(len(usernameUTF), 1)) send(sock, usernameUTF) serverNameLen1 = receive(sock, 1) serverNameLen = bytes_to_int(serverNameLen1) serverNameBytes = receive(sock, serverNameLen) serverName = serverNameBytes.decode('utf-8') servN_bytes = receive(sock, 128) serve_bytes = receive(sock, 128) servN = bytes_to_int(servN_bytes) serve = bytes_to_int(serve_bytes) server_key = RSA_key(pubkey=(servN, serve)) ttpSig_bytes = receive(sock, 128) NameNe = serverNameBytes + servN_bytes + serve_bytes ttpSign = bytes_to_int(ttpSig_bytes) digest = hashes.Hash(hashes.SHA3_512()) digest.update(NameNe) t = digest.finalize() digest = hashes.Hash(hashes.SHA3_512()) digest.update(t) tdash = digest.finalize() tFinal = bytes_to_int(t + tdash) verSig = pow(tFinal, ttp_key.d, ttp_key.N) # verify if (verSig != ttpSign): sock.close() return None N = dh.N g = dh.g a = random.randint(0, N - 1) A = calc_A(N, g, a) encA = server_key.encrypt(A) encABytes = int_to_bytes(encA, 128) sentLen = send(sock, encABytes) salt = receive(sock, 16) if salt != s: sock.close() return None B = receive(sock, 64) # calc u u = calc_u(A, B) k = calc_u(N, g) # calc x x = calc_x(s, pw) # calc v v = pow(g, x, N) # calc K_client k_client = calc_K_client(N, B, k, v, a, u, x) # calc M1 and send M1 = calc_M1(A, B, k_client) sentLen = send(sock, M1) if sentLen < len(M1): sock.close() return None M2 = receive(sock, 32) clientM2 = calc_M2(A, M1, k_client) if (M2 == clientM2): k_client_bytes = int_to_bytes(k_client, 64) aesKey = k_client_bytes[:32] hmacKey = k_client_bytes[32:] cyphertext = pad_encrypt_then_HMAC(file_bytes, aesKey, hmacKey) cypherLen = int_to_bytes(len(cyphertext), 4) send(sock, cypherLen) send(sock, cyphertext) sock.close() return (A, k_client) sock.close() return None except: return None
def ttp_sign( sock: socket.socket, ttp_key: RSA_key, \ database: Mapping[str,RSA_key] ) -> Optional[Mapping[str,RSA_key]]: """Carry out the TTP's signing procedure. IMPORTANT: 's' has already been read! PARAMETERS ========== sock: The communication socket to send/receive data over. Must be closed before the function exits. ttp_key: An RSA_key object. database: A dictionary of all signatures generated, of the form database[server_name] = key, where server_name is a string and key is an RSA_key object. RETURNS ======= If the server has not requested a signature before, and the values can be signed, return an updated version of the database. If the server has already requested a signature but with different information, return None. If the information was the same, return the database unmodified. If a socket error occurs, return None. """ assert type(sock) is socket.socket assert type(database) == dict nameLengthBytes = receive(sock, 1) nameLength = bytes_to_int(nameLengthBytes) nameBytes = receive(sock, nameLength) N_bytes = receive(sock, 128) e_bytes = receive(sock, 128) if (len(N_bytes) != 128) or (len(e_bytes) != 128): sock.close() return None hash = hashes.Hash(hashes.SHA3_512()) hash.update(nameBytes + N_bytes + e_bytes) t = hash.finalize() hash1 = hashes.Hash(hashes.SHA3_512()) hash1.update(t) tDash = hash1.finalize() tAndtdash = bytes_to_int(t + tDash) N = bytes_to_int(N_bytes) e = bytes_to_int(e_bytes) S = tAndtdash % ttp_key.N if database.get(nameBytes.decode('utf-8')) == None: key = RSA_key(pubkey=(N, e)) sig = ttp_key.sign(S) database[nameBytes.decode('utf-8')] = key newNbytes = int_to_bytes(ttp_key.N, 128) if (sig == None): sock.close() return database sentLength = send(sock, newNbytes) if sentLength != 128: sock.close() return database sig_bytes = int_to_bytes(sig, 128) sentLength = send(sock, sig_bytes) if sentLength != 256: sock.close() return database sock.close() return database else: key = database[nameBytes.decode('utf-8')] if key.N == N and key.e == e: #send(sock,N_bytes) sig = ttp_key.sign(S) newNbytes = int_to_bytes(ttp_key.N, 128) if (sig == None): sock.close() return database sentLength = send(sock, newNbytes) if sentLength != 128: sock.close() return database sig_bytes = int_to_bytes(sig, 128) sentLength = send(sock, sig_bytes) if sentLength != 256: sock.close() return database sock.close() return database sock.close() return None
def client_protocol( ip: str, port: int, dh: DH_params, ttp_key: RSA_key, \ username: str, pw: str, s: bytes, file_bytes: bytes ) -> \ Optional[tuple[int,int]]: """Generate the shared key and send the file, from the client side. IMPORTANT: don't forget to send 'p'! PARAMETERS ========== ip: The IP address to connect to, as a string. port: The port to connect to, as an int. dh: A DH_params object. ttp_key: An RSA_key object. username: The username to register, as a string. pw: The password, as a string. s: The salt, a bytes object 16 bytes long. Must match what the server sends back. file_bytes: The plaintext to send to the server, as a bytes object. RETURNS ======= If successful, return a tuple of the form (a, K_client), where both a and K_client are integers. If not, return None. """ sock = create_socket(ip, port) if sock is None: return None count = send(sock, b'p') if count != 1: return close_sock(sock) encoded_username = username.encode() encoded_username_length = len(encoded_username) count = send(sock, int_to_bytes(encoded_username_length, 1)) if count != 1: return close_sock(sock) count = send(sock, encoded_username) if count != encoded_username_length: return close_sock(sock) encoded_server_name_length_bytes = receive(sock, 1) if len(encoded_server_name_length_bytes) != 1: return close_sock(sock) encoded_server_name_length = bytes_to_int(encoded_server_name_length_bytes) server_cert = receive(sock, (encoded_server_name_length + 384)) if len(server_cert) != (encoded_server_name_length + 384): return close_sock(sock) ttp_sig_rec = server_cert[-128:] server_cert = server_cert[:-128] server_name_bytes = server_cert[:-256] server_N_bytes = server_cert[-256:-128] server_e_bytes = server_cert[-128:] server_N = bytes_to_int(server_N_bytes) server_e = bytes_to_int(server_e_bytes) server_name = server_name_bytes.decode() server_key = RSA_key(pubkey=(server_N, server_e)) digest = hashes.Hash(hashes.SHA3_512()) digest.update(server_cert) t = digest.finalize() digest = hashes.Hash(hashes.SHA3_512()) digest.update(t) t_prime = digest.finalize() S = bytes_to_int(t + t_prime) - ttp_key.N ttp_sig = ttp_key.sign(S) if ttp_sig_rec != ttp_sig: return close_sock(sock) #COPIED FROM A2 BELOW a = int.from_bytes(os.urandom(63), byteorder="big") A = calc_A(dh.N, dh.g, a) #A = int_to_bytes(A, 64) enc_A = server_key.encrypt(A) enc_A_bytes = int_to_bytes(A, 128) send(sock, enc_A_bytes) #3 print("Client: A = " + str(bytes_to_int(A))) s = receive(sock, 16) #4 print("Client: Recieved " + s.hex()) B = receive(sock, 64) #5 print("Client: Recieved " + s.hex()) u = calc_u(A, B) x = calc_x(s, pw) v = calc_A(dh.N, dh.g, x) #where is k? I already calculated it....... byteN = dh.N byteG = dh.g if type(byteN) == int: byteN = int_to_bytes(byteN, 64) if type(byteG) == int: byteG = int_to_bytes(byteG, 64) byteK = hash_bytes(byteN + byteG) k = int.from_bytes(byteK, "big") K_client = calc_K_client(N, B, k, v, a, u, x) M1 = calc_M1(A, B, K_client) send(sock, M1) #6 print("Client: M1 = " + M1.hex()) M2 = receive(sock, 32) #7 print("Client: Recieved " + M2.hex()) M2check = calc_M2(A, M1, K_client) if M2 != M2check: return close_sock(sock) K_client_bytes = int_to_bytes(K_client, 64) AES_key = K_client_bytes[:32] HMAC_key = K_client_bytes[32:] encrypted_file_bytes = pad_encrypt_then_HMAC( file_bytes, AES_key, HMAC_key ) #this might now work, might need to break up file and only pad final block encrypted_file_bytes_length = len(encrypted_file_bytes) encrypted_file_bytes_length_bytes = int_to_bytes( encrypted_file_bytes_length, 4) count = send(sock, encrypted_file_bytes_length_bytes) if count != 4: return close_sock(sock) count = send(sock, encrypted_file_bytes) if count != encrypted_file_bytes_length: return close_sock(sock) close_sock(sock) return (a, K_client)
print() print("NapicuCrypt (v1.1.0)") print("==============================") print() # klíč # file = open('key.key', 'rb') # klic_us = file.read() # file.close() heslo = input('Zadejte heslo: ') # heslo je 'Jonáš je L' heslo_en = heslo.encode() saltA = b'U\xf7+\xe9=4\xbd\xd1\xf3\xd7$\xa2\xa7H\xbe\xc5' decod = PBKDF2HMAC(algorithm=hashes.SHA3_512(), length=32, salt=saltA, iterations=10000, backend=default_backend()) klic_us = base64.urlsafe_b64encode(decod.derive(heslo_en)) print() print('\033[31m' + 'Varování!!!' + '\033[0m' + ' Tento program vám může trvalo poškodit soubory!') print('Prosím před použití napište: ' + '"napicucrypt -h"') print("=============================================================") funkce = input('Co chceš ? \033[31m' + 'zaheslovat / odheslovat' + '\033[0m : ') if funkce == ('zaheslovat'): print("******************************")
def ttp_sign( sock: socket.socket, ttp_key: RSA_key, \ database: Mapping[str,RSA_key] ) -> Optional[Mapping[str,RSA_key]]: """Carry out the TTP's signing procedure. IMPORTANT: 's' has already been read! PARAMETERS ========== sock: The communication socket to send/receive data over. Must be closed before the function exits. ttp_key: An RSA_key object. database: A dictionary of all signatures generated, of the form database[server_name] = key, where server_name is a string and key is an RSA_key object. RETURNS ======= If the server has not requested a signature before, and the values can be signed, return an updated version of the database. If the server has already requested a signature but with different information, return None. If the information was the same, return the database unmodified. If a socket error occurs, return None. """ assert type(sock) is socket.socket assert type(database) == dict length_name = receive(sock, 1) if len(length_name) != 1: return close_sock(sock) length_name = bytes_to_int(length_name) varprint(length_name, 'length_name', "TTP") name = receive(sock, length_name) if len(name) != length_name: return close_sock(sock) varprint(name.decode("utf-8"), 'name', "name") serv_N = receive(sock, 128) if len(serv_N) != 128: return close_sock(sock) serv_e = receive(sock, 128) if len(serv_e) != 128: return close_sock(sock) serv_key = (bytes_to_int(serv_N), bytes_to_int(serv_e)) varprint(serv_key, 'serv_key', "TTP") db_index = name.decode("utf-8") if db_index in database: db_serv_key = database[db_index] if db_serv_key.N != serv_key[0] or db_serv_key.e != serv_key[1]: print("Server name exists with different information. Quitting...") return close_sock(sock) digest = hashes.Hash(hashes.SHA3_512()) digest.update(name + serv_N + serv_e) t = digest.finalize() digest = hashes.Hash(hashes.SHA3_512()) digest.update(t) t_prime = digest.finalize() S = bytes_to_int(t + t_prime) - ttp_key.N ttp_sig = ttp_key.sign(S) N_bytes = int_to_bytes(ttp_key.N, byte_length_of_int(ttp_key.N)) count = send(sock, N_bytes) if count != len(N_bytes): return close_sock(sock) ttp_sig_bytes = int_to_bytes(ttp_sig, byte_length_of_int(ttp_sig)) count = send(sock, ttp_sig_bytes) if count != len(ttp_sig_bytes): return close_sock(sock) if db_index not in database: database[db_index] = RSA_key(pubkey=serv_key) close_sock(sock) return database
self.file1 = file1 def save_key(self,pk1,pk): salt= os.urandom(32) pem1= pk.private_bytes( encoding=serilization.Encoding.PEM, format=serilization.PrivateFormat.TraditionalOpenssl, ecryption_algorithm= hashes.SHA3_512() length= 64 iteration=100000 ) with open(self.file0, 'wb') as pem1_out pemt_out.write(pem1) pem0= pk1.private_bytes( encoding=serilization.Encoding.PEM, format=serilization.PrivateFormat.TraditionalOpenssl, ecryption_algorithm= hashes.SHA3_512() length= 64 iteration=100000 ) with open(self.file0, 'wb') as pem0_out pemt_out.write(pem) def gen_key(self): private_key = rsa.generate_private_key( public_exponent=65537, key_size= 4096, backend=default_backend() ) return private_key def load_key(self): with open(self.file0, 'rb') as pem_in: premlines = pem_in.read() private_key = load_pem_private_key(pemlines,none,default_backend())
from asn1crypto.algos import SignedDigestAlgorithm from cryptography.hazmat.primitives import hashes _STR_TO_HASH_ALGO = { 'md5' : hashes.MD5(), 'sha1' : hashes.SHA1(), 'sha224' : hashes.SHA224(), 'sha256' : hashes.SHA256(), 'sha384' : hashes.SHA384(), 'sha512' : hashes.SHA512(), 'sha512_224' : hashes.SHA512_224(), 'sha512_256' : hashes.SHA512_256(), 'sha3_224' : hashes.SHA3_224(), 'sha3_256' : hashes.SHA3_256(), 'sha3_384' : hashes.SHA3_384(), 'sha3_512' : hashes.SHA3_512(), } def get_hash_algo_by_name(hash_algo: str): hash_algo = hash_algo.lower() if hash_algo not in _STR_TO_HASH_ALGO: raise ValueError("Invalid hash algorithm '{}'".format(hash_algo)) return _STR_TO_HASH_ALGO[hash_algo] def update_sig_algo_if_no_hash_algo(sig_algo: SignedDigestAlgorithm, hash_algo: str): n_sig_algo = sig_algo['algorithm'].native if n_sig_algo == 'rsassa_pkcs1v15' or n_sig_algo == 'ecdsa' or n_sig_algo == 'dsa': if n_sig_algo == 'rsassa_pkcs1v15': n_sig_algo = 'rsa' if hash_algo == 'md5':
def readMail(secType, sender, receiver, secureInputFile, plainOutputFile, digestAlg, encryAlg, rsaKeySize): senderPrivateKeyFile = sender + '_priv_' + str(rsaKeySize) + '.txt' senderPublicKeyFile = sender + '_pub_' + str(rsaKeySize) + '.txt' receiverPrivateKeyFile = receiver + '_priv_' + str(rsaKeySize) + '.txt' receiverPublicKeyFile = receiver + '_pub_' + str(rsaKeySize) + '.txt' with open(senderPrivateKeyFile, "rb") as key_file: senderPrivateKey = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) # print(senderPrivateKey) with open(senderPublicKeyFile, "rb") as key_file: senderPublicKey = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) with open(receiverPrivateKeyFile, "rb") as key_file: receiverPrivateKey = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) with open(receiverPublicKeyFile, "rb") as key_file: receiverPublicKey = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) if secType == 'CONF': print("Decrypting message") with open(secureInputFile, 'r') as file: lines = file.readlines() encryptedb64SessionKey = lines[0] encryptedb64Message = lines[1] b64iv = lines[2] #print(encryptedKey) #print(encryptedMessage) #Decode from base 64 to bytes encryptedSessionKey = base64.b64decode(encryptedb64SessionKey) encryptedMessage = base64.b64decode(encryptedb64Message) iv = base64.b64decode(b64iv) sessionKey = receiverPrivateKey.decrypt( encryptedSessionKey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) if encryAlg == 'aes-256-cbc': cipher = Cipher(algorithms.AES(sessionKey), modes.CBC(iv)) decryptor = cipher.decryptor() decryptedMessage = decryptor.update( encryptedMessage) + decryptor.finalize() unpadder = sym_padding.PKCS7(128).unpadder() data = unpadder.update(decryptedMessage) data = data + unpadder.finalize() #print(decryptedMessage) #print(data) elif encryAlg == 'des-ede3-cbc': #print("DES") #sessionKey = os.urandom(24) #v = os.urandom(8) cipher = Cipher(algorithms.TripleDES(sessionKey), modes.CBC(iv)) decryptor = cipher.decryptor() decryptedMessage = decryptor.update( encryptedMessage) + decryptor.finalize() unpadder = sym_padding.PKCS7(64).unpadder() data = unpadder.update(decryptedMessage) data = data + unpadder.finalize() #print(decryptedMessage) #print(data) with open(plainOutputFile, 'wb') as f: f.write(data) # f.newLine() #f.write('\n'.encode()) #f.write(base64.b64encode(encryptedMessage)) print("Decryption successful") elif secType == 'AUIN': print("Verifying digital signature of the message") with open(secureInputFile, 'r') as file: lines = file.readlines() b64Signature = lines[0] b64Message = lines[1] #b64iv=lines[2] signature = base64.b64decode(b64Signature) #message = base64.b64decode(b64Message) if digestAlg == 'sha512': senderPublicKey.verify( signature, b64Message.encode(), padding.PSS(mgf=padding.MGF1(hashes.SHA512()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA512()) elif digestAlg == 'sha3-512': senderPublicKey.verify( signature, b64Message.encode(), padding.PSS(mgf=padding.MGF1(hashes.SHA3_512()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA3_512()) with open(plainOutputFile, 'wb') as f: f.write(b"Digital signature verified") print("Digital signature verified") elif secType == 'COAI': print("Decrypting message and verifying digital signature") with open(secureInputFile, 'r') as file: lines = file.readlines() encryptedb64SessionKey = lines[0] encryptedb64Signature = lines[1] encryptedb64Message = lines[2] b64iv = lines[3] encryptedSessionKey = base64.b64decode(encryptedb64SessionKey) encryptedSignature = base64.b64decode(encryptedb64Signature) encryptedMessage = base64.b64decode(encryptedb64Message) iv = base64.b64decode(b64iv) sessionKey = receiverPrivateKey.decrypt( encryptedSessionKey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) print("Digital signature verified") if encryAlg == 'aes-256-cbc': cipher = Cipher(algorithms.AES(sessionKey), modes.CBC(iv)) sig_decryptor = cipher.decryptor() msg_decryptor = cipher.decryptor() decryptedPaddedMessage = msg_decryptor.update( encryptedMessage) + msg_decryptor.finalize() msg_unpadder = sym_padding.PKCS7(128).unpadder() message = msg_unpadder.update(decryptedPaddedMessage) message = message + msg_unpadder.finalize() decryptedPaddedSignature = sig_decryptor.update( encryptedSignature) + sig_decryptor.finalize() sig_unpadder = sym_padding.PKCS7(128).unpadder() signature = sig_unpadder.update(decryptedPaddedSignature) signature = signature + sig_unpadder.finalize() #print(decryptedMessage) #print(data) elif encryAlg == 'des-ede3-cbc': #print("DES") #sessionKey = os.urandom(24) #v = os.urandom(8) cipher = Cipher(algorithms.TripleDES(sessionKey), modes.CBC(iv)) sig_decryptor = cipher.decryptor() msg_decryptor = cipher.decryptor() decryptedPaddedMessage = msg_decryptor.update( encryptedMessage) + msg_decryptor.finalize() msg_unpadder = sym_padding.PKCS7(64).unpadder() message = msg_unpadder.update(decryptedPaddedMessage) message = message + msg_unpadder.finalize() decryptedPaddedSignature = sig_decryptor.update( encryptedSignature) + sig_decryptor.finalize() sig_unpadder = sym_padding.PKCS7(64).unpadder() signature = sig_unpadder.update(decryptedPaddedSignature) signature = signature + sig_unpadder.finalize() #print(decryptedMessage) #print(data) if digestAlg == 'sha512': senderPublicKey.verify( signature, message, padding.PSS(mgf=padding.MGF1(hashes.SHA512()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA512()) elif digestAlg == 'sha3-512': senderPublicKey.verify( signature, message, padding.PSS(mgf=padding.MGF1(hashes.SHA3_512()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA3_512()) with open(plainOutputFile, 'wb') as f: f.write(message) print("Decryption successful")
def createMail(secType, sender, receiver, emailInputFile, emailOutputFile, digestAlg, encryAlg, rsaKeySize): senderPrivateKeyFile = sender + '_priv_' + str(rsaKeySize) + '.txt' senderPublicKeyFile = sender + '_pub_' + str(rsaKeySize) + '.txt' receiverPrivateKeyFile = receiver + '_priv_' + str(rsaKeySize) + '.txt' receiverPublicKeyFile = receiver + '_pub_' + str(rsaKeySize) + '.txt' with open(senderPrivateKeyFile, "rb") as key_file: senderPrivateKey = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) # print(senderPrivateKey) with open(senderPublicKeyFile, "rb") as key_file: senderPublicKey = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) with open(receiverPrivateKeyFile, "rb") as key_file: receiverPrivateKey = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) with open(receiverPublicKeyFile, "rb") as key_file: receiverPublicKey = serialization.load_pem_public_key( key_file.read(), backend=default_backend()) with open(emailInputFile, 'r') as file: message = file.read() if secType == 'AUIN': print("Generating message digest") if digestAlg == 'sha512': signature = senderPrivateKey.sign( message.encode(), padding.PSS(mgf=padding.MGF1(hashes.SHA512()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA512()) # digest = hashes.Hash(hashes.SHA512(), backend=default_backend()) # digest.update(message.encode()) # digest.finalize() # encrypted = senderPrivateKey.encrypt( # digest, # padding.OAEP( # mgf=padding.MGF1(algorithm=hashes.SHA256()), # algorithm=hashes.SHA256(), # label=None # ) # ) elif digestAlg == 'sha3-512': # digest = hashes.Hash(hashes.SHA3_512()) # digest.update(message.encode()) # digest.finalize() # encrypted = senderPrivateKey.encrypt( # digest, # padding.OAEP( # mgf=padding.MGF1(algorithm=hashes.SHA256()), # algorithm=hashes.SHA256(), # label=None # ) # ) signature = senderPrivateKey.sign( message.encode(), padding.PSS(mgf=padding.MGF1(hashes.SHA3_512()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA3_512()) base64_enc_digest = base64.b64encode(signature) with open(emailOutputFile, 'wb') as f: f.write(base64_enc_digest) # f.newLine() f.write('\n'.encode()) f.write(message.encode()) print("Message digest generation is successful") elif secType == 'CONF': print("Encrypting sender's message") if encryAlg == 'aes-256-cbc': # sessionKey = AESGCM.generate_key(bit_length=256) # aesgcm = AESGCM(sessionKey) # nonce = os.urandom(12) # encryptedMessage = aesgcm.encrypt(nonce, message.encode(), None) sessionKey = os.urandom(32) iv = os.urandom(16) padder = sym_padding.PKCS7(128).padder() padded_message = padder.update(message.encode()) padded_message += padder.finalize() cipher = Cipher(algorithms.AES(sessionKey), modes.CBC(iv)) encryptor = cipher.encryptor() encryptedMessage = encryptor.update( padded_message) + encryptor.finalize() elif encryAlg == 'des-ede3-cbc': #print("DES") sessionKey = os.urandom(24) iv = os.urandom(8) padder = sym_padding.PKCS7(64).padder() padded_message = padder.update(message.encode()) padded_message += padder.finalize() cipher = Cipher(algorithms.TripleDES(sessionKey), modes.CBC(iv)) encryptor = cipher.encryptor() encryptedMessage = encryptor.update( padded_message) + encryptor.finalize() encryptedSessionKey = receiverPublicKey.encrypt( sessionKey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) with open(emailOutputFile, 'wb') as f: f.write(base64.b64encode(encryptedSessionKey)) # f.newLine() f.write('\n'.encode()) f.write(base64.b64encode(encryptedMessage)) f.write('\n'.encode()) f.write(base64.b64encode(iv)) print("Encryption of sender's message successful") elif secType == 'COAI': print("Generating message digest") if digestAlg == 'sha512': signature = senderPrivateKey.sign( message.encode(), padding.PSS(mgf=padding.MGF1(hashes.SHA512()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA512()) elif digestAlg == 'sha3-512': signature = senderPrivateKey.sign( message.encode(), padding.PSS(mgf=padding.MGF1(hashes.SHA3_512()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA3_512()) print("Message digest generation is successful") print("Encrypting sender's message digest") if encryAlg == 'aes-256-cbc': sessionKey = os.urandom(32) iv = os.urandom(16) sig_padder = sym_padding.PKCS7(128).padder() msg_padder = sym_padding.PKCS7(128).padder() padded_signature = sig_padder.update(signature) padded_signature += sig_padder.finalize() padded_message = msg_padder.update(message.encode()) padded_message += msg_padder.finalize() cipher = Cipher(algorithms.AES(sessionKey), modes.CBC(iv)) sig_encryptor = cipher.encryptor() msg_encryptor = cipher.encryptor() encryptedSignature = sig_encryptor.update( padded_signature) + sig_encryptor.finalize() encryptedMessage = msg_encryptor.update( padded_message) + msg_encryptor.finalize() elif encryAlg == 'des-ede3-cbc': #print("DES") sessionKey = os.urandom(24) iv = os.urandom(8) sig_padder = sym_padding.PKCS7(64).padder() msg_padder = sym_padding.PKCS7(64).padder() padded_signature = sig_padder.update(signature) padded_signature += sig_padder.finalize() padded_message = msg_padder.update(message.encode()) padded_message += msg_padder.finalize() cipher = Cipher(algorithms.TripleDES(sessionKey), modes.CBC(iv)) sig_encryptor = cipher.encryptor() msg_encryptor = cipher.encryptor() encryptedSignature = sig_encryptor.update( padded_signature) + sig_encryptor.finalize() encryptedMessage = msg_encryptor.update( padded_message) + msg_encryptor.finalize() encryptedSessionKey = receiverPublicKey.encrypt( sessionKey, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) with open(emailOutputFile, 'wb') as f: f.write(base64.b64encode(encryptedSessionKey)) # f.newLine() f.write('\n'.encode()) f.write(base64.b64encode(encryptedSignature)) f.write('\n'.encode()) f.write(base64.b64encode(encryptedMessage)) f.write('\n'.encode()) f.write(base64.b64encode(iv)) print("Encryption of sender's message successful")
from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes, hmac from .utils import wycheproof_tests _HMAC_ALGORITHMS = { "HMACSHA1": hashes.SHA1(), "HMACSHA224": hashes.SHA224(), "HMACSHA256": hashes.SHA256(), "HMACSHA384": hashes.SHA384(), "HMACSHA512": hashes.SHA512(), "HMACSHA3-224": hashes.SHA3_224(), "HMACSHA3-256": hashes.SHA3_256(), "HMACSHA3-384": hashes.SHA3_384(), "HMACSHA3-512": hashes.SHA3_512(), } @wycheproof_tests( "hmac_sha1_test.json", "hmac_sha224_test.json", "hmac_sha256_test.json", "hmac_sha384_test.json", "hmac_sha3_224_test.json", "hmac_sha3_256_test.json", "hmac_sha3_384_test.json", "hmac_sha3_512_test.json", "hmac_sha512_test.json", ) def test_hmac(backend, wycheproof):
b1_h5_hval = hexlify(b1_h5_hval) b1_h5_hval = int(b1_h5_hval, 16) b1_h5_hval = int(b1_h5_hval) % (len(bit_vect2)) bit_vect2[b1_h5_hval] = 1 b1_h6 = hashes.Hash(hashes.SHA3_384(), backend=backend) b1_h6.update(TempHash.encode()) b1_h6_hval = b1_h6.finalize() b1_h6_hval = hexlify(b1_h6_hval) b1_h6_hval = int(b1_h6_hval, 16) b1_h6_hval = int(b1_h6_hval) % (len(bit_vect2)) bit_vect2[b1_h6_hval] = 1 b1_h7 = hashes.Hash(hashes.SHA3_512(), backend=backend) b1_h7.update(TempHash.encode()) b1_h7_hval = b1_h7.finalize() b1_h7_hval = hexlify(b1_h7_hval) b1_h7_hval = int(b1_h7_hval, 16) b1_h7_hval = int(b1_h7_hval) % (len(bit_vect2)) bit_vect2[b1_h7_hval] = 1 b1_h8 = hashes.Hash(hashes.MD5(), backend=backend) b1_h8.update(TempHash.encode()) b1_h8_hval = b1_h8.finalize() b1_h8_hval = hexlify(b1_h8_hval) b1_h8_hval = int(b1_h8_hval, 16) b1_h8_hval = int(b1_h8_hval) % (len(bit_vect2))