def test_bytearray(self): data = b"\x00\x01\x02" h0 = Poly1305.new(key=self.key, data=data, cipher=AES) d_ref = h0.digest() # Data and key can be a bytearray (during initialization) key_ba = bytearray(self.key) data_ba = bytearray(data) h1 = Poly1305.new(key=self.key, data=data, cipher=AES, nonce=h0.nonce) h2 = Poly1305.new(key=key_ba, data=data_ba, cipher=AES, nonce=h0.nonce) key_ba[:1] = b'\xFF' data_ba[:1] = b'\xEE' self.assertEqual(h1.digest(), d_ref) self.assertEqual(h2.digest(), d_ref) # Data can be a bytearray (during operation) data_ba = bytearray(data) h1 = Poly1305.new(key=self.key, cipher=AES) h2 = Poly1305.new(key=self.key, cipher=AES, nonce=h1.nonce) h1.update(data) h2.update(data_ba) data_ba[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest())
def test_bytearray(self): data = b"\x00\x01\x02" h0 = Poly1305.new(key=self.key, data=data, cipher=AES) d_ref = h0.digest() # Data and key can be a bytearray (during initialization) key_ba = bytearray(self.key) data_ba = bytearray(data) h1 = Poly1305.new(key=self.key, data=data, cipher=AES, nonce=h0.nonce) h2 = Poly1305.new(key=key_ba, data=data_ba, cipher=AES, nonce=h0.nonce) key_ba[:1] = b'\xFF' data_ba[:1] = b'\xEE' self.assertEqual(h1.digest(), d_ref) self.assertEqual(h2.digest(), d_ref) # Data can be a bytearray (during operation) data_ba = bytearray(data) h1 = Poly1305.new(key=self.key, cipher=AES) h2 = Poly1305.new(key=self.key, cipher=AES, nonce=h1.nonce) h1.update(data) h2.update(data_ba) data_ba[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest())
def test_new_positive(self): data = b'r' * 100 h1 = Poly1305.new(key=self.key, cipher=ChaCha20) self.assertEqual(h1.digest_size, 16) self.assertEqual(len(h1.nonce), 12) h2 = Poly1305.new(key=self.key, cipher=ChaCha20, nonce=b'8' * 8) self.assertEqual(len(h2.nonce), 8) self.assertEqual(h2.nonce, b'8' * 8)
def test_update(self): pieces = [b"\x0A" * 200, b"\x14" * 300] h1 = Poly1305.new(key=self.key, cipher=AES) h1.update(pieces[0]).update(pieces[1]) d1 = h1.digest() h2 = Poly1305.new(key=self.key, cipher=AES, nonce=h1.nonce) h2.update(pieces[0] + pieces[1]) d2 = h2.digest() self.assertEqual(d1, d2)
def test_new_positive(self): data = b'r' * 100 h1 = Poly1305.new(key=self.key, cipher=ChaCha20) self.assertEqual(h1.digest_size, 16) self.assertEqual(len(h1.nonce), 12) h2 = Poly1305.new(key=self.key, cipher=ChaCha20, nonce = b'8' * 8) self.assertEqual(len(h2.nonce), 8) self.assertEqual(h2.nonce, b'8' * 8)
def test_update(self): pieces = [b"\x0A" * 200, b"\x14" * 300] h1 = Poly1305.new(key=self.key, cipher=AES) h1.update(pieces[0]).update(pieces[1]) d1 = h1.digest() h2 = Poly1305.new(key=self.key, cipher=AES, nonce=h1.nonce) h2.update(pieces[0] + pieces[1]) d2 = h2.digest() self.assertEqual(d1, d2)
def test_new_positive(self): data = b'r' * 100 h1 = Poly1305.new(key=self.key, cipher=AES) self.assertEqual(h1.digest_size, 16) self.assertEqual(len(h1.nonce), 16) d1 = h1.update(data).digest() self.assertEqual(len(d1), 16) h2 = Poly1305.new(key=self.key, nonce=h1.nonce, data=data, cipher=AES) d2 = h2.digest() self.assertEqual(h1.nonce, h2.nonce) self.assertEqual(d1, d2)
def test_new_positive(self): data = b'r' * 100 h1 = Poly1305.new(key=self.key, cipher=AES) self.assertEqual(h1.digest_size, 16) self.assertEqual(len(h1.nonce), 16) d1 = h1.update(data).digest() self.assertEqual(len(d1), 16) h2 = Poly1305.new(key=self.key, nonce=h1.nonce, data=data, cipher=AES) d2 = h2.digest() self.assertEqual(h1.nonce, h2.nonce) self.assertEqual(d1, d2)
def test_update_after_digest(self): msg=b"rrrrttt" # Normally, update() cannot be done after digest() h = Poly1305.new(key=self.key, data=msg[:4], cipher=AES) h.digest() self.assertRaises(TypeError, h.update, msg[4:])
def test_update_after_digest(self): msg = b"rrrrttt" # Normally, update() cannot be done after digest() h = Poly1305.new(key=self.key, data=msg[:4], cipher=AES) h.digest() self.assertRaises(TypeError, h.update, msg[4:])
def chat_send(room_socket, my_text, member_info, text_list): m = my_text.get() if len(m) == 0: return # mac = Poly1305.new(key=key, cipher=AES, nonce=nonce) for member in member_info: destination = member.encode('ASCII') to_msg = encrypt_message(member_info[member], client_id + ": " + m) mac = Poly1305.new(key=key, cipher=AES, nonce=nonce) mac.update(to_msg) mac_hex_digest = mac.hexdigest().encode('ASCII') # mac ready = select.select([room_socket], [room_socket], []) if not ready[0] and ready[1]: room_socket.sendall(destination) ready = select.select([room_socket], [room_socket], []) if not ready[0] and ready[1]: room_socket.sendall(to_msg) # inicio mac ready = select.select([room_socket], [room_socket], []) if not ready[0] and ready[1]: room_socket.sendall(mac_hex_digest) # final mac text_list.insert(tkinter.END, client_id + ": " + m) # # Instead of just writing to the list, recv the msg as confirmation # destination = encrypt_message(server_key, client_id) # to_msg = encrypt_message(public_key, client_id + ": " + m) # ready = select.select([room_socket], [room_socket], []) # if not ready[0] and ready[1]: # room_socket.sendall(destination) # ready = select.select([room_socket], [room_socket], []) # if not ready[0] and ready[1]: # room_socket.sendall(to_msg) my_text.set("")
def verify_Poly1305_mac(data, key, nonce, mac_digest): mac_verify = Poly1305.new(data=data, key=key, nonce=nonce, cipher=AES) try: mac_verify.hexverify(mac_digest) print('Message Authentication Success') except: print('Message Authentication Failed')
def test_digest(self): h = Poly1305.new(key=self.key, cipher=AES) digest = h.digest() # hexdigest does not change the state self.assertEqual(h.digest(), digest) # digest returns a byte string self.failUnless(isinstance(digest, type(b"digest")))
def test_digest(self): h = Poly1305.new(key=self.key, cipher=AES) digest = h.digest() # hexdigest does not change the state self.assertEqual(h.digest(), digest) # digest returns a byte string self.failUnless(isinstance(digest, type(b"digest")))
def chat_recv(room_socket, text_list, member_info, w): while len(member_info) > 0: try: if not w.winfo_exists(): break ready = select.select([room_socket], [], [], 1) if ready[0]: enc_msg = room_socket.recv(BUFSIZ) if len(enc_msg) == 0: raise ConnectionError # inicio mac ready = select.select([room_socket], [], []) if ready[0]: mac_hex_digest = room_socket.recv(BUFSIZ).decode('ASCII') # final mac recv_msg = (decrypt_message(private_key, enc_msg)) if "/*-*/s_l/*+*/" in recv_msg: m_name = recv_msg.replace("/*-*/s_l/*+*/", "") del member_info[m_name] text_list.insert(tkinter.END, m_name + ' left the room') continue if "/*file-sent*/" in recv_msg: f_name = recv_msg.replace("/*file-sent*/", "", 1) text_list.insert(tkinter.END, f_name) f_name = f_name[f_name.find(" |") + 2:len(f_name)] get_file(w, client_socket, f_name) continue mac_verify = Poly1305.new(key=key, nonce=nonce, cipher=AES, data=enc_msg) mac_verify.hexverify(mac_hex_digest) text_list.insert(tkinter.END, recv_msg) except ConnectionError: # traceback.print_exc() print("Closed from server?") break except OSError: # traceback.print_exc() print("Closed from client") break except RuntimeError: print("App ended, closing all windows") break except ValueError: text_list.insert( tkinter.END, "2-end Authentication FAILED! Closing connection") traceback.print_exc() print("MAC check failed") break except: traceback.print_exc() if len(member_info) == 0: text_list.insert( tkinter.END, 'Everyone else left the chat room. Closing chat room') room_socket.close()
def test_hex_digest(self): mac = Poly1305.new(key=self.key, cipher=AES) digest = mac.digest() hexdigest = mac.hexdigest() # hexdigest is equivalent to digest self.assertEqual(hexlify(digest), tobytes(hexdigest)) # hexdigest does not change the state self.assertEqual(mac.hexdigest(), hexdigest) # hexdigest returns a string self.failUnless(isinstance(hexdigest, type("digest")))
def test_hex_digest(self): mac = Poly1305.new(key=self.key, cipher=AES) digest = mac.digest() hexdigest = mac.hexdigest() # hexdigest is equivalent to digest self.assertEqual(hexlify(digest), tobytes(hexdigest)) # hexdigest does not change the state self.assertEqual(mac.hexdigest(), hexdigest) # hexdigest returns a string self.failUnless(isinstance(hexdigest, type("digest")))
def test_memoryview(self): data = b"\x00\x01\x02" def get_mv_ro(data): return memoryview(data) def get_mv_rw(data): return memoryview(bytearray(data)) for get_mv in (get_mv_ro, get_mv_rw): # Data and key can be a memoryview (during initialization) key_mv = get_mv(self.key) data_mv = get_mv(data) h1 = Poly1305.new(key=self.key, data=data, cipher=AES) h2 = Poly1305.new(key=key_mv, data=data_mv, cipher=AES, nonce=h1.nonce) if not data_mv.readonly: data_mv[:1] = b'\xFF' key_mv[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest()) # Data can be a memoryview (during operation) data_mv = get_mv(data) h1 = Poly1305.new(key=self.key, cipher=AES) h2 = Poly1305.new(key=self.key, cipher=AES, nonce=h1.nonce) h1.update(data) h2.update(data_mv) if not data_mv.readonly: data_mv[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest())
def runTest(self): tag = unhexlify(b"fb447350c4e868c52ac3275cf9d4327e") msg = b'' for msg_len in range(5000 + 1): key = tag + strxor_c(tag, 0xFF) nonce = tag[::-1] if msg_len > 0: msg = msg + tobytes(tag[0]) auth = Poly1305.new(key=key, nonce=nonce, cipher=AES, data=msg) tag = auth.digest() # Compare against output of original DJB's poly1305aes-20050218 self.assertEqual("CDFA436DDD629C7DC20E1128530BAED2", auth.hexdigest().upper())
def runTest(self): tag = unhexlify(b"fb447350c4e868c52ac3275cf9d4327e") msg = b'' for msg_len in range(5000 + 1): key = tag + strxor_c(tag, 0xFF) nonce = tag[::-1] if msg_len > 0: msg = msg + tobytes(tag[0]) auth = Poly1305.new(key=key, nonce=nonce, cipher=AES, data=msg) tag = auth.digest() # Compare against output of original DJB's poly1305aes-20050218 self.assertEqual("CDFA436DDD629C7DC20E1128530BAED2", auth.hexdigest().upper())
def test_memoryview(self): data = b"\x00\x01\x02" def get_mv_ro(data): return memoryview(data) def get_mv_rw(data): return memoryview(bytearray(data)) for get_mv in (get_mv_ro, get_mv_rw): # Data and key can be a memoryview (during initialization) key_mv = get_mv(self.key) data_mv = get_mv(data) h1 = Poly1305.new(key=self.key, data=data, cipher=AES) h2 = Poly1305.new(key=key_mv, data=data_mv, cipher=AES, nonce=h1.nonce) if not data_mv.readonly: data_mv[:1] = b'\xFF' key_mv[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest()) # Data can be a memoryview (during operation) data_mv = get_mv(data) h1 = Poly1305.new(key=self.key, cipher=AES) h2 = Poly1305.new(key=self.key, cipher=AES, nonce=h1.nonce) h1.update(data) h2.update(data_mv) if not data_mv.readonly: data_mv[:1] = b'\xFF' self.assertEqual(h1.digest(), h2.digest())
def __init__(self, key, nonce): """Initialize a ChaCha20-Poly1305 AEAD cipher object See also `new()` at the module level.""" self.nonce = _copy_bytes(None, None, nonce) self._next = (self.update, self.encrypt, self.decrypt, self.digest, self.verify) self._authenticator = Poly1305.new(key=key, nonce=nonce, cipher=ChaCha20) self._cipher = ChaCha20.new(key=key, nonce=nonce) self._cipher.seek(64) # Block counter starts at 1 self._len_aad = 0 self._len_ct = 0 self._mac_tag = None self._status = _CipherStatus.PROCESSING_AUTH_DATA
def __init__(self, key, nonce): """Initialize a ChaCha20-Poly1305 AEAD cipher object See also `new()` at the module level.""" self.nonce = _copy_bytes(None, None, nonce) self._next = (self.update, self.encrypt, self.decrypt, self.digest, self.verify) self._authenticator = Poly1305.new(key=key, nonce=nonce, cipher=ChaCha20) self._cipher = ChaCha20.new(key=key, nonce=nonce) self._cipher.seek(64) # Block counter starts at 1 self._len_aad = 0 self._len_ct = 0 self._mac_tag = None self._status = _CipherStatus.PROCESSING_AUTH_DATA
def EaM(ptxt, key1, key2, nonce): counter = 0 temp2 = 0 NonceCount = nonce ^ counter ctxt = 0 E = SimonCipher(key1) #encryption block default 128 bit mac = Poly1305.new(key=key2.encode(), cipher=AES) #Mac block block = breakup(ptxt, 16) T = mac.update(ptxt.encode()).hexdigest() for i in range(len(block)): NonceCount = nonce ^ counter counter = counter + 1 temp = E.encrypt(NonceCount) for a in block[ i]: #shift temp2 by 1 byte each time and or it with a new byte temp2 = (temp2 << 8) | ord(a) #print(temp2) #print(temp) ctxt = (ctxt << 128) | (temp ^ temp2) # accumulate onto the ctxt print("CTXT: ") print(hex(ctxt)) print("T: ") print(T)
def on_closing_filesender(wind, s, room_socket, member_info, text_list, fname): s.close() wind.destroy() try: for member in member_info: destination = member.encode('ASCII') to_msg = encrypt_message( member_info[member], "/*file-sent*/" + client_id + " sent a file: |" + fname) mac = Poly1305.new(key=key, cipher=AES, nonce=nonce) mac.update(to_msg) mac_hex_digest = mac.hexdigest().encode('ASCII') # mac ready = select.select([room_socket], [room_socket], []) if not ready[0] and ready[1]: room_socket.sendall(destination) ready = select.select([room_socket], [room_socket], []) if not ready[0] and ready[1]: room_socket.sendall(to_msg) ready = select.select([room_socket], [room_socket], []) if not ready[0] and ready[1]: room_socket.sendall(mac_hex_digest) text_list.insert(tkinter.END, "You sent a file: |" + fname) except: traceback.print_exc()
def generate_Poly1305_mac(data, key): mac = Poly1305.new(key=key, cipher=AES, data=data) return (mac.hexdigest(), mac.nonce)
def new(key, *data, **kwds): _kwds = dict(kwds) if len(data) == 1: _kwds['data'] = data[0] _kwds['key'] = key return Poly1305.new(**_kwds)
def encrypt(plaintext, mode): key = get_random_bytes(32) ret = None if mode == "AES_CBC": iv = os.urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) start_time = time.time() ret = cipher.encrypt(pad(plaintext, AES.block_size)) elif mode == "AES_OCB": cipher = AES.new(key, AES.MODE_OCB) start_time = time.time() #ret, _ = cipher.encrypt_and_digest(pad(plaintext, AES.block_size)) ret, _ = cipher.encrypt_and_digest(plaintext) elif mode == "AES_GCM": cipher = AES.new(key, AES.MODE_GCM) start_time = time.time() ret, _ = cipher.encrypt_and_digest(plaintext) elif mode == "AES_CCM": cipher = AES.new(key, AES.MODE_CCM) start_time = time.time() #ret, _ = cipher.encrypt_and_digest(pad(plaintext, AES.block_size)) ret, _ = cipher.encrypt_and_digest(plaintext) elif mode == "RSA1024": # generate private key key = RSA.generate(1024) encrypted_key = key.export_key() file_out = open("rsa_key.bin", "wb") file_out.write(encrypted_key) file_out.close() encoded_key = open("rsa_key.bin", "rb").read() key = RSA.import_key(encoded_key) cipher = PKCS1_OAEP.new(key) # max block size of RSA 1024 is 86 Bytes blk_size = 86 start_time = time.time() for i in range(0, len(plaintext), blk_size): blk_plain = plaintext[i:i+blk_size] ret = cipher.encrypt(blk_plain) elif mode == "RSA2048": # generate private key key = RSA.generate(2048) encrypted_key = key.export_key() file_out = open("rsa_key.bin", "wb") file_out.write(encrypted_key) file_out.close() encoded_key = open("rsa_key.bin", "rb").read() key = RSA.import_key(encoded_key) cipher = PKCS1_OAEP.new(key) # max block size of RSA 1024 is 214 Bytes blk_size = 214 start_time = time.time() for i in range(0, len(plaintext), blk_size): blk_plain = plaintext[i:i+blk_size] ret = cipher.encrypt(blk_plain) elif mode == "SHA": # SHA256 provided by Crypto.Hash is slow. # hash_obj = SHA256.new() # start_time = time.time() # hash_obj.update(plaintext) # ret = hash_obj.hexdigest() m = hashlib.sha256() start_time = time.time() m.update(plaintext) ret = m.digest() elif mode == "CC20": cipher = ChaCha20.new(key=key) start_time = time.time() ret = cipher.encrypt(plaintext) elif mode == "POLY": mac = Poly1305.new(key=key, cipher=AES) start_time = time.time() mac.update(plaintext) ret = mac.hexdigest() elif mode == "CCP": cipher = ChaCha20_Poly1305.new(key=key) start_time = time.time() ret, _ = cipher.encrypt_and_digest(plaintext) elif mode == "HMAC": h = HMAC.new(key, digestmod=SHA256) start_time = time.time() h.update(plaintext) ret = h.hexdigest() elif mode == "CMAC": cobj = CMAC.new(key, ciphermod=AES) start_time = time.time() cobj.update(plaintext) ret = cobj.hexdigest() else: print("Mode not supported.") exit(1) end_time = time.time() cost_time = end_time - start_time return ret, cost_time
def poly1305(k, p): #secret = b'Thirtytwo very very secret bytes' mac = Poly1305.new(key=k, cipher=AES) mac.update(p) tag = mac.nonce.hex() return tag
fh = open('/Users/kris/TopSecret.txt', 'rb') dataSHA = fh.read() hash_object = SHA256.new(data=dataSHA) print(hash_object.hexdigest()) # Poly1305: from Crypto.Hash import Poly1305 from Crypto.Cipher import AES fh = open('/Users/kris/TopSecret.txt', 'rb') dataPoly = fh.read() secret = b'\xa4\x84\x85\xe6\xf1\xc8\xfe\x81\xb8\r~\x13\x94\xc7\xc4\x7f\xab\xbf5%\xdc\x00\xd8\xffS\x80\xccO\xc6J\xb1\x83' mac = Poly1305.new(key=secret, cipher=AES) mac.update(dataPoly) print("Nonce: ", mac.nonce.hex()) print("MAC: ", mac.hexdigest()) hex_tag = Poly1305.new(key=secret, cipher=AES, data=dataPoly).hexdigest() # Encryption w/ AES CBC Mode: import json from base64 import b64encode from Crypto.Cipher import AES
def test_hexverify(self): h = Poly1305.new(key=self.key, cipher=AES) mac = h.hexdigest() h.hexverify(mac) self.assertRaises(ValueError, h.hexverify, "4556")
def test_verify(self): h = Poly1305.new(key=self.key, cipher=AES) mac = h.digest() h.verify(mac) wrong_mac = strxor_c(mac, 255) self.assertRaises(ValueError, h.verify, wrong_mac)
def test_update_negative(self): h = Poly1305.new(key=self.key, cipher=AES) self.assertRaises(TypeError, h.update, u"string")
def test_verify(self): h = Poly1305.new(key=self.key, cipher=AES) mac = h.digest() h.verify(mac) wrong_mac = strxor_c(mac, 255) self.assertRaises(ValueError, h.verify, wrong_mac)
def test_update_negative(self): h = Poly1305.new(key=self.key, cipher=AES) self.assertRaises(TypeError, h.update, u"string")
def test_hexverify(self): h = Poly1305.new(key=self.key, cipher=AES) mac = h.hexdigest() h.hexverify(mac) self.assertRaises(ValueError, h.hexverify, "4556")
def new(key, *data, **kwds): _kwds = dict(kwds) if len(data) == 1: _kwds['data'] = data[0] _kwds['key'] = key return Poly1305.new(**_kwds)