def fingerprint(self) -> Optional[str]: """Return SHA1 hex string as fingerprint.""" if not self._x509: return None fingerprint = self._x509.fingerprint(hashes.SHA1()) return fingerprint.hex()
class TestTOTP(object): @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA1()), skip_message="Does not support HMAC-SHA1.") @pytest.mark.parametrize("params", [i for i in vectors if i["mode"] == b"SHA1"]) def test_generate_sha1(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) assert totp.generate(time) == totp_value @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA256()), skip_message="Does not support HMAC-SHA256.") @pytest.mark.parametrize("params", [i for i in vectors if i["mode"] == b"SHA256"]) def test_generate_sha256(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA256(), 30, backend) assert totp.generate(time) == totp_value @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA512()), skip_message="Does not support HMAC-SHA512.") @pytest.mark.parametrize("params", [i for i in vectors if i["mode"] == b"SHA512"]) def test_generate_sha512(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA512(), 30, backend) assert totp.generate(time) == totp_value @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA1()), skip_message="Does not support HMAC-SHA1.") @pytest.mark.parametrize("params", [i for i in vectors if i["mode"] == b"SHA1"]) def test_verify_sha1(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) assert totp.verify(totp_value, time) is None @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA256()), skip_message="Does not support HMAC-SHA256.") @pytest.mark.parametrize("params", [i for i in vectors if i["mode"] == b"SHA256"]) def test_verify_sha256(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA256(), 30, backend) assert totp.verify(totp_value, time) is None @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA512()), skip_message="Does not support HMAC-SHA512.") @pytest.mark.parametrize("params", [i for i in vectors if i["mode"] == b"SHA512"]) def test_verify_sha512(self, backend, params): secret = params["secret"] time = int(params["time"]) totp_value = params["totp"] totp = TOTP(secret, 8, hashes.SHA512(), 30, backend) assert totp.verify(totp_value, time) is None def test_invalid_verify(self, backend): secret = b"12345678901234567890" time = 59 totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) with pytest.raises(InvalidToken): totp.verify(b"12345678", time) def test_floating_point_time_generate(self, backend): secret = b"12345678901234567890" time = 59.1 totp = TOTP(secret, 8, hashes.SHA1(), 30, backend) assert totp.generate(time) == b"94287082"
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. import pytest from cryptography.hazmat.primitives import hashes from .utils import generate_pbkdf2_test from ...utils import load_nist_vectors @pytest.mark.supported( only_if=lambda backend: backend.pbkdf2_hmac_supported(hashes.SHA1()), skip_message="Does not support SHA1 for PBKDF2HMAC", ) class TestPBKDF2HMACSHA1: test_pbkdf2_sha1 = generate_pbkdf2_test( load_nist_vectors, "KDF", ["rfc-6070-PBKDF2-SHA1.txt"], hashes.SHA1(), )
def test_prehashed_unsupported_in_signer_ctx(self, backend): private_key = DSA_KEY_1024.private_key(backend) with pytest.raises(TypeError): private_key.signer(Prehashed(hashes.SHA1()))
email = name + '@' + domain + '.' + ext csr = x509.CertificateSigningRequestBuilder().subject_name( x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Minnesota"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"Minneapolis"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"UMN"), x509.NameAttribute(NameOID.COMMON_NAME, u"testsite.com"), ])).add_extension( x509.SubjectAlternativeName([x509.RFC822Name(email)]), critical=False, ).sign(key, hashes.SHA256(), default_backend()) digest = hashes.Hash(hashes.SHA1(), backend=default_backend()) digest.update(csr.public_bytes(serialization.Encoding.PEM)) target = hexlify(digest.finalize())[-16:] csr2 = x509.CertificateSigningRequestBuilder().subject_name( x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Minnesota"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"Minneapolis"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"UMN"), x509.NameAttribute(NameOID.COMMON_NAME, u"testsite.com"), ])).add_extension( x509.BasicConstraints(True, None), critical=True, ).sign(key, hashes.SHA256(), default_backend())
def test_add_two_certs(self): cert, issuer = _cert_and_issuer() builder = ocsp.OCSPRequestBuilder() builder = builder.add_certificate(cert, issuer, hashes.SHA1()) with pytest.raises(ValueError): builder.add_certificate(cert, issuer, hashes.SHA1())
def test_dsa_verify_invalid_asn1(self, backend): public_key = DSA_KEY_1024.public_numbers.public_key(backend) verifier = public_key.verifier(b'fakesig', hashes.SHA1()) verifier.update(b'fakesig') with pytest.raises(InvalidSignature): verifier.verify()
def test_verify_reject_unicode(self, backend): h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) with pytest.raises(TypeError): h.verify("") # type: ignore[arg-type]
def parse(**kwargs): # Объявляем списки для хранения словарей и пространство OID-имён X509list = [] X509OIDsList = [] oid2name = x509.oid._OID_NAMES # Объявляем словарь-контейнер для хранения данных сертификата X509Entity = {} try: # Читаем файл и загружаем в массив байтов data = Convert.FromBase64String(kwargs['sign']) data = X509Certificates.X509Certificate(data) X509Entity['serial'] = data.GetSerialNumberString() X509Entity['sign'] = kwargs['sign'] cert = x509.load_der_x509_certificate(bytes(data.GetRawCertData()), default_backend()) data = None # SubjectInfo X509Entity['Subject_SNILS'] = ''.join( [getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'SNILS']) X509Entity['Subject_orgRequisites'] = ''.join([getvalue(x.value).replace('-', '/') for x in cert.subject if ( oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'orgRequisites']) requisites = X509Entity['Subject_orgRequisites'].replace('INN=', '') \ .replace('KPP=', '').replace('OGRN=', '').replace('ИНН=', '').replace('КПП=', '') \ .replace('ОГРН=', '').replace('ОГРНИП=', '').replace('OGRNIP', '') \ .replace(' ', '').strip().split('/') X509Entity['Subject_INN'] = '' try: if len(requisites[0]) == 10 or len(requisites[0]) == 12: X509Entity['Subject_INN'] = requisites[0] except Exception as exc: X509Entity['Subject_INN'] = '' if X509Entity['Subject_INN'] == '': X509Entity['Subject_INN'] = ''.join( [getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'INN']) X509Entity['Subject_KPP'] = '' try: if len(requisites[1]) == 9: X509Entity['Subject_KPP'] = requisites[1] except Exception as exc: X509Entity['Subject_KPP'] = '' X509Entity['Subject_OGRN'] = '' try: if len(requisites[2]) == 13 or len(requisites[2]) == 15: X509Entity['Subject_OGRN'] = requisites[2] except Exception as exc: X509Entity['Subject_OGRN'] = '' if X509Entity['Subject_OGRN'] == '': X509Entity['Subject_OGRN'] = ''.join([getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'OGRN']) X509Entity['Subject_CommonName'] = ''.join([getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid( x.oid.dotted_string)) == 'commonName']) department = [] for x in cert.subject: if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'organizationalUnitName': if getvalue(x.value) not in department: department.append(getvalue(x.value)) X509Entity['Subject_Department'] = '; '.join(department) X509Entity['Subject_region'] = ''.join([getvalue(x.value) for x in cert.subject if ( oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'stateOrProvinceName']) X509Entity['Subject_city'] = ''.join([getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'localityName']) X509Entity['Subject_streetAddress'] = ''.join([getvalue(x.value) for x in cert.subject if ( oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'streetAddress']) X509Entity['Subject_email'] = ''.join([getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'emailAddress']) X509Entity['Subject_User'] = ''.join( [getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'surname']) X509Entity['Subject_User'] += ' ' + ''.join([getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid( x.oid.dotted_string)) == 'givenName']) X509Entity['Subject_UserPost'] = ''.join( [getvalue(x.value) for x in cert.subject if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'title']) X509Entity['Thumb'] = str(cert.fingerprint(hashes.SHA1()).hex().upper()) X509Entity['ValidFrom'] = cert.not_valid_before.strftime('%Y-%m-%d') X509Entity['ValidTo'] = cert.not_valid_after.strftime('%Y-%m-%d') # IssuerInfo X509Entity['Issuer_CN'] = ''.join([getvalue(x.value) for x in cert.issuer if (oid2name.get(x.oid) or get_oid(x.oid.dotted_string)) == 'commonName']) try: for x in cert.extensions.get_extension_for_oid(ExtensionOID.EXTENDED_KEY_USAGE).value: X509OID = {} X509OID['Thumb'] = X509Entity['Thumb'] X509OID['oid'] = x.dotted_string X509OID['value'] = '' X509OID['type'] = 'extensions' X509OIDsList.append(X509OID) except Exception as exc: pass for x in cert.subject.rdns: for i in x: X509OID = {} X509OID['Thumb'] = X509Entity['Thumb'] X509OID['oid'] = i.oid.dotted_string X509OID['value'] = (getvalue(i.value) or '') X509OID['type'] = 'subject' X509OIDsList.append(X509OID) for x in cert.issuer.rdns: for i in x: X509OID = {} X509OID['Thumb'] = X509Entity['Thumb'] X509OID['oid'] = i.oid.dotted_string X509OID['value'] = (getvalue(i.value) or '') X509OID['type'] = 'issuer' X509OIDsList.append(X509OID) X509list.append(X509Entity) print(X509Entity['Thumb']) except Exception as exc: pass if len(X509list) > 0: kwargs['mutex'].acquire() kwargs['certificates'].extend(X509list) kwargs['oids'].extend(X509OIDsList) kwargs['mutex'].release()
def test_unsupported_ec_keys(self): _skip_curve_unsupported(backend, ec.SECP256R1()) private_key = ec.generate_private_key(ec.SECP256R1(), backend) with pytest.raises(NotImplementedError): backend.create_x509_csr(object(), private_key, hashes.SHA1())
def test_hmac_reject_unicode(self, backend): h = hmac.HMAC(b"mykey", hashes.SHA1(), backend=backend) with pytest.raises(TypeError): h.update("\u00FC") # type: ignore[arg-type]
def test_unsupported_dsa_keys(self): private_key = DSA_KEY_2048.private_key(backend) with pytest.raises(NotImplementedError): backend.create_x509_csr(object(), private_key, hashes.SHA1())
def decryptRSA(priv_key,ciphertext): message = priv_key.decrypt(ciphertext,padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(),label=None)) return message
def _NewHMAC(self, use_sha256=False): if use_sha256: hash_algorithm = hashes.SHA256() else: hash_algorithm = hashes.SHA1() return hmac.HMAC(self.key, hash_algorithm, backend=openssl.backend)
def begin_handshake(): # Store the cert after it is received and unencrypted nonce once it received cert_received = None nonce_received = None # Create the self signed certificate for Alice # Most code taken from https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate # First create the key (using RSA) key = rsa.generate_private_key( public_exponent=random.choice(public_exponent_list), key_size=KEY_SIZE, backend=default_backend()) # Create the cert # Various details about who we are. For a self-signed certificate the # subject and issuer are always the same. subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Utah"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"Park City"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"University of Utah"), x509.NameAttribute(NameOID.COMMON_NAME, u"alice"), ]) cert = x509.CertificateBuilder( ).subject_name(subject).issuer_name(issuer).public_key(key.public_key( )).serial_number(x509.random_serial_number()).not_valid_before( # Can't use this cert until after it has been made datetime.datetime.utcnow()).not_valid_after( # Valid for 1 day datetime.datetime.utcnow() + datetime.timedelta(days=1)).add_extension( x509.SubjectAlternativeName([x509.DNSName(u"localhost")]), critical=False, # Sign this cert with our RSA key we generated (self-signed) ).sign(key, hashes.SHA256(), default_backend()) # STEP 1 send client_hello s_bob = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s_bob.connect((HOST, PORT_BOB)) # Using the record format # Taken from https://www.cisco.com/c/en/us/support/docs/security-vpn/secure-socket-layer-ssl/116181-technote-product-00.html#anc2 handshake_record_header = bytearray( [0x16, 0x03, 0x00] ) # Handshake record (0x16) and SSL v3 (ADD LENGTH AFTER KNOWING HOW LONG!) # Now create the handshake message handshake_msg = bytearray([0x01]) # Client hello handshake_msg.extend(bytearray((8).to_bytes(3, byteorder='big'))) # Length handshake_msg.extend(bytearray([0x03, 0x00])) # Version number SSL v3 handshake_msg.extend(bytearray([0x0 ])) # length of session_id (absent so 0) handshake_msg.extend( bytearray([0x0, 0x2]) ) # length of cipher suite (just 2 since we are picking ciper, and length in octets) handshake_msg.extend(bytearray( [0x00, 0xB7])) # Cipher to use TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 handshake_msg.extend(bytearray([0x0])) # No compression # Add the length to the record header length = len(handshake_msg) client_hello_header = handshake_record_header + ( (length).to_bytes(2, byteorder='big')) print('STEP 1 client hello:') print('HEADER:', client_hello_header) print('Client hello message:', handshake_msg) client_hello_msg = client_hello_header + handshake_msg print('Alice sent to Bob:', client_hello_msg) print('\n') s_bob.sendall(client_hello_msg) # STEP 2 receive server hello, cert, and request from Bob msg = s_bob.recv(MESSAGE_SIZE) print('STEP 2 server hello') print('Received from Bob:', msg) cert_received = process_handshake_msg(msg) print('\n') # STEP 3 send encrypted nonce and certificate (if requested) # Now create a ClientKeyExchange rnd = Random.new() nonce = rnd.read(32) ciphertext = cert_received.public_key().encrypt( nonce, padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)) client_key_exchange_msg = bytearray([0x10]) # Server key exchange type client_key_exchange_msg.extend( bytearray((len(ciphertext)).to_bytes(3, byteorder='big'))) # Length client_key_exchange_msg.extend(bytearray(ciphertext)) # Ciphertext length = len(client_key_exchange_msg) # If we received a certificate request, send it to the server if send_cert: # Now create the certificate to add to the record cert_len = (len(cert.public_bytes( serialization.Encoding.PEM))).to_bytes(3, byteorder='big') client_certificate_msg = bytearray([0x0b]) # Certificate type client_certificate_msg.extend(bytearray(cert_len)) # Length client_certificate_msg.extend( bytearray(cert.public_bytes( serialization.Encoding.PEM))) # Certificate length += len(client_certificate_msg) # Add the length to the record header certificate_header = handshake_record_header + ( (length).to_bytes(2, byteorder='big')) print('STEP 3 sending cert (if requested) and client key exchange:') print('HEADER:', certificate_header) print('Nonce created:', nonce) print('Encrypted nonce:', ciphertext) print('Client key exchange message:', handshake_msg) client_key_exchange_and_cert_msg = certificate_header + client_key_exchange_msg if send_cert: print('Client cert message:', client_certificate_msg) client_key_exchange_and_cert_msg += client_certificate_msg print('Alice sent to Bob:', client_key_exchange_and_cert_msg) print('\n') s_bob.sendall(client_key_exchange_and_cert_msg) # STEP 4 receive the encrypted nonce from the server and server done! encrypted_nonce_msg = s_bob.recv(MESSAGE_SIZE) print('STEP 4 receive encrypted nonce') print('Recieved from Bob:', encrypted_nonce_msg) nonce_received = process_handshake_msg(encrypted_nonce_msg, key) print('Decrypted nonce received:', nonce_received) print('\n') master_secret = bytes(a ^ b for a, b in zip(nonce, nonce_received)) print( '********************************************************************************************************************' ) print('Master secret created:', master_secret) print( '********************************************************************************************************************' ) print('\n') # Now create a MAC of all the messages that have been sent and SERVER and CLIENT appended (keyed SHA-1) digest = hashes.Hash(hashes.SHA1(), backend=default_backend()) digest.update(client_hello_msg) digest.update(msg) digest.update(client_key_exchange_and_cert_msg) digest.update(encrypted_nonce_msg) digest.update(master_secret) # Create a copy for now, so we can check CLIENT MAC digest_client = digest.copy() digest_client.update(b'CLIENT') mac_client = digest_client.finalize() # Finish digest to send by appending SERVER digest.update(b'SERVER') mac_server = digest.finalize() # STEP 5 Receive MAC from server (keyed SHA-1 with SERVER appended) mac_msg = s_bob.recv(MESSAGE_SIZE) print('STEP 5 receive MAC from server') print('Received MAC from bob:', mac_msg) process_handshake_msg(mac_msg, expected_mac=mac_server) print('\n') # STEP 6 send client MAC to server # Now create a certificate verify message mac_length = len(mac_server) client_mac_msg = bytearray([0x0f]) # Certificate verify msg client_mac_msg.extend(bytearray( (mac_length).to_bytes(3, byteorder='big'))) # Length client_mac_msg.extend(bytearray(mac_client)) # MAC value # Add the length to the record header length = len(client_mac_msg) handshake_header_total = handshake_record_header + (length).to_bytes( 2, byteorder='big') total_mac_msg = handshake_header_total + client_mac_msg print('STEP 6 send client MAC') print('HEADER:', handshake_header_total) print('MAC:', mac_client) print('Sending to Bob:', total_mac_msg) s_bob.sendall(total_mac_msg) # DONE WITH HANDSHAKE! Create keys print('\n') print('***** DONE WITH HANDSHAKE! AUTHENTICATED *****') print('\n') # Create keys... using https://cryptography.io/en/latest/hazmat/primitives/key-derivation-functions/# kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), length=160, # need to generate 4-keys (32-bytes each) salt=shared_salt, iterations=1000000, # recommended is 1mil backend=default_backend()) keys_bytes = kdf.derive(master_secret) # Create the keys associated with client keys = { 'encrypt': keys_bytes[0:32], 'decrypt': keys_bytes[32:64], 'auth_send': keys_bytes[64:96], 'auth_recv': keys_bytes[96:128], 'iv': keys_bytes[128:] } return keys, s_bob
def __init__(self): super(_RsaOaep, self).__init__( padding.OAEP(padding.MGF1(hashes.SHA1()), hashes.SHA1(), None))
from __future__ import absolute_import, division, print_function import abc import datetime from enum import Enum import six from cryptography import x509 from cryptography.hazmat.primitives import hashes from cryptography.x509.base import (_EARLIEST_UTC_TIME, _convert_to_naive_utc_time, _reject_duplicate_extension) _OIDS_TO_HASH = { "1.3.14.3.2.26": hashes.SHA1(), "2.16.840.1.101.3.4.2.4": hashes.SHA224(), "2.16.840.1.101.3.4.2.1": hashes.SHA256(), "2.16.840.1.101.3.4.2.2": hashes.SHA384(), "2.16.840.1.101.3.4.2.3": hashes.SHA512(), } class OCSPResponderEncoding(Enum): HASH = "By Hash" NAME = "By Name" class OCSPResponseStatus(Enum): SUCCESSFUL = 0 MALFORMED_REQUEST = 1
class DummyMGF(padding.MGF): _salt_length = 0 _algorithm = hashes.SHA1()
def wcdb_generate_device_salt(serialno: bytes, cpu_serial: bytes): serial = serialno + cpu_serial return pbkdf2.PBKDF2HMAC(hashes.SHA1(), 16, serial, 1, default_backend()).derive(serial)
def test_rsa_padding_supported_pss(self): assert backend.rsa_padding_supported( padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)) is True
def test_signature_not_bytes(self, backend): public_key = DSA_KEY_1024.public_numbers.public_key(backend) with pytest.raises(TypeError): public_key.verifier(1234, hashes.SHA1())
def test_rsa_padding_supported_oaep(self): assert backend.rsa_padding_supported( padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None), ) is True
def test_prehashed_unsupported_in_verifier_ctx(self, backend): public_key = DSA_KEY_1024.private_key(backend).public_key() with pytest.raises(TypeError): public_key.verifier(b"0" * 64, Prehashed(hashes.SHA1()))
def test_rsa_padding_unsupported_oaep_sha1_ripemd160(self): assert backend.rsa_padding_supported( padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.RIPEMD160(), label=None), ) is False
from __future__ import absolute_import, division, print_function import binascii import os import pytest from cryptography.hazmat.backends.interfaces import HashBackend from cryptography.hazmat.primitives import hashes from .utils import _load_all_params, generate_hash_test from ...utils import load_hash_vectors, load_nist_vectors @pytest.mark.supported( only_if=lambda backend: backend.hash_supported(hashes.SHA1()), skip_message="Does not support SHA1", ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA1(object): test_sha1 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA1"), ["SHA1LongMsg.rsp", "SHA1ShortMsg.rsp"], hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported(hashes.SHA224()), skip_message="Does not support SHA224",
send(players_list[i].socket, str(game_info).encode(), players_list[i].serverKey) print(" [!] Game info sent complete!") signature_ps = receive(players_list[i].socket, 1024, players_list[i].serverKey) # Verificar assinatura do pseudonimo certif = players_list[i].cert cert = x509.load_pem_x509_certificate(certif, default_backend()) pubKey = cert.public_key() data = bytes(players_list[i].pseudonym, 'utf-8') try: v = pubKey.verify(signature_ps, data, padding.PKCS1v15(), hashes.SHA1()) if v is None: send(players_list[i].socket, "checked".encode(), players_list[i].serverKey) clientGameSign = receive(players_list[i].socket, 16384, players_list[i].serverKey) clientGameSign = clientGameSign.split(b":__:") game_info_client = clientGameSign[0] game_hash2 = hashlib.md5(game_info_client).hexdigest() if game_hash != game_hash2: print("\n[!] Game information has been changed!")
def verifyClient(self): public_key = self.client_cert.public_key() v = public_key.verify(self.sign_client,self.clint_text , padding.PKCS1v15(), hashes.SHA1()) if v == None: return True else: return False
def get_session_server(client, address, i): client.send("s00".encode()) #random 8bytes eightByte = os.urandom(8) sess = hashlib.md5(eightByte) session = sess.hexdigest() #receive player public key tmpClientPublic = client.recv(2048) client.send("ok".encode()) #receive player public key hash clientPublicHash = client.recv(2048) tmpClientPublic = tmpClientPublic.decode('utf-8').replace("\r\n", '') tmpHashObject = hashlib.md5(tmpClientPublic.encode()) tmpHash = tmpHashObject.hexdigest() if tmpHash.encode() == clientPublicHash: print("\n[!]Sending 8 bytes to player \n") clientPublic = RSA.importKey(tmpClientPublic) #send to player session 8B + hash(8B) + hash of server public key encrypted with players public key fSend = eightByte + b":" + session.encode( ) + b":" + my_hash_public.encode() fSend = clientPublic.encrypt(fSend, None) tosend = str(fSend) + "::" + str(public.decode('utf-8')) client.send(tosend.encode()) #"sess" in client clientPH = client.recv(2048) if clientPH != "": clientPH = RSA.importKey(private).decrypt( eval(clientPH.decode('utf-8'))) print("\n[!] Matching session \n") if clientPH == eightByte: # creating 128 bits AES key print("\n[!] Creating AES key\n") key_128 = eightByte + eightByte[::-1] AESKey = AES.new(key_128, AES.MODE_CBC, IV=key_128) clientMsg = AESKey.encrypt(Padding("Ready")) #ready signal to client send(client, clientMsg, key_128) print("\n[!] Waiting for client's pseudonym\n") clientPseydonym = receive(client, 2048, key_128).decode('utf-8') send(client, "pseudonym ok".encode(), key_128) print("\n[!] Client's pseudonym\n") print(clientPseydonym) print( "\n[!] Waiting for client's information about identity\n") info = receive(client, 512, key_128).decode() if info == "noCC": send(client, "ok noCC".encode(), key_128) print("Anonymous player ") elif info == "withCC": send(client, "ok withCC".encode(), key_128) #receive signature os pseudonym and public cert of CC sign_ps = receive(client, 16384, key_128).split(b":_:") sign = sign_ps[0] cert_recvd = sign_ps[1] cert = x509.load_pem_x509_certificate( cert_recvd, default_backend()) pubKey = cert.public_key() data = bytes(clientPseydonym, 'utf-8') try: v = pubKey.verify(sign, data, padding.PKCS1v15(), hashes.SHA1()) #validating signature if v is None: print("\n[!] Valid signature. \n") send(client, "verification successful".encode(), key_128) else: print("\n[!] Invalid signature. \n") send(client, "verification failed".encode(), key_128) except: print("Verification failed") send(client, "verification failed".encode(), key_128) conn.append(client) addr.append(address) if info == "noCC": #CREATE INSTANCE OF PLAYER and add to server player list player = Player(clientPseydonym, client, tmpClientPublic, clientPublicHash, key_128, points, None) else: #CREATE INSTANCE OF PLAYER and add to server player list player = Player(clientPseydonym, client, tmpClientPublic, clientPublicHash, key_128, points, cert_recvd) #add to list of connected players players_list.append(player) print("\n[!] Player registration completed!\n") else: print("\nSession key from client does not match") else: print("\nPublic key and public hash doesn't match") client.close()
def __init__(self) -> None: super().__init__(algorithm=hashes.SHA1())
def get_fingerprint_from_cert(self): """Get the fingerprint from the certificate""" pem = open(self.cert_file, "rb").read() cert = load_pem_x509_certificate(pem, default_backend()) f = cert.fingerprint(hashes.SHA1()) return "".join("{:02x}".format(x) for x in f)