def public_numbers(self): p = self._backend._ffi.new("BIGNUM **") g = self._backend._ffi.new("BIGNUM **") q = self._backend._ffi.new("BIGNUM **") self._backend._lib.DH_get0_pqg(self._dh_cdata, p, q, g) self._backend.openssl_assert(p[0] != self._backend._ffi.NULL) self._backend.openssl_assert(g[0] != self._backend._ffi.NULL) if q[0] == self._backend._ffi.NULL: q_val = None else: q_val = self._backend._bn_to_int(q[0]) pub_key = self._backend._ffi.new("BIGNUM **") self._backend._lib.DH_get0_key(self._dh_cdata, pub_key, self._backend._ffi.NULL) self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL) return dh.DHPublicNumbers( parameter_numbers=dh.DHParameterNumbers( p=self._backend._bn_to_int(p[0]), g=self._backend._bn_to_int(g[0]), q=q_val ), y=self._backend._bn_to_int(pub_key[0]) )
def test_dh_serialization_with_q_unsupported(self, backend, vector): parameters = dh.DHParameterNumbers( int(vector["p"], 16), int(vector["g"], 16), int(vector["q"], 16) ) public = dh.DHPublicNumbers(int(vector["ystatcavs"], 16), parameters) private = dh.DHPrivateNumbers(int(vector["xstatcavs"], 16), public) private_key = private.private_key(backend) public_key = private_key.public_key() with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_SERIALIZATION): private_key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption(), ) with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_SERIALIZATION): public_key.public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo, ) with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_SERIALIZATION): parameters.parameters(backend).parameter_bytes( serialization.Encoding.PEM, serialization.ParameterFormat.PKCS3 )
def test_dh_parameternumbers(): params = dh.DHParameterNumbers( 65537, 2 ) assert params.p == 65537 assert params.g == 2 with pytest.raises(TypeError): dh.DHParameterNumbers( None, 2 ) with pytest.raises(TypeError): dh.DHParameterNumbers( 65537, None ) with pytest.raises(TypeError): dh.DHParameterNumbers( None, None ) with pytest.raises(ValueError): dh.DHParameterNumbers( 65537, 1 ) params = dh.DHParameterNumbers( 65537, 7, 1245 ) assert params.p == 65537 assert params.g == 7 assert params.q == 1245 with pytest.raises(TypeError): dh.DHParameterNumbers( 65537, 2, "hello" )
def test_symmetric_key_padding(self, backend): """ This test has specific parameters that produce a symmetric key In length 63 bytes instead 64. We make sure here that we add padding to the key. """ p = int("11859949538425015739337467917303613431031019140213666" "129025407300654026585086345323066284800963463204246390" "256567934582260424238844463330887962689642467123") g = 2 y = int("32155788395534640648739966373159697798396966919821525" "72238852825117261342483718574508213761865276905503199" "969908098203345481366464874759377454476688391248") x = int("409364065449673443397833358558926598469347813468816037" "268451847116982490733450463194921405069999008617231539" "7147035896687401350877308899732826446337707128") parameters = dh.DHParameterNumbers(p, g) public = dh.DHPublicNumbers(y, parameters) private = dh.DHPrivateNumbers(x, public) key = private.private_key(backend) symkey = key.exchange(public.public_key(backend)) assert len(symkey) == 512 // 8 assert symkey[:1] == b'\x00'
def test_generate_dh(self, backend, with_q): if with_q: vector = load_vectors_from_file( os.path.join("asymmetric", "DH", "RFC5114.txt"), load_nist_vectors)[0] p = int(vector["p"], 16) g = int(vector["g"], 16) q = int(vector["q"], 16) parameters = dh.DHParameterNumbers(p, g, q).parameters(backend) key_size = 1024 else: generator = 2 key_size = 512 parameters = dh.generate_parameters(generator, key_size, backend) assert isinstance(parameters, dh.DHParameters) key = parameters.generate_private_key() assert isinstance(key, dh.DHPrivateKey) assert key.key_size == key_size public = key.public_key() assert isinstance(public, dh.DHPublicKey) assert public.key_size == key_size assert isinstance(parameters, dh.DHParametersWithSerialization) parameter_numbers = parameters.parameter_numbers() assert isinstance(parameter_numbers, dh.DHParameterNumbers) assert parameter_numbers.p.bit_length() == key_size assert isinstance(public, dh.DHPublicKeyWithSerialization) assert isinstance(public.public_numbers(), dh.DHPublicNumbers) assert isinstance(public.parameters(), dh.DHParameters) assert isinstance(key, dh.DHPrivateKeyWithSerialization) assert isinstance(key.private_numbers(), dh.DHPrivateNumbers) assert isinstance(key.parameters(), dh.DHParameters)
def test_dh_numbers(): params = dh.DHParameterNumbers(P_1536, 2) public = dh.DHPublicNumbers(1, params) assert public.parameter_numbers is params assert public.y == 1 with pytest.raises(TypeError): dh.DHPublicNumbers(1, None) with pytest.raises(TypeError): dh.DHPublicNumbers(None, params) private = dh.DHPrivateNumbers(1, public) assert private.public_numbers is public assert private.x == 1 with pytest.raises(TypeError): dh.DHPrivateNumbers(1, None) with pytest.raises(TypeError): dh.DHPrivateNumbers(None, public)
return X25519PublicKey.from_public_bytes(data) def curve25519_to_bytes(key): if isinstance(key, X25519PublicKey): return key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) else: return key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw, serialization.NoEncryption()) _P = 179769313486231590770839156793787453197860296048756011706444423684197180216158519368947833795864925541502180565485980503646440548199239100050792877003355816639229553136239076508735759914822574862575007425302077447712589550957937778424442426617334727629299387668709205606050270810842907692932019128194467627007 _G = 2 _DH_PARAMETERS_NUMBERS = dh.DHParameterNumbers(_P, _G) _DH_PARAMETERS = _DH_PARAMETERS_NUMBERS.parameters(default_backend()) def dh_private(): return _DH_PARAMETERS.generate_private_key() def dh_public(private): return private.public_key() def dh_public_to_bytes(key): return key.public_numbers().y.to_bytes(128, 'big')
def DH_parametersNumbers(p, g): pn = dh.DHParameterNumbers(p, g) return pn.parameters(default_backend())
def process(self, msg): """ Processa uma mensagem (`bytestring`) enviada pelo CLIENTE. Retorna a mensagem a transmitir como resposta (`None` para finalizar ligação) """ self.msg_cnt += 1 if (msg[:1] == b'P'): P = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 G = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 global pn global private_key_dh_server global public_key_server_dh global derived_key pn = dh.DHParameterNumbers(P, G) parameters = pn.parameters(default_backend()) #chave privada do server private_key_dh_server = parameters.generate_private_key() #gerar chave publica public_key = private_key_dh_server.public_key() public_key_server_dh = public_key.public_numbers().y #envia chave publica dh do server res = 'P' + str(public_key_server_dh) ress = res.encode() msg = ress return msg if (msg[:1] == b'S'): #ler assinatura do cliente vsign = msg[1:257] public_key_cliente_dh = msg[257:565] clipem = msg[565:] ''' peerPublicNumbers = dh.DHPublicNumbers(public_key_cliente_dh, pn) peer_key = peerPublicNumbers.public_key(default_backend()) public_key_server_dh_peer = private_key_dh_server.exchange(peer_key) ''' #verifica Certificado verificacao = verifica(clipem) if verificacao: publica = extractPublic(clipem) #concatenar gxgy = public key dh server + public_key_dh public_key_client gxgy = str(public_key_server_dh).encode() gxy = gxgy + public_key_cliente_dh # verificar assinatura verifySignature(vsign, publica, gxy) #extrair chave privada file do servidor svrp12 = crypto.load_pkcs12( open("server.p12", 'rb').read(), "xpto2") svrpem = getCertificado(svrp12) global cert cert = svrp12 keyprivatesvr = extractPrivate(svrp12) #4º - Assina gxgy com priv_servidor signature_Server = keyprivatesvr.sign( gxy, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) ''' derived_key = HKDF( algorithm=hashes.SHA512(), length=24, salt=None, info=b'handshake data', backend=default_backend() ).derive(shared_key) ''' #5º - Envia assinaturax msgcomsign = b'm' + signature_Server + svrpem return msgcomsign if (msg[:1] == b'4'): balhelhe = b'4' print('é seguro falarmos') return balhelhe if (msg[:1] == b'C'): self.msg_cnt += 1 #dividir iv do hmac do texto da mensagem iv_client = msg[1:17] mac_client = msg[17:49] novamensagem = msg[49:] ctp = encriptarcli(keyaes, iv_client, novamensagem) print('%d : %r' % (self.id, ctp)) iv = os.urandom(16) ct = encriptarserver(keyaes, iv, ctp) # hmac da mensagem final = hmacserver(keymac, ct) msgfinal = b'4' + iv + final + ct return msgfinal if len(msgfinal) > 0 else None
def process(self, msg=b""): """ Processa uma mensagem (`bytestring`) enviada pelo SERVIDOR. Retorna a mensagem a transmitir como resposta (`None` para finalizar ligação) """ self.msg_cnt += 1 p = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 g = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 pn = dh.DHParameterNumbers(p, g) parameters = pn.parameters(default_backend()) if self.msg_cnt == 1: #envia chave publica gx serializada:gxb self.x_client_private_key = parameters.generate_private_key() self.gx = self.x_client_private_key.public_key() self.gxb = self.gx.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo) return self.gxb elif self.msg_cnt == 2: #Cliente recebe msg. Que contém gyb e Sigb self.gyb, self.sigb = msg[:-256], msg[-256:] #desserializar chave gyb para gy self.gy = serialization.load_der_public_key( data=self.gyb, backend=default_backend()) ''' :::::::::::::::::::::SIGa(gx,gy):::::::::::::::::::::::::::::::::::: ''' with open("client_private_key.txt", "rb") as file2: self.cliente_private_key_assinatura = serialization.load_der_private_key( file2.read(), password=None, backend=default_backend()) self.assinatura = self.gxb + self.gyb #gxb é a chave da alice enviada, gyb é a chave do bob recebida #vamos fazer a assinatura da chave publica serializada Diffi-Helman da Alice self.signature = self.cliente_private_key_assinatura.sign( self.assinatura, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) ''' VERIFICAR ASSINATURA ''' with open("server_public_key_assinatura.txt", "rb") as file1: self.serverPK = serialization.load_der_public_key( file1.read(), backend=default_backend()) #self.sigb é a assinatura do servidor, recebida na msg try: self.serverPK.verify( # self.sigb, self.assinatura, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) self.shared_key = self.x_client_private_key.exchange(self.gy) except (InvalidSignature): print("Oops! Não se verificou a assinatura.") self.derived_key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake data', backend=default_backend()).derive( self.shared_key) self.key1 = self.derived_key[:16] self.key2 = self.derived_key[16:] print('Input message to send (empty to finish)') new_msg = input().encode() iv = os.urandom(16) cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(new_msg) + encryptor.finalize() # mac h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend()) h.update(ct) tag = h.finalize() new_msg2 = (iv + ct) + tag + self.signature return new_msg2 if len(new_msg) > 0 else None elif self.msg_cnt >= 3: if msg: criptoIV, tag = msg[:-32], msg[-32:] iv, cripto = criptoIV[:16], criptoIV[16:] h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend()) h.update(cripto) try: h.verify(tag) cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend()) decryptor = cipher.decryptor() msg = decryptor.update(cripto) + decryptor.finalize() print('Received (%d): %r' % (self.msg_cnt, msg.decode())) except (InvalidSignature): print( "Oops! Não se verificou a integridade do criptograma." ) print('Input message to send (empty to finish)') new_msg = input().encode() iv = os.urandom(16) cipher = Cipher(algorithms.AES(self.key1), modes.CTR(iv), default_backend()) encryptor = cipher.encryptor() ct = encryptor.update(new_msg) + encryptor.finalize() # mac h = hmac.HMAC(self.key2, hashes.SHA256(), default_backend()) h.update(ct) tag = h.finalize() # como mandar tag para o outro lado?? new_msg2 = (iv + ct) + tag return new_msg2 if len(new_msg) > 0 else None
def __init__(self): prime_14 = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF pn = dh.DHParameterNumbers(prime_14, 2) parameters = pn.parameters(default_backend()) self.private_key = parameters.generate_private_key() self.public_key = self.private_key.public_key()
def tcp_echo_client(loop=None): if loop is None: loop = asyncio.get_event_loop() reader, writer = yield from asyncio.open_connection('127.0.0.1', 9999, loop=loop) data = b'P' client = Client("Cliente 1") msg = client.initHandshake() # Initiates key exchange process while len(data)>0: if msg: writer.write(msg) if msg[:1] == b'E': break data = yield from reader.read(1000) if len(data)>0 : if data[:1] == b'P': # receives parameters p and g and sends the public key ''' 1º - Receive parameters: p and g 2º - Generates Private Key: pivKey 3º - Generates Public Key pubKey 4º - Send Public Key ''' #1º g = int(data[1:2].decode()) p = int(data[2:].decode()) pn = dh.DHParameterNumbers(p, g) parameters = pn.parameters(default_backend()) #2º and 3º prvtKey = client.generatePrivateKey(parameters) pblcKey = client.generatePublicKey(prvtKey) pblcValue = client.getPublicValue(pblcKey) #4º msg = 'K' + str(pblcValue) msg = msg.encode() elif data[:1]==b'K': # receives Alice public key and initiates secure communication ''' 1º - Receives Alice's Public Key: aliceKey 2º - Create Shared Key: sharedKey 3º - Send msg of encrypted Hello (Letter S -> means secure) ''' #1º serverKey = data[1:].decode() peer_public_key = client.decomposePeerKey(int(data[1:].decode()),pn) # through Alice's public key creates object that allows you to compute the shared key #2º shared_key = client.generateSharedKey(prvtKey,peer_public_key) #3º msg = client.initmsg() nonce,msg = client.encrypt(shared_key[:32],msg) msg = b'S' + nonce + msg elif data[:1]==b'S': ''' Secure communication 1º - Decipher msg with sharedKey 2º - Encrypt with sharedKey ''' #1º msg = client.decrypt(shared_key[:32],data[14:],data[1:14]) msg = client.respond(msg) #2º nonce,msg = client.encrypt(shared_key[:32],msg) msg = b'S' + nonce +msg else: writer.write(b'E') break else: writer.write(b'E') break print('Socket closed!') writer.close()
def test_dh_parameter_numbers_equality(): assert dh.DHParameterNumbers(P_1536, 2) == dh.DHParameterNumbers(P_1536, 2) assert dh.DHParameterNumbers(P_1536, 7, 12345) == dh.DHParameterNumbers( P_1536, 7, 12345 ) assert dh.DHParameterNumbers(P_1536 + 2, 2) != dh.DHParameterNumbers( P_1536, 2 ) assert dh.DHParameterNumbers(P_1536, 2, 123) != dh.DHParameterNumbers( P_1536, 2, 456 ) assert dh.DHParameterNumbers(P_1536, 5) != dh.DHParameterNumbers(P_1536, 2) assert dh.DHParameterNumbers(P_1536, 2) != object()
print("Public Information from Alice and send to Bob : ") print("------------------------------------------------") print("\t - Generator (g) : ", Alice_parameters_num.g) print("\t - Prime number (p) : ", Alice_parameters_num.p) print("\t - Public Key (A) : \n", A_public_key.decode('utf-8')) print("Private Information from Alice : ") print("------------------------------------------------") print("\t - Private Key (a) : \n", A_private_key.decode('utf-8')) ################################################################################################# # Bob : Receive Public Information from Alice and compute public and private information (b, B) # ################################################################################################# Exchange_parameters = dh.DHParameterNumbers( Alice_parameters_num.p, Alice_parameters_num.g) # a new instance of DHBackEnd Bob_parameters = Exchange_parameters.parameters( default_backend()) # a new instance of DHParameters Bob_parameters_num = Bob_parameters.parameter_numbers( ) # a new instance of DHParametersNumbers Bob_private_key = Bob_parameters.generate_private_key( ) # a new instance of DHPrivateKey Bob_public_key = Bob_private_key.public_key() # a new instance of DHPublicKey B_public_key = Bob_public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) B_private_key = Bob_private_key.private_bytes( encoding=serialization.Encoding.PEM,
def test_dh_parameter_numbers_equality(): assert dh.DHParameterNumbers(65537, 2) == dh.DHParameterNumbers(65537, 2) assert dh.DHParameterNumbers(6, 2) != dh.DHParameterNumbers(65537, 2) assert dh.DHParameterNumbers(65537, 5) != dh.DHParameterNumbers(65537, 2) assert dh.DHParameterNumbers(65537, 2) != object()
60C980DD 98EDD3DF FFFFFFFF FFFFFFFF""") mLen = 8192 _ffdh_raw_params = { 'modp768' : modp768, 'modp1024': modp1024, 'modp1536': modp1536, 'modp2048': modp2048, 'modp3072': modp3072, 'modp4096': modp4096, 'modp6144': modp6144, 'modp8192': modp8192 } FFDH_GROUPS = {} if dh and default_backend: for name, group in _ffdh_raw_params.iteritems(): pn = dh.DHParameterNumbers(group.m, group.g) params = pn.parameters(default_backend()) FFDH_GROUPS[name] = [params, group.mLen] #from scapy.layers.tls.crypto.pkcs1 import pkcs_os2ip, pkcs_i2osp # # #class FFDHParams(object): # """ # Finite-Field Diffie-Hellman parameters. # self.priv is an integer. Its value may remain unknown. # self.pub, self.other_pub, and finally self.secret, are also integers. # Default group parameters relate to the 2048-bit group from RFC 3526. # """ # def __init__(self, g=ffdh_params[2048].g,
def process(self, msg): """ Processa uma mensagem (`bytestring`) enviada pelo CLIENTE. Retorna a mensagem a transmitir como resposta (`None` para finalizar ligação) """ self.msg_cnt += 1 if (msg[:1] == b'P'): P = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 G = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 global pn global private_key global derived_key pn = dh.DHParameterNumbers(P, G) parameters = pn.parameters(default_backend()) #chave privada do server #parameters = dh.generate_parameters(generator=2, key_size=2048, backend=default_backend()) private_key = parameters.generate_private_key() #gerar chave publica public_key = private_key.public_key() public_key_server = public_key.public_numbers().y res = 'P' + str(G) + str(P) + str(public_key_server) ress = res.encode() msg = ress return msg elif (msg[:1] == b'S'): public_key_cliente = int(msg[1:].decode()) #CALCULAR exchange peerPublicNumbers = dh.DHPublicNumbers(public_key_cliente, pn) peer_key = peerPublicNumbers.public_key(default_backend()) shared_key = private_key.exchange(peer_key) # Perform key derivation. derived_key = HKDF(algorithm=hashes.SHA512(), length=24, salt=None, info=b'handshake data', backend=default_backend()).derive(shared_key) msg2s = '1' msg2 = str(msg2s).encode() return msg2 elif (msg[:1] == b'C'): iv_cl = msg[1:17] mac_cli = msg[17:49] texto = msg[49:] cipher = Cipher(algorithms.AES(derived_key), modes.CTR(iv_cl), backend=backend) decryptor = cipher.decryptor() txt = decryptor.update(texto) #print("txt") #print(txt) #txt=txt.decode() #h=hmac.HMAC(key,hashes.SHA256(),backend=default_backend()) #h.update(texto) #h.copy().verify(mac_cli) print('%d : %r' % (self.id, txt)) #if(h.copy().verify(mac_cli)): # print("mensagem recebida correta") # print('Recebi (%d): %r' % (self.msg_cnt , msg)) #else: # printf("mensagem recebida está errada") # print('%d : %r' % (self.id,t)) #new = txt.upper().encode() iv_s = os.urandom(16) cipher = Cipher(algorithms.AES(derived_key), modes.CTR(iv_s), backend=backend) encryptor = cipher.encryptor() ct = encryptor.update(txt) + encryptor.finalize() #################################### #HMAC h = hmac.HMAC(key_mac, hashes.SHA256(), backend=default_backend()) h.update(ct) mac_serv = h.finalize() carater = b'2' new_msg = carater + iv_s + mac_serv + ct ######################## return new_msg if len(new_msg) > 0 else None
def __init__(self): self.backend = default_backend() self.pn = dh.DHParameterNumbers(P,G) self.parameters = self.pn.parameters(self.backend) self.private_key = self.parameters.generate_private_key()
# 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. from cryptography.hazmat.primitives.asymmetric import dh FFDH3072_P = dh.DHParameterNumbers( p=int( "ffffffffffffffffadf85458a2bb4a9aafdc5620273d3cf1d8b9c583ce2d3695a9e" "13641146433fbcc939dce249b3ef97d2fe363630c75d8f681b202aec4617ad3df1e" "d5d5fd65612433f51f5f066ed0856365553ded1af3b557135e7f57c935984f0c70e" "0e68b77e2a689daf3efe8721df158a136ade73530acca4f483a797abc0ab182b324" "fb61d108a94bb2c8e3fbb96adab760d7f4681d4f42a3de394df4ae56ede76372bb1" "90b07a7c8ee0a6d709e02fce1cdf7e2ecc03404cd28342f619172fe9ce98583ff8e" "4f1232eef28183c3fe3b1b4c6fad733bb5fcbc2ec22005c58ef1837d1683b2c6f34" "a26c1b2effa886b4238611fcfdcde355b3b6519035bbc34f4def99c023861b46fc9" "d6e6c9077ad91d2691f7f7ee598cb0fac186d91caefe130985139270b4130c93bc4" "37944f4fd4452e2d74dd364f2e21e71f54bff5cae82ab9c9df69ee86d2bc522363a" "0dabc521979b0deada1dbf9a42d5c4484e0abcd06bfa53ddef3c1b20ee3fd59d7c2" "5e41d2b66c62e37ffffffffffffffff", 16, ), g=2, )
from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives import hashes, hmac from cryptography.exceptions import InvalidSignature from Crypto.Cipher import AES from OpenSSL import crypto from cryptography import x509 from cryptography.hazmat.primitives.asymmetric import padding conn_cnt = 0 conn_port = 8888 max_msg_size = 9999 G = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 P = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 dh_parameters = dh.DHParameterNumbers(G, P, q=None).parameters(default_backend()) class ServerWorker(object): """ Classe que implementa a funcionalidade do SERVIDOR. """ def __init__(self, cnt, addr=None): """ Construtor da classe. """ self.id = cnt self.addr = addr self.msg_cnt = 0 self.server_private_key = dh_parameters.generate_private_key( ) #server chave privada self.server_public_key = self.server_private_key.public_key( ) #server chave pública self.client_public_key = None self.derived_key = None
algort = ['AES', 'SEED', 'CAST5', 'TripleDES', 'Camellia'] modos = ['CFB', 'CTR', 'OFB'] dg =['SHA256', 'SHA512', 'SHA3256', 'SHA3512'] #this is where we keep all user ids #dict with id: cc users = {} #this is where we keep CSUIT of each user through their id CSUIT = {} #this is where we keep a list of ciphers used in the comunication through user id ciphers = {} dKey = {} readings = {} # Generate some parameters. These can be reused. p = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF g = 2 params_numbers = dh.DHParameterNumbers(p,g) parameters = params_numbers.parameters(default_backend()) trusted_certs = {} server_cert = "" with open("localhost.crt", "rb") as file: certificate_data = file.read() server_cert = x509.load_pem_x509_certificate(certificate_data, backend=default_backend()) crl = "" with open("GTS1O1core.crl", "rb") as file: crl_data = file.read() crl = x509.load_der_x509_crl(crl_data, backend=default_backend()) all_files = os.scandir("/etc/ssl/certs")
def create_dh_public_key(public_key_num: int): pn = dh.DHParameterNumbers(p, g) public_numbers = dh.DHPublicNumbers(public_key_num, pn) public_key = public_numbers.public_key(default_backend()) return public_key
import socket import os from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, padding from cryptography.hazmat.primitives.asymmetric import dh from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.serialization import load_pem_public_key, PublicFormat, Encoding # Número primo e valor de gerador dado pelo Guião. P = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 G = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 # A criação do DH com os números fornecidos no Guião. parameters = dh.DHParameterNumbers(P, G, None).parameters(backend=default_backend()) # Chave Privada do Cliente. clientPrivateKey = parameters.generate_private_key() # Chave Pública do Cliente. clientPublicKey = clientPrivateKey.public_key() # IV iv = b'\x8f\x84\x82\xb0\xfc\x19\xe4!\xd6\xf3"\xce\x87o\xe4}' conn_port = 8888 max_msg_size = 9999 class Client:
def do_get_keys(self, request): req = request.content.read() req = json.loads(req.decode()) signature = base64.b64decode(req["signature"].encode()) data_signed = json.loads(req["data"]) client_uuid = data_signed["uuid_c"] client_cert = x509.load_pem_x509_certificate( data_signed["client_cert"].encode()) client_public_key_rsa = client_cert.public_key() #Verificar que o certificado recebido esta assinado pela CA self.CA_public_key.verify( client_cert.signature, client_cert.tbs_certificate_bytes, paddingAsymetric.PKCS1v15(), client_cert.signature_hash_algorithm, ) #Verificar a assinatura if self.users[client_uuid]["digest"] == "SHA256": client_public_key_rsa.verify( signature, req["data"].encode(), paddingAsymetric.PSS( mgf=paddingAsymetric.MGF1(hashes.SHA256()), salt_length=paddingAsymetric.PSS.MAX_LENGTH), hashes.SHA256()) elif self.users[client_uuid]["digest"] == "SHA512": client_public_key_rsa.verify( signature, req["data"].encode(), paddingAsymetric.PSS( mgf=paddingAsymetric.MGF1(hashes.SHA512()), salt_length=paddingAsymetric.PSS.MAX_LENGTH), hashes.SHA512()) else: print("Erro") sys.exit(0) self.users[client_uuid]["client_cert"] = client_cert #TODO: p = 0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF g = 2 params_numbers = dh.DHParameterNumbers(p, g) parameters = params_numbers.parameters(default_backend()) #parameters = dh.generate_parameters(generator=2, key_size=2048) parameters_pem = parameters.parameter_bytes(Encoding.PEM, ParameterFormat.PKCS3) # Generate a private key DH self.server_private_key = parameters.generate_private_key() # Generate a public DH server_public_key_pem = self.server_private_key.public_key( ).public_bytes(encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) data = { "parameters": parameters_pem.decode('latin'), "server_pub_key": server_public_key_pem.decode('latin') } data = json.dumps(data) if self.users[client_uuid]["digest"] == "SHA256": signature = self.server_cert_private_key.sign( data.encode(), paddingAsymetric.PSS( mgf=paddingAsymetric.MGF1(hashes.SHA256()), salt_length=paddingAsymetric.PSS.MAX_LENGTH), hashes.SHA256()) elif self.users[client_uuid]["digest"] == "SHA512": signature = self.server_cert_private_key.sign( data.encode(), paddingAsymetric.PSS( mgf=paddingAsymetric.MGF1(hashes.SHA512()), salt_length=paddingAsymetric.PSS.MAX_LENGTH), hashes.SHA512()) else: print("Erro") sys.exit(0) payload = { "signature": base64.b64encode(signature).decode('latin'), "message": data } request.setResponseCode(200) request.responseHeaders.addRawHeader(b"content-type", b"application/json") return json.dumps(payload).encode('latin')
from binascii import hexlify, unhexlify from cryptography.hazmat.primitives.serialization import load_pem_public_key import os # DH generator must be 2 or 5 # Minumun DH key size is 512 # The sample code is extracted from the book Python Cryptography # The book can be downloaded from https://leanpub.com/cryptop # Online Crypto Playgroud https://8gwifi.org # Author Anish Nath p=175628339748224396140181355652569699881813470248510623740591206685224250268384255240141948567354436537469491258220480057343568322574414086924865612809502228925716250748136611976100895526530988783989918151666049795173173954826715147064072440336587386179441044551636048835596196013590766513435349750248369932891 g=107176209836536718962801284808131605075363838277339744565850617301534676770726222742912610436798059249618678970839324288089303827822543766150505159246951497945379339255850622488608863364657965634629341847037411606765436699180972115636657444687917156956960679037643921673927062603550324334473749946110139377151 pn = dh.DHParameterNumbers(p,g) parameters = pn.parameters(default_backend()) #You must generate a new private key using generate_private_key() for each exchange() when performing an DHE key exchange private_key = parameters.generate_private_key() #peer_public_key = parameters.generate_private_key().public_key() #Public Key Extracted peer_public_key = load_pem_public_key(open('/tmp/shpub.pem', 'rb').read(),default_backend()) shared_key = private_key.exchange(peer_public_key) print "Shared Key " + hexlify(shared_key) # Perform key derivation. derived_key = HKDF(
class DH: DH_GENERATOR = 2 PRIME_MODULO = int( "0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A4" "31B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B" "1FE649286651ECE65381FFFFFFFFFFFFFFFF", 16) PARAM_NUMBERS = dh.DHParameterNumbers(p=PRIME_MODULO, g=DH_GENERATOR) @staticmethod def generate_keys(): """ Generates the 128 bit diffe hellman private (x) and public (g^x) keys. :return: x value, x as bytes, gx value, and gx as bytes """ # Use cryptography module to generate secure keys dh_params = DH.PARAM_NUMBERS.parameters(default_backend()) x = dh_params.generate_private_key() x_bytes = x.private_numbers().x.to_bytes(128, 'big') # Also create the public key ==> gx gx = x.public_key() gx_bytes = gx.public_numbers().y.to_bytes(128, 'big') return x, x_bytes, gx, gx_bytes @staticmethod def derrive_shared_key(x: dh.DHPrivateKey, gy: bytes, hash: bytes): """ Derrive the shared key from gy with x, as done in Diffie Hellman :param x: OP's private key :param gy: OR's public key :param hash: a hash of the shared key given by the OR (known as KH) :return: a dict of keys for encryption, decryption, and hashing """ # Generate the shared key material gy = DH.dh_public_from_bytes(gy) shared_key_material = x.exchange(gy) # Derrive from shared key material the set of keys kdf_dict = DH.kdf_tor(shared_key_material) if not kdf_dict['KH'] == hash: raise ValueError( "[*] ERROR: Hash Value is not what the shared key should be") else: print("[*] TAP handshake completed successfully.") return kdf_dict @staticmethod def dh_public_from_bytes(key_bytes: bytes): """ Turn a key represtented in bytes into a diffie hellman public key object :param key_bytes: the key in bytes format :return: the public key as an object """ y = int.from_bytes(key_bytes, 'big') peer_pub_numbers = dh.DHPublicNumbers(y, DH.PARAM_NUMBERS) return peer_pub_numbers.public_key(default_backend()) @staticmethod def kdf_tor(key_material: bytes): """ From the base key material K0, they compute KEY_LEN*2+HASH_LEN*3 bytes of derivative key data as K = H(K0 | [00]) | H(K0 | [01]) | H(K0 | [02]) | ... The first HASH_LEN bytes of K form KH; the next HASH_LEN form the forward digest Df; the next HASH_LEN 41-60 form the backward digest Db; the next KEY_LEN 61-76 form Kf, and the final KEY_LEN form Kb. :param key_material: K0 which is g^xy in TAP handshake :return: the dict of keys """ expanded_key = bytearray() i = 0 while len(expanded_key) < CryptoConstants.KDF_TOR_LEN: assert i < 256 counter_byte = pack.pack_value(CryptoConstants.COUNTER_BYTE_LEN, i) expanded_key += Hash.hash_bytes(key_material + counter_byte, hashes.SHA1()) i += 1 kdf_tor_dict = { 'KH': expanded_key[:CryptoConstants.HASH_LEN], 'Df': expanded_key[CryptoConstants.HASH_LEN:(CryptoConstants.HASH_LEN * 2)], 'Db': expanded_key[(CryptoConstants.HASH_LEN * 2):(CryptoConstants.HASH_LEN * 3)], 'Kf': expanded_key[(CryptoConstants.HASH_LEN * 3):(CryptoConstants.HASH_LEN * 3 + CryptoConstants.KEY_LEN)], 'Kb': expanded_key[(CryptoConstants.HASH_LEN * 3 + CryptoConstants.KEY_LEN):( CryptoConstants.HASH_LEN * 3 + CryptoConstants.KEY_LEN * 2)] } return kdf_tor_dict
def process(self, msg=b""): """ Processa uma mensagem (`bytestring`) enviada pelo SERVIDOR. Retorna a mensagem a transmitir como resposta (`None` para finalizar ligação) """ #primeiro p e g self.msg_cnt += 1 if msg == b'': msg = mensagemboasvinda(self) return msg while len(msg) > 0: if msg: if (msg[:1] == b'E'): break if (msg[:1] == b'P'): global derived_key_2 global public_key_file_server_serial P = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 G = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 #ve qual é a chave publica DH server public_key_server_dh = int(msg[1:].decode()) #dh do cliente pn = dh.DHParameterNumbers(P, G) parameters = pn.parameters(default_backend()) #criar private key dh do cliente private_key_cliente_dh = parameters.generate_private_key() #gerar public key dh do cliente public_key_cliente_dh = private_key_cliente_dh.public_key( ).public_numbers().y #atraves da public key dh cria objeto para calcular chave Partilhada peerPublicNumbers2 = dh.DHPublicNumbers( public_key_server_dh, pn) peer_key2 = peerPublicNumbers2.public_key( default_backend()) #Lê o ficheiro p12 para extrair a sua chave privada filepriv = open("privateKeyCli.pem", "rb") keyprivateclii = filepriv.read() filepriv.close() #fazer serializacao chave privada ficheiro do cliente private_key_file_cliente_serial = serialization.load_pem_private_key( keyprivateclii, password=None, backend=default_backend()) #- Lê chave pública do ficheiro do servidor filepub = open("publicKeySvr.pem", "rb") keypublicread = filepub.read() filepub.close() #fazer serializacao chave publica ficheiro do SERVIDOR public_key_file_server_serial = serialization.load_pem_public_key( keypublicread, backend=default_backend()) clp12 = crypto.load_pkcs12( open("client.p12", 'rb').read(), "xpto") print(clp12) clpem = getCertificado(clp12) keyprivatecli = extractPrivate(clp12) #concatenar chave publica dh server + chave publica dh cliente gxgy = str(public_key_server_dh) + str( public_key_cliente_dh) global gyxx gyxx = gxgy.encode() #assinatura = gxgy + chave privada ficheiro cliente serial signature = keyprivatecli.sign( gyxx, padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256()) public_key_cliente_dh_2 = str( public_key_cliente_dh).encode() #envia assinatura + certificado + chave pública tmp = b'S' + signature + public_key_cliente_dh_2 + clpem shared_key_2 = private_key_cliente_dh.exchange(peer_key2) derived_key_2 = HKDF( algorithm=hashes.SHA512(), length=24, salt=None, info=b'handshake data', backend=default_backend()).derive(shared_key_2) print(signature) print(public_key_cliente_dh_2) print(clpem) return tmp #finito #reopen if (msg[:1] == b'm'): #- Recebe Assinatura print("entra aqui") vsign = msg[1:257] svrpem = msg[257:] print("here\n") print(svrpem) print("svrpem\n") verificacao = verifica(svrpem) if verificacao: pub_svr = extractPublic(svrpem) verifySignature(vsign, pub_svr, gyxx) print('é seguro falarmos') balhelhe = b'4' return balhelhe else: print(signature) print(public_key_cliente_dh) print(clpem) msg = b'S' + signature + clpem if (msg[:1] == b'4'): iv_recebido = msg[1:17] #chave de aes mac_recebido = msg[17:49] new_msg = msg[49:] #imprime mensagem recebida print('Received (%d): %r' % (1, msg)) print('Input message to send (empty to finish)') new_msg_encode = input().encode() iv_servido = os.urandom(16) #encriptar ct = encriptarcliente(keyaes, iv_servido, new_msg_encode) #hmac hmacfin = hmaccliente(keymac, ct) #verificamac(self,msg,hmacfin,mac_recebido) iv_cliente = os.urandom(16) mensagem = b'C' + iv_servido + hmacfin + ct return mensagem if len(mensagem) > 0 else None else: #desencriptar cipher = Cipher(algorithms.AES(keyaes), modes.CTR(iv_recebido), backend=backend) decryptor = cipher.decryptor() #hmac hmacfin = hmacclienteelse(keymac, new_msg) txt = decryptor.update(new_msg) + decryptor.finalize() msg = txt.decode() #verificamac(self,msg,hmacfin,mac_recebido) #Função para verificar o hmac #def verificamac(self,msg,hmacfin,mac_recebido,msgpv=b''): if (hmacfin == mac_recebido): print('Received (%d): %r' % (self.msg_cnt, msg)) print('Input message to send (empty to finish)') new_msg_encode = input().encode() iv_posve = os.urandom(16) ct = encriptarelse(keyaes, iv_posve, new_msg_encode) msgpv = iv_posve + hmacfin + ct print(msgpv) return msgpv if len(msgpv) > 0 else None else: print('deu erro, nao e igual')
def __init__(self): self.private_key = dh.DHParameterNumbers(P, G).parameters( default_backend()).generate_private_key()
from cryptography.hazmat.primitives import hashes, hmac, padding, serialization from cryptography.hazmat.primitives.asymmetric import dh from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives.serialization import load_pem_public_key cl_id = 0 # ID de cada cliente sv_address = 'localhost' # Endereço do servidor sv_port = 8888 # Porta do servidor max_msg_size = 9999 hkdf_info = b'hkdf password' # Palavra-passe para o HKDF # Parâmetros de grupo P = 99494096650139337106186933977618513974146274831566768179581759037259788798151499814653951492724365471316253651463342255785311748602922458795201382445323499931625451272600173180136123245441204133515800495917242011863558721723303661523372572477211620144038809673692512025566673746993593384600667047373692203583 G = 44157404837960328768872680677686802650999163226766694797650810379076416463147265401084491113667624054557335394761604876882446924929840681990106974314935015501571333024773172440352475358750668213444607353872754650805031912866692119819377041901642732455911509867728218394542745330014071040326856846990119719675 pn = dh.DHParameterNumbers(P, G) parameters = pn.parameters(default_backend()) # Chave privada do servidor sv_key_private = parameters.generate_private_key() sv_key_peer_public = sv_key_private.public_key() # Chave pública do servidor sv_key_public = sv_key_peer_public.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) class Connection(object): def __init__(self, id, address=None):
def tcp_echo_client(loop=None): if loop is None: loop = asyncio.get_event_loop() reader, writer = yield from asyncio.open_connection('127.0.0.1', 8888, loop=loop) key = AESGCM.generate_key(bit_length=128) #Receber os parametros p = yield from reader.read(3000) g = yield from reader.read(3000) pn = dh.DHParameterNumbers(int(p.decode()), int(g.decode())) parameters = pn.parameters(default_backend()) private_key = parameters.generate_private_key() #Receber a public key dele public_key2 = yield from reader.read(3000) partner_pk = load_pem_public_key(public_key2, default_backend()) public_key = private_key.public_key() public_bytes = public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) writer.write(public_bytes) yield from writer.drain() #Fazer load do p12 p12 = crypto.load_pkcs12( open("Cliente.p12", 'rb').read(), "secretpassword") assinatura = assinar(public_bytes, public_key2, p12) writer.write(assinatura) yield from writer.drain() certificate = p12.get_certificate() cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, certificate) writer.write(cert_pem) yield from writer.drain() shared_key = private_key.exchange(partner_pk) assinatura_partner = yield from reader.read(256) certificate_part = yield from reader.read(3000) certificate_part = crypto.load_certificate(crypto.FILETYPE_PEM, certificate_part) if (len(assinatura_partner) != 0): if (verify_chain_of_trust(certificate_part) == True): res = verificar(assinatura_partner, public_bytes, public_key2, certificate_part) if res == 0: writer.write(b"") yield from writer.drain() else: data = b'S' #Gerar a chave aesgcm = AESGCM(shared_key[:32]) client = Client("Cliente 1", aesgcm) msg = client.initmsg() while len(data) > 0: if msg: msg = b'M' + msg writer.write(msg) if msg[:1] == b'E': break data = yield from reader.read(100) if len(data) > 0: msg = client.respond(data[1:]) else: break else: break writer.write(b'E') print('Socket closed!') writer.close()