def decrypt(src, dst, key): with open(src, 'rb') as rf, open(dst, 'wb') as wf: m, version, enc_type, nonce_size, _ = struct.unpack('>2sHsB2s', rf.read(8)) if m != b'EN' or version != 2 or enc_type != b'P' or nonce_size != 24: return key_nonce = rf.read(nonce_size) e = rf.read(32+nonce_size) key_tag = rf.read(16) cipher = ChaCha20_Poly1305.new(key=key, nonce=key_nonce) d = cipher.decrypt(e) cipher.verify(key_tag) data_key = d[:32] data_nonce = d[32:] rf.seek(-16, io.SEEK_END) message_size = rf.tell() - 8 - nonce_size * 2 - 32 - 16 tag = rf.read(16) cipher = ChaCha20_Poly1305.new(key=data_key, nonce=data_nonce) rf.seek(8 + nonce_size * 2 + 32 + 16) a = 0 while True: n = min(4096, message_size-a) if n <= 0: break e = rf.read(n) d = cipher.decrypt(e) wf.write(d) a += len(e) cipher.verify(tag)
def test_encrypt(self): # From https://tools.ietf.org/html/draft-arciszewski-xchacha-03 # Section A.3.1 pt = b""" 4c616469657320616e642047656e746c656d656e206f662074686520636c6173 73206f66202739393a204966204920636f756c64206f6666657220796f75206f 6e6c79206f6e652074697020666f7220746865206675747572652c2073756e73 637265656e20776f756c642062652069742e""" pt = unhexlify(pt.replace(b"\n", b"").replace(b" ", b"")) aad = unhexlify(b"50515253c0c1c2c3c4c5c6c7") key = unhexlify(b"808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f") iv = unhexlify(b"404142434445464748494a4b4c4d4e4f5051525354555657") ct = b""" bd6d179d3e83d43b9576579493c0e939572a1700252bfaccbed2902c21396cbb 731c7f1b0b4aa6440bf3a82f4eda7e39ae64c6708c54c216cb96b72e1213b452 2f8c9ba40db5d945b11b69b982c1bb9e3f3fac2bc369488f76b2383565d3fff9 21f9664c97637da9768812f615c68b13b52e""" ct = unhexlify(ct.replace(b"\n", b"").replace(b" ", b"")) tag = unhexlify(b"c0875924c1c7987947deafd8780acf49") cipher = ChaCha20_Poly1305.new(key=key, nonce=iv) cipher.update(aad) ct_test, tag_test = cipher.encrypt_and_digest(pt) self.assertEqual(ct, ct_test) self.assertEqual(tag, tag_test) cipher = ChaCha20_Poly1305.new(key=key, nonce=iv) cipher.update(aad) cipher.decrypt_and_verify(ct, tag)
def computeHintSequences(key, time): interval = toIntervalNumber(time) # closest interval number besides the current one altInterval = toIntervalNumber(time + 800000) if altInterval == interval: altInterval = toIntervalNumber(time - 8000000) c = ChaCha20_Poly1305.new(key=key, nonce=struct.pack("<Q", interval)) x = c.encrypt(b"\0\0\0\0\0\0") hint = hintBytesToNumber(x[0:3]) wake = hintBytesToNumber(x[3:6]) c = ChaCha20_Poly1305.new(key=key, nonce=struct.pack("<Q", altInterval)) x = c.encrypt(b"\0\0\0\0\0\0") althint = hintBytesToNumber(x[0:3]) altwake = hintBytesToNumber(x[3:6]) c = ChaCha20_Poly1305.new(key=key, nonce=b'\0\0\0\0\0\0\0\0') x = c.encrypt(b"\0\0\0") fixedhint = hintBytesToNumber(x[0:3]) x = { 'phint': hint, 'altphint': althint, 'fixedhint': fixedhint, 'pwake': wake, 'altpwake': altwake } return x
def test_hex_mac(self): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) mac_hex = cipher.hexdigest() self.assertEqual(cipher.digest(), unhexlify(mac_hex)) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.hexverify(mac_hex)
def test_valid_init_verify(self): # Verify path INIT->VERIFY cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) mac = cipher.digest() cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.verify(mac)
def test_invalid_decrypt_or_update_after_verify(self): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) ct = cipher.encrypt(self.data_128) mac = cipher.digest() for method_name in "decrypt", "update": cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.decrypt(ct) cipher.verify(mac) self.assertRaises(TypeError, getattr(cipher, method_name), self.data_128) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.decrypt(ct) cipher.verify(mac) self.assertRaises(TypeError, getattr(cipher, method_name), self.data_128) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.decrypt_and_verify(ct, mac) self.assertRaises(TypeError, getattr(cipher, method_name), self.data_128)
def test_data_must_be_bytes(self): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*') cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')
def test_loopback(self): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) pt = get_tag_random("plaintext", 16 * 100) ct = cipher.encrypt(pt) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2)
def test_either_encrypt_or_decrypt(self): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.encrypt(b"") self.assertRaises(TypeError, cipher.decrypt, b"") cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.decrypt(b"") self.assertRaises(TypeError, cipher.encrypt, b"")
def test_nonce_attribute(self): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) self.assertEqual(cipher.nonce, self.nonce_96) # By default, a 12 bytes long nonce is randomly generated nonce1 = ChaCha20_Poly1305.new(key=self.key_256).nonce nonce2 = ChaCha20_Poly1305.new(key=self.key_256).nonce self.assertEqual(len(nonce1), 12) self.assertNotEqual(nonce1, nonce2)
def test_invalid_mac(self): from Crypto.Util.strxor import strxor_c cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) ct, mac = cipher.encrypt_and_digest(self.data_128) invalid_mac = strxor_c(mac, 0x01) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) self.assertRaises(ValueError, cipher.decrypt_and_verify, ct, invalid_mac)
def test_valid_encrypt_and_digest_decrypt_and_verify(self): # encrypt_and_digest cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.update(self.data_128) ct, mac = cipher.encrypt_and_digest(self.data_128) # decrypt_and_verify cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.update(self.data_128) pt = cipher.decrypt_and_verify(ct, mac) self.assertEqual(self.data_128, pt)
def test_valid_init_update_digest_verify(self): # No plaintext, fixed authenticated data # Verify path INIT->UPDATE->DIGEST cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.update(self.data_128) mac = cipher.digest() # Verify path INIT->UPDATE->VERIFY cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.update(self.data_128) cipher.verify(mac)
def test_valid_init_encrypt_decrypt_digest_verify(self): # No authenticated data, fixed plaintext # Verify path INIT->ENCRYPT->DIGEST cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) ct = cipher.encrypt(self.data_128) mac = cipher.digest() # Verify path INIT->DECRYPT->VERIFY cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.decrypt(ct) cipher.verify(mac)
def test_invalid_encrypt_or_update_after_digest(self): for method_name in "encrypt", "update": cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.encrypt(self.data_128) cipher.digest() self.assertRaises(TypeError, getattr(cipher, method_name), self.data_128) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.encrypt_and_digest(self.data_128)
def test_valid_multiple_digest_or_verify(self): # Multiple calls to digest cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.update(self.data_128) first_mac = cipher.digest() for x in range(4): self.assertEqual(first_mac, cipher.digest()) # Multiple calls to verify cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.update(self.data_128) for x in range(5): cipher.verify(first_mac)
def runTest(self): for assoc_data, pt, ct, mac, key, nonce in self.test_vectors: # Encrypt cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) cipher.update(assoc_data) ct2, mac2 = cipher.encrypt_and_digest(pt) self.assertEqual(ct, ct2) self.assertEqual(mac, mac2) # Decrypt cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) cipher.update(assoc_data) pt2 = cipher.decrypt_and_verify(ct, mac) self.assertEqual(pt, pt2)
def decrypt(key, ciphertext, tag, nonce): ''' Decrypt the mnemonic phrase ''' # construct the cipher object with the key cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) print(f'{red}Decrypting mnemonic phrase.{end}') # decrypt and verify the ciphertext return cipher.decrypt_and_verify(ciphertext, tag)
def pair_verify_m3_m4(self, encrypted): prk = hkdf.hkdf_extract(b"Pair-Verify-Encrypt-Salt", self.accessory_shared_key) session_key = hkdf.hkdf_expand(prk, b"Pair-Verify-Encrypt-Info", 32) c = ChaCha20_Poly1305.new(key=session_key, nonce=b"PV-Msg03") enc_tlv = encrypted[:-16] tag = encrypted[-16:] dec_tlv = c.decrypt_and_verify(enc_tlv, tag) sub_tlv = Tlv8.decode(dec_tlv) device_id = sub_tlv[Tlv8.Tag.IDENTIFIER] device_sig = sub_tlv[Tlv8.Tag.SIGNATURE] device_info = self.client_curve_public + device_id + self.accessory_curve_public device_pairing_filepath = "./pairings/" + device_id.decode( "utf-8") + ".pub" if path.exists(device_pairing_filepath): with open(device_pairing_filepath, "rb") as device_pairing_file: self.device_ltpk = device_pairing_file.read() verify_key = nacl.signing.VerifyKey(self.device_ltpk) verify_key.verify(device_info, device_sig) return True, [Tlv8.Tag.STATE, PairingState.M4] else: return False, [Tlv8.Tag.ERROR, PairingErrors.AUTHENTICATION]
def aead_chacha20poly1305_encrypt(key, counter, plain_text, auth_text): cipher = ChaCha20_Poly1305.new(key=key, nonce=b'\x00\x00\x00\x00' + counter.to_bytes(8, 'little')) cipher.update(auth_text) cipher_text, digest = cipher.encrypt_and_digest(plain_text) return cipher_text + digest
def tls_13_server_new_session_ticket(self, server_static_enc_key, resumption_secret): ticket_lifetime = (604800).to_bytes(4, 'big') ticket_age_add = get_random_bytes(4) ticket_nonce_len = (8).to_bytes(1, 'big') ticket_nonce = get_random_bytes(8) #PSK calculation suite = tls_constants.TLS_CHACHA20_POLY1305_SHA256 hkdf = tls_crypto.HKDF(self.csuite) hkdf_lbl = tls_crypto.tls_hkdf_label('resumption'.encode(), ticket_nonce, hkdf.hash_length) PSK = hkdf.tls_hkdf_expand(resumption_secret, hkdf_lbl, hkdf.hash_length) plaintext = PSK + ticket_age_add + ticket_lifetime + self.csuite.to_bytes( 2, 'big') nonce = get_random_bytes(8) #ctxt = tls_crypto.tls_aead_encrypt(suite, server_static_enc_key, nonce, plaintext) cipher = ChaCha20_Poly1305.new(key=server_static_enc_key, nonce=nonce) ciphertext, tag = cipher.encrypt_and_digest(plaintext) ctxt = ciphertext + tag ticket = nonce + ctxt ticket_len = (len(ticket)).to_bytes(2, 'big') ext_len = (1).to_bytes(2, 'big') ext_type = (tls_constants.EARLY_DATA_TYPE).to_bytes(1, 'big') early_data = (4096).to_bytes(4, 'big') #print(int.from_bytes(early_data, 'big')) session_ticket = ticket_lifetime + ticket_age_add + ticket_nonce_len + ticket_nonce + ticket_len + ticket + ext_len + ext_type + early_data return self.attach_handshake_header(tls_constants.NEWST_TYPE, session_ticket)
def decrypt(src, dst, password: str): with open(src, 'rb') as rf, open(dst, 'wb') as wf: tag = rf.read(16) header = rf.read(112) argon2_type, version, memory_cost, time_cost, parallelism, salt, nonce = struct.unpack( '>LLLLL32s24s36x', header) argon2_type = { 0: argon2.low_level.Type.D, 1: argon2.low_level.Type.I, 2: argon2.low_level.Type.ID }[argon2_type] if version != 19 or memory_cost > 1 * 1024 * 1024: return secret = password.encode() key = argon2.low_level.hash_secret_raw(secret=secret, salt=salt, time_cost=time_cost, memory_cost=memory_cost, parallelism=parallelism, hash_len=32, type=argon2_type, version=version) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) cipher.update(header) while True: d = rf.read(4096) if len(d) == 0: break wf.write(cipher.decrypt(d)) cipher.verify(tag)
def decrypt(key, ciphertext, authdata, iv, tag): """ Decrypts a message using ChaCha20-Poly1305. Args: key: 256-bit shared key ciphertext: Ciphertext to be decrypted authdata: Additional data for authentication iv: 96-bit initialization vector (nonce) tag: 128-bit authentication tag Returns: Plaintext if decryption succeeded, else None """ k = ("ciphertext", "auth", "iv", "tag") v = (b16decode(x) for x in (ciphertext, authdata, iv, tag)) result = dict(zip(k, v)) try: cipher = ChaCha20_Poly1305.new(key=key, nonce=result["iv"]) cipher.update(result["auth"]) plaintext = cipher.decrypt_and_verify(result["ciphertext"], result["tag"]) return plaintext except: print("Decryption failed") return None
def pair_verify_m1_m2(self, client_public): self.client_curve_public = client_public self.accessory_curve = x25519.X25519PrivateKey.generate() self.accessory_curve_public = self.accessory_curve.public_key( ).public_bytes(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) self.accessory_shared_key = self.accessory_curve.exchange( x25519.X25519PublicKey.from_public_bytes(client_public)) accessory_info = self.accessory_curve_public + self.accessory_id + client_public accessory_signed = self.accessory_ltsk.sign(accessory_info) accessory_sig = accessory_signed.signature sub_tlv = Tlv8.encode([ Tlv8.Tag.IDENTIFIER, self.accessory_id, Tlv8.Tag.SIGNATURE, accessory_sig ]) prk = hkdf.hkdf_extract(b"Pair-Verify-Encrypt-Salt", self.accessory_shared_key) session_key = hkdf.hkdf_expand(prk, b"Pair-Verify-Encrypt-Info", 32) c = ChaCha20_Poly1305.new(key=session_key, nonce=b"PV-Msg02") enc_tlv, tag = c.encrypt_and_digest(sub_tlv) return [ Tlv8.Tag.STATE, PairingState.M2, Tlv8.Tag.PUBLICKEY, self.accessory_curve_public, Tlv8.Tag.ENCRYPTEDDATA, enc_tlv + tag ]
def test_memoryview(self): # Encrypt key_mv = memoryview(bytearray(self.key_256)) nonce_mv = memoryview(bytearray(self.nonce_96)) header_mv = memoryview(bytearray(self.data_128)) data_mv = memoryview(bytearray(self.data_128)) cipher1 = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher1.update(self.data_128) ct = cipher1.encrypt(self.data_128) tag = cipher1.digest() cipher2 = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) key_mv[:3] = b'\xFF\xFF\xFF' nonce_mv[:3] = b'\xFF\xFF\xFF' cipher2.update(header_mv) header_mv[:3] = b'\xFF\xFF\xFF' ct_test = cipher2.encrypt(data_mv) data_mv[:3] = b'\x99\x99\x99' tag_test = cipher2.digest() self.assertEqual(ct, ct_test) self.assertEqual(tag, tag_test) self.assertEqual(cipher1.nonce, cipher2.nonce) # Decrypt key_mv = memoryview(bytearray(self.key_256)) nonce_mv = memoryview(bytearray(self.nonce_96)) header_mv = memoryview(bytearray(self.data_128)) ct_mv = memoryview(bytearray(ct)) tag_mv = memoryview(bytearray(tag)) del data_mv cipher3 = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) key_mv[:3] = b'\xFF\xFF\xFF' nonce_mv[:3] = b'\xFF\xFF\xFF' cipher3.update(header_mv) header_mv[:3] = b'\xFF\xFF\xFF' pt_test = cipher3.decrypt(ct_mv) ct_mv[:3] = b'\x99\x99\x99' cipher3.verify(tag_mv) self.assertEqual(pt_test, self.data_128)
def test_bytearray(self): # Encrypt key_ba = bytearray(self.key_256) nonce_ba = bytearray(self.nonce_96) header_ba = bytearray(self.data_128) data_ba = bytearray(self.data_128) cipher1 = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher1.update(self.data_128) ct = cipher1.encrypt(self.data_128) tag = cipher1.digest() cipher2 = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) key_ba[:3] = b'\xFF\xFF\xFF' nonce_ba[:3] = b'\xFF\xFF\xFF' cipher2.update(header_ba) header_ba[:3] = b'\xFF\xFF\xFF' ct_test = cipher2.encrypt(data_ba) data_ba[:3] = b'\x99\x99\x99' tag_test = cipher2.digest() self.assertEqual(ct, ct_test) self.assertEqual(tag, tag_test) self.assertEqual(cipher1.nonce, cipher2.nonce) # Decrypt key_ba = bytearray(self.key_256) nonce_ba = bytearray(self.nonce_96) header_ba = bytearray(self.data_128) ct_ba = bytearray(ct) tag_ba = bytearray(tag) del data_ba cipher3 = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) key_ba[:3] = b'\xFF\xFF\xFF' nonce_ba[:3] = b'\xFF\xFF\xFF' cipher3.update(header_ba) header_ba[:3] = b'\xFF\xFF\xFF' pt_test = cipher3.decrypt(ct_ba) ct_ba[:3] = b'\xFF\xFF\xFF' cipher3.verify(tag_ba) self.assertEqual(pt_test, self.data_128)
def runTest(self): # Encrypt/Decrypt data and test output parameter key = b'4' * 32 nonce = b'5' * 12 cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) pt = b'5' * 16 ct = cipher.encrypt(pt) output = bytearray(16) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) res = cipher.encrypt(pt, output=output) self.assertEqual(ct, output) self.assertEqual(res, None) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) res = cipher.decrypt(ct, output=output) self.assertEqual(pt, output) self.assertEqual(res, None) import sys if sys.version[:3] != '2.6': output = memoryview(bytearray(16)) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) cipher.encrypt(pt, output=output) self.assertEqual(ct, output) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) cipher.decrypt(ct, output=output) self.assertEqual(pt, output) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0' * 16) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0' * 16) shorter_output = bytearray(7) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
def test_corrupt_decrypt(self, tv): self._id = "Wycheproof Corrupt Decrypt ChaCha20-Poly1305 Test #" + str(tv.id) if len(tv.iv) == 0 or len(tv.ct) < 1: return cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv) cipher.update(tv.aad) ct_corrupt = strxor(tv.ct, b"\x00" * (len(tv.ct) - 1) + b"\x01") self.assertRaises(ValueError, cipher.decrypt_and_verify, ct_corrupt, tv.tag)
def test_message_chunks(self): # Validate that both associated data and plaintext/ciphertext # can be broken up in chunks of arbitrary length auth_data = get_tag_random("authenticated data", 127) plaintext = get_tag_random("plaintext", 127) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.update(auth_data) ciphertext, ref_mac = cipher.encrypt_and_digest(plaintext) def break_up(data, chunk_length): return [data[i:i+chunk_length] for i in range(0, len(data), chunk_length)] # Encryption for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128: cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) for chunk in break_up(auth_data, chunk_length): cipher.update(chunk) pt2 = b"" for chunk in break_up(ciphertext, chunk_length): pt2 += cipher.decrypt(chunk) self.assertEqual(plaintext, pt2) cipher.verify(ref_mac) # Decryption for chunk_length in 1, 2, 3, 7, 10, 13, 16, 40, 80, 128: cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) for chunk in break_up(auth_data, chunk_length): cipher.update(chunk) ct2 = b"" for chunk in break_up(plaintext, chunk_length): ct2 += cipher.encrypt(chunk) self.assertEqual(ciphertext, ct2) self.assertEquals(cipher.digest(), ref_mac)
def test_invalid_mixing_encrypt_decrypt(self): # Once per method, with or without assoc. data for method1_name, method2_name in (("encrypt", "decrypt"), ("decrypt", "encrypt")): for assoc_data_present in (True, False): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) if assoc_data_present: cipher.update(self.data_128) getattr(cipher, method1_name)(self.data_128) self.assertRaises(TypeError, getattr(cipher, method2_name), self.data_128)
def runTest(self): # Encrypt/Decrypt data and test output parameter key = b'4' * 32 nonce = b'5' * 12 cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) pt = b'5' * 16 ct = cipher.encrypt(pt) output = bytearray(16) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) res = cipher.encrypt(pt, output=output) self.assertEqual(ct, output) self.assertEqual(res, None) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) res = cipher.decrypt(ct, output=output) self.assertEqual(pt, output) self.assertEqual(res, None) import sys if sys.version[:3] != '2.6': output = memoryview(bytearray(16)) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) cipher.encrypt(pt, output=output) self.assertEqual(ct, output) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) cipher.decrypt(ct, output=output) self.assertEqual(pt, output) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16) shorter_output = bytearray(7) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output) cipher = ChaCha20_Poly1305.new(key=key, nonce=nonce) self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)
def test_valid_multiple_encrypt_or_decrypt(self): for method_name in "encrypt", "decrypt": for auth_data in (None, b"333", self.data_128, self.data_128 + b"3"): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) if auth_data is not None: cipher.update(auth_data) method = getattr(cipher, method_name) method(self.data_128) method(self.data_128) method(self.data_128) method(self.data_128)
def test_encrypt(self, tv): self._id = "Wycheproof Encrypt ChaCha20-Poly1305 Test #" + str(tv.id) try: cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv) except ValueError as e: assert len(tv.iv) not in (8, 12) and "Nonce must be" in str(e) return cipher.update(tv.aad) ct, tag = cipher.encrypt_and_digest(tv.msg) if tv.valid: self.assertEqual(ct, tv.ct) self.assertEqual(tag, tv.tag) self.warn(tv)
def test_decrypt(self, tv): self._id = "Wycheproof Decrypt ChaCha20-Poly1305 Test #" + str(tv.id) try: cipher = ChaCha20_Poly1305.new(key=tv.key, nonce=tv.iv) except ValueError as e: assert len(tv.iv) not in (8, 12) and "Nonce must be" in str(e) return cipher.update(tv.aad) try: pt = cipher.decrypt_and_verify(tv.ct, tv.tag) except ValueError: assert not tv.valid else: assert tv.valid self.assertEqual(pt, tv.msg) self.warn(tv)
def test_nonce(self): # Nonce can only be 8 or 12 bytes cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=b'H' * 8) self.assertEqual(len(cipher.nonce), 8) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=b'H' * 12) self.assertEqual(len(cipher.nonce), 12) # If not passed, the nonce is created randomly cipher = ChaCha20_Poly1305.new(key=self.key_256) nonce1 = cipher.nonce cipher = ChaCha20_Poly1305.new(key=self.key_256) nonce2 = cipher.nonce self.assertEqual(len(nonce1), 12) self.assertNotEqual(nonce1, nonce2) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) ct = cipher.encrypt(self.data_128) cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) self.assertEquals(ct, cipher.encrypt(self.data_128))
def setup(self): from Crypto.Cipher import ChaCha20_Poly1305 self.cipher_new = lambda nonce: ChaCha20_Poly1305.new(key=self.key, nonce=nonce)
def test_block_size(self): # Not based on block ciphers cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) self.failIf(hasattr(cipher, 'block_size'))
def test_null_encryption_decryption(self): for func in "encrypt", "decrypt": cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) result = getattr(cipher, func)(b"") self.assertEqual(result, b"")
def test_mac_len(self): cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) _, mac = cipher.encrypt_and_digest(self.data_128) self.assertEqual(len(mac), 16)
def test_valid_init_digest(self): # Verify path INIT->DIGEST cipher = ChaCha20_Poly1305.new(key=self.key_256, nonce=self.nonce_96) cipher.digest()