def test_aes_ccm_aead_api(backend, wycheproof): key = binascii.unhexlify(wycheproof.testcase["key"]) iv = binascii.unhexlify(wycheproof.testcase["iv"]) aad = binascii.unhexlify(wycheproof.testcase["aad"]) msg = binascii.unhexlify(wycheproof.testcase["msg"]) ct = binascii.unhexlify(wycheproof.testcase["ct"]) tag = binascii.unhexlify(wycheproof.testcase["tag"]) if (wycheproof.invalid and wycheproof.testcase["comment"] == "Invalid tag size"): with pytest.raises(ValueError): AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8) return aesccm = AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8) if wycheproof.valid or wycheproof.acceptable: computed_ct = aesccm.encrypt(iv, msg, aad) assert computed_ct == ct + tag computed_msg = aesccm.decrypt(iv, ct + tag, aad) assert computed_msg == msg elif not 7 <= len(iv) <= 13: with pytest.raises(ValueError): aesccm.decrypt(iv, ct + tag, aad) else: with pytest.raises(InvalidTag): aesccm.decrypt(iv, ct + tag, aad)
def test_vectors(self, subtests, backend): vectors = _load_all_params( os.path.join("ciphers", "AES", "CCM"), [ "DVPT128.rsp", "DVPT192.rsp", "DVPT256.rsp", "VADT128.rsp", "VADT192.rsp", "VADT256.rsp", "VNT128.rsp", "VNT192.rsp", "VNT256.rsp", "VPT128.rsp", "VPT192.rsp", "VPT256.rsp", ], load_nist_ccm_vectors, ) for vector in vectors: with subtests.test(): key = binascii.unhexlify(vector["key"]) nonce = binascii.unhexlify(vector["nonce"]) adata = binascii.unhexlify(vector["adata"])[: vector["alen"]] ct = binascii.unhexlify(vector["ct"]) pt = binascii.unhexlify(vector["payload"])[: vector["plen"]] aesccm = AESCCM(key, vector["tlen"]) if vector.get("fail"): with pytest.raises(InvalidTag): aesccm.decrypt(nonce, ct, adata) else: computed_pt = aesccm.decrypt(nonce, ct, adata) assert computed_pt == pt assert aesccm.encrypt(nonce, pt, adata) == ct
def test_aes_ccm_aead_api(backend, wycheproof): key = binascii.unhexlify(wycheproof.testcase["key"]) iv = binascii.unhexlify(wycheproof.testcase["iv"]) aad = binascii.unhexlify(wycheproof.testcase["aad"]) msg = binascii.unhexlify(wycheproof.testcase["msg"]) ct = binascii.unhexlify(wycheproof.testcase["ct"]) tag = binascii.unhexlify(wycheproof.testcase["tag"]) if ( wycheproof.invalid and wycheproof.testcase["comment"] == "Invalid tag size" ): with pytest.raises(ValueError): AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8) return aesccm = AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8) if wycheproof.valid or wycheproof.acceptable: computed_ct = aesccm.encrypt(iv, msg, aad) assert computed_ct == ct + tag computed_msg = aesccm.decrypt(iv, ct + tag, aad) assert computed_msg == msg elif not 7 <= len(iv) <= 13: with pytest.raises(ValueError): aesccm.decrypt(iv, ct + tag, aad) else: with pytest.raises(InvalidTag): aesccm.decrypt(iv, ct + tag, aad)
def AES_CCM_ecnrypt(text): data = bytes(text,'utf-8') aad = bytes("Research",'utf-8') key = AESCCM.generate_key(bit_length=128) aesccm = AESCCM(key) nonce = os.urandom(12) ct = aesccm.encrypt(nonce, data, aad) aesccm.decrypt(nonce, ct, aad) return True
def test_associated_data_none_equal_to_empty_bytestring(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) nonce = os.urandom(12) ct1 = aesccm.encrypt(nonce, b"some_data", None) ct2 = aesccm.encrypt(nonce, b"some_data", b"") assert ct1 == ct2 pt1 = aesccm.decrypt(nonce, ct1, None) pt2 = aesccm.decrypt(nonce, ct2, b"") assert pt1 == pt2
def test_associated_data_none_equal_to_empty_bytestring(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) nonce = os.urandom(12) ct1 = aesccm.encrypt(nonce, b"some_data", None) ct2 = aesccm.encrypt(nonce, b"some_data", b"") assert ct1 == ct2 pt1 = aesccm.decrypt(nonce, ct1, None) pt2 = aesccm.decrypt(nonce, ct2, b"") assert pt1 == pt2
def test_buffer_protocol(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) pt = b"encrypt me" ad = b"additional" nonce = os.urandom(12) ct = aesccm.encrypt(nonce, pt, ad) computed_pt = aesccm.decrypt(nonce, ct, ad) assert computed_pt == pt aesccm2 = AESCCM(bytearray(key)) ct2 = aesccm2.encrypt(bytearray(nonce), pt, ad) assert ct2 == ct computed_pt2 = aesccm2.decrypt(bytearray(nonce), ct2, ad) assert computed_pt2 == pt
def test_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) nonce = binascii.unhexlify(vector["nonce"]) adata = binascii.unhexlify(vector["adata"])[:vector["alen"]] ct = binascii.unhexlify(vector["ct"]) pt = binascii.unhexlify(vector["payload"])[:vector["plen"]] aesccm = AESCCM(key, vector["tlen"]) if vector.get('fail'): with pytest.raises(InvalidTag): aesccm.decrypt(nonce, ct, adata) else: computed_pt = aesccm.decrypt(nonce, ct, adata) assert computed_pt == pt assert aesccm.encrypt(nonce, pt, adata) == ct
def test_buffer_protocol(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) pt = b"encrypt me" ad = b"additional" nonce = os.urandom(12) ct = aesccm.encrypt(nonce, pt, ad) computed_pt = aesccm.decrypt(nonce, ct, ad) assert computed_pt == pt aesccm2 = AESCCM(bytearray(key)) ct2 = aesccm2.encrypt(bytearray(nonce), pt, ad) assert ct2 == ct computed_pt2 = aesccm2.decrypt(bytearray(nonce), ct2, ad) assert computed_pt2 == pt
def test_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) nonce = binascii.unhexlify(vector["nonce"]) adata = binascii.unhexlify(vector["adata"])[:vector["alen"]] ct = binascii.unhexlify(vector["ct"]) pt = binascii.unhexlify(vector["payload"])[:vector["plen"]] aesccm = AESCCM(key, vector["tlen"]) if vector.get('fail'): with pytest.raises(InvalidTag): aesccm.decrypt(nonce, ct, adata) else: computed_pt = aesccm.decrypt(nonce, ct, adata) assert computed_pt == pt assert aesccm.encrypt(nonce, pt, adata) == ct
def test_randomize_aead(session): aes_key = os.urandom(16) nonce_id = 0x01234567 key = OtpAeadKey.put( session, 0, "Test OTP Randomize AEAD", 1, CAPABILITY.DECRYPT_OTP | CAPABILITY.RANDOMIZE_OTP_AEAD, ALGORITHM.AES128_YUBICO_OTP, nonce_id, aes_key, ) aead = key.randomize_otp_aead() assert len(aead) == 36 # Decrypt generated AEAD aes_ccm = AESCCM(aes_key, 8) nonce, ct = aead[:6], aead[6:] pt = aes_ccm.decrypt(struct.pack("<I6sBBB", nonce_id, nonce, 0, 0, 0), ct, None) # Construct an OTP otp_data = OtpData(1, 2, 3, 4) otp = _construct_otp(pt[:16], pt[16:], otp_data) # Compare YubiHSM decrypted output assert key.decrypt_otp(aead, otp) == otp_data key.delete()
def decryptMessage(encMessage, sessionKey, nonce): aesccm = AESCCM(sessionKey) message = aesccm.decrypt(nonce, encMessage, None) return message
def Mydecrypt(ct, IV, key): # If the key length is too short, return with error if (len(key) < 32): return "Your key length is too short: " + str(len(key)) # Decrypt using the AES/CBC-MAC object aesccm = AESCCM(key) M = aesccm.decrypt(IV, ct, "None".encode('utf-8')) return M
def aes_ccm_decrypt(key: Key, nonce: Nonce, data: bytes, mic: MIC, associated_data: Optional[bytes] = None) -> bytes: tag_len = len(mic.bytes_be) aes_ccm = AESCCM(key.key_bytes, tag_len) try: return aes_ccm.decrypt(nonce.as_be_bytes(), data + mic.bytes_be, associated_data) except exceptions.InvalidKey: raise InvalidKey() except exceptions.InvalidTag: raise InvalidMIC()
def test_roundtrip(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) pt = b"encrypt me" ad = b"additional" nonce = os.urandom(12) ct = aesccm.encrypt(nonce, pt, ad) computed_pt = aesccm.decrypt(nonce, ct, ad) assert computed_pt == pt
def test_roundtrip(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) pt = b"encrypt me" ad = b"additional" nonce = os.urandom(12) ct = aesccm.encrypt(nonce, pt, ad) computed_pt = aesccm.decrypt(nonce, ct, ad) assert computed_pt == pt
def _decrypt_ccm(secret_key, value): aesccm = AESCCM(secret_key) try: decoded = base64.b64decode(value) nonce = decoded[:AES_CCM_NONCE_LENGTH] ct = decoded[AES_CCM_NONCE_LENGTH:] decrypted = aesccm.decrypt(nonce, ct, None) return decrypted.decode("utf-8") except Exception: logger.exception("Got exception when trying to decrypt value `%s`", value) raise DecryptionFailureException()
class CYBLE_AESCCM: """ To be used with cyble internal functions """ def __init__(self, key16): self.aesccm = AESCCM(key16, tag_length=4) def CyBle_AesCcmEncrypt(self, nonce13, plaintext): """ Acts like the cyble function :param nonce13: bytes :param plaintext: bytes (1..27) :return: ciphertext (bytes) """ return self.aesccm.encrypt(nonce13, plaintext, bytes([1])) def CyBle_AesCcmDecrypt(self, nonce13, ciphertext): """ Acts like the cyble function :param nonce13: bytes :param ciphertext: bytes (1..27) :return: plaintext (bytes) """ return self.aesccm.decrypt(nonce13, ciphertext, bytes([1])) def crypt(self, cosa): """ receives plaintext and returns the ciphertext :param cosa: bytes/str :return: bytes """ if isinstance(cosa, str): cosa = bytes(cosa.encode('ascii')) # an handful of random bytes ahorb = bytes(secrets.token_bytes(13)) return ahorb + self.CyBle_AesCcmEncrypt(ahorb, cosa) def decrypt(self, cosa): """ receives ciphertext and returns the plaintext :param cosa: bytes :return: bytes """ return self.CyBle_AesCcmDecrypt(bytes(cosa[:13]), bytes(cosa[13:]))
def Algo4(filename, key, nonce, fname): aad = "authenticated but unencrypted data" aesccm = AESCCM(key) source_filename = 'encrypted/' + fname+'/files/'+ filename target_filename = 'files/' + filename file = open(source_filename,'rb') target_file = open(target_filename,'wb') raw = "" for line in file: raw = raw + line secret_data = aesccm.decrypt(nonce, raw, aad) target_file.write(secret_data) file.close() target_file.close()
def decrypt(cls, encoded: bytes, key: bytes, iv: bytes, external_aad: bytes): decoded = loads(encoded) tag = decoded.tag (protected, unprotected, ciphertext) = decoded.value aad = dumps(Encrypt0Message.enc_structure(protected, external_aad)) print("OSCORE AAD: ", aad.hex()) print("TAG: ", ciphertext[-8:].hex()) cipher = AESCCM(key, tag_length=8) plaintext = cipher.decrypt(nonce=iv, data=ciphertext, associated_data=aad) return plaintext
def repo_thread(conn): while True: try: # get data data = recvall(conn) if data: s = data.decode("utf-8") data = json.loads(s) # first messages from the client # This message is not secure if "type" in data.keys() and (data["type"] == "otp_needed" or data["type"] == "requestId"): print("MESSAGE REQUEST:", data["type"]) resp = message_execute(data) if resp != None: resp_json = json.dumps(resp) conn.send(bytes(resp_json, 'utf-8')) # deal with the message to save session key elif 'from' not in data.keys(): print("MESSAGE REQUEST:", data["type"]) resp, serial = message_execute(data) if resp != None: resp_json = json.dumps(resp) nonce = os.urandom(13) aesccm = AESCCM(myAuction.clients_keys[int(serial)]) b = aesccm.encrypt(nonce, bytes(resp_json, 'utf-8'), None) data_str = json.dumps({"nonce": base64.b64encode(nonce).decode(), "data" : base64.b64encode(b).decode()}) conn.send(bytes(data_str, 'utf-8')) # deal with all the other messages with the structure : "{ from : id , data : encrypted_data , nonce : nonce used }" else: aesccm = AESCCM(myAuction.clients_keys[data['from']]) d = aesccm.decrypt(base64.b64decode(data['nonce']), base64.b64decode(data['data']), None) j = json.loads(d.decode()) print("MESSAGE REQUEST:", j["type"]) resp = message_execute(j) if resp != None: resp_json = json.dumps(resp) data_str = json.dumps({"message" : resp_json}) nonce = os.urandom(8) b = aesccm.encrypt(nonce, bytes(data_str, 'utf-8'), None) data_str = json.dumps({"nonce": base64.b64encode(nonce).decode(), "data" : base64.b64encode(b).decode()}) conn.send(bytes(data_str, 'utf-8')) except SocketError: pass
def test_decrypt_data_too_short(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) with pytest.raises(InvalidTag): aesccm.decrypt(b"0" * 12, b"0", None)
import os from cryptography.hazmat.primitives.ciphers.aead import AESCCM data = '' with open('myfile.txt', 'r', encoding='utf-8') as f: data = f.read() for line in f.readline(): data += line aud = b"authenticated but unencrypted data" key = AESCCM.generate_key(bit_length=128) aesccm = AESCCM(key) nonce = os.urandom(13) # NIST recommends 96-bit edata = aesccm.encrypt(nonce, bytes(data,'utf-8'), aud) print('Original File Contents') print(bytes(data, 'utf-8')) print('Encrypted Data') print('*****************') print(edata) print('*****************') print('Unencrypted Data') print('*****************') print(aesccm.decrypt(nonce, edata, aud)) print('*****************')
def message_decipher_aes(message, nonce): aesccm = AESCCM(keys['repository']) return aesccm.decrypt(nonce, message, None).decode()
def test_decrypt_data_too_short(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) with pytest.raises(InvalidTag): aesccm.decrypt(b"0" * 12, b"0", None)
def decrypt(cls, key: 'SK', nonce: bytes, ciphertext: bytes, external_aad: bytes) -> bytes: cipher = AESCCM(key=key.k, tag_length=cls.get_tag_length()) return cipher.decrypt(nonce, data=ciphertext, associated_data=external_aad)
class AESCCMKey(ContentEncryptionKey): """ """ def __init__(self, params: Dict[int, Any]): """ """ super().__init__(params) self._cipher: AESCCM self._nonce_len = 0 # Validate alg. if self._alg == 10: # AES-CCM-16-64-128 if not self._key: self._key = AESCCM.generate_key(bit_length=128) if len(self._key) != 16: raise ValueError("The length of AES-CCM-16-64-128 key should be 16 bytes.") self._cipher = AESCCM(self._key, tag_length=8) self._nonce_len = 13 elif self._alg == 11: # AES-CCM-16-64-256 if not self._key: self._key = AESCCM.generate_key(bit_length=256) if len(self._key) != 32: raise ValueError("The length of AES-CCM-16-64-256 key should be 32 bytes.") self._cipher = AESCCM(self._key, tag_length=8) self._nonce_len = 13 elif self._alg == 12: # AES-CCM-64-64-128 if not self._key: self._key = AESCCM.generate_key(bit_length=128) if len(self._key) != 16: raise ValueError("The length of AES-CCM-64-64-128 key should be 16 bytes.") self._cipher = AESCCM(self._key, tag_length=8) self._nonce_len = 7 elif self._alg == 13: # AES-CCM-64-64-256 if not self._key: self._key = AESCCM.generate_key(bit_length=256) if len(self._key) != 32: raise ValueError("The length of AES-CCM-64-64-256 key should be 32 bytes.") self._cipher = AESCCM(self._key, tag_length=8) self._nonce_len = 7 elif self._alg == 30: # AES-CCM-16-128-128 if not self._key: self._key = AESCCM.generate_key(bit_length=128) if len(self._key) != 16: raise ValueError("The length of AES-CCM-16-128-128 key should be 16 bytes.") self._cipher = AESCCM(self._key) self._nonce_len = 13 elif self._alg == 31: # AES-CCM-16-128-256 if not self._key: self._key = AESCCM.generate_key(bit_length=256) if len(self._key) != 32: raise ValueError("The length of AES-CCM-16-128-256 key should be 32 bytes.") self._cipher = AESCCM(self._key) self._nonce_len = 13 elif self._alg == 32: # AES-CCM-64-128-128 if not self._key: self._key = AESCCM.generate_key(bit_length=128) if len(self._key) != 16: raise ValueError("The length of AES-CCM-64-128-128 key should be 16 bytes.") self._cipher = AESCCM(self._key) self._nonce_len = 7 elif self._alg == 33: # AES-CCM-64-128-256 if not self._key: self._key = AESCCM.generate_key(bit_length=256) if len(self._key) != 32: raise ValueError("The length of AES-CCM-64-128-256 key should be 32 bytes.") self._cipher = AESCCM(self._key) self._nonce_len = 7 else: raise ValueError(f"Unsupported or unknown alg({self._alg}) for AES CCM.") def generate_nonce(self): return token_bytes(self._nonce_len) def encrypt(self, msg: bytes, nonce: bytes, aad: Optional[bytes] = None) -> bytes: """ """ if len(nonce) != self._nonce_len: raise ValueError("The length of nonce should be %d bytes." % self._nonce_len) try: return self._cipher.encrypt(nonce, msg, aad) except Exception as err: raise EncodeError("Failed to encrypt.") from err def decrypt(self, msg: bytes, nonce: bytes, aad: Optional[bytes] = None) -> bytes: """ """ if len(nonce) != self._nonce_len: raise ValueError("The length of nonce should be %d bytes." % self._nonce_len) try: return self._cipher.decrypt(nonce, msg, aad) except Exception as err: raise DecodeError("Failed to decrypt.") from err
from cryptography.hazmat.primitives.ciphers.aead import AESCCM from cryptography.hazmat.backends import default_backend import os # 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 backend = default_backend() nonce = os.urandom(13) message = "Hello 8gwifi.org" aaed = "Not Secret" # This AES key is 128 but long key = AESCCM.generate_key(256) aesccm = AESCCM(key) #AES-256 GCM Mode Encyption ct = aesccm.encrypt(nonce, message, aaed) print ct assert message, aesccm.decrypt(nonce, ct, aaed)
def Decrypt(key_ccm, nonce, ct, aad): aesccm = AESCCM(bytes(key_ccm), 8) return aesccm.decrypt(bytes(nonce), bytes(ct), bytes(aad))
def decrypt(self,key,msg,nonce): aesccm = AESCCM(key) dt = aesccm.decrypt(nonce, msg, None) return dt
args = arguments() print(args) if args['generate_key'] and args['key_size']: key = AESCCM.generate_key(bit_length=int(args['key_size'])) aesccm = AESCCM(key) aad = b'authentic' nouce = os.urandom(13) for file_ in args['file']: ct = None with open(file_, 'rb') as data: if args['operation'] == 'encrypt': ct = aesccm.encrypt(nouce, data.read(), aad) with open(file_, 'wb') as writer: writer.write(ct) print(hexdigest(key)) print(hexdigest(nouce)) else: aesccm = AESCCM(str_2_hex(args['key'])) aad = b'authentic' nouce = os.urandom(13) for file_ in args['file']: ct = None with open(file_, 'rb') as data: if args['operation'] == 'encrypt': ct = aesccm.encrypt(nouce, data.read(), aad) else: nouce = str_2_hex(args['nouce']) ct = aesccm.decrypt(nouce, data.read(), aad) with open(file_, 'wb') as writer: writer.write(ct)