def decryptMessage(encMessage, sessionKey, nonce): aesccm = AESCCM(sessionKey) message = aesccm.decrypt(nonce, encMessage, None) return message
def getDevicePSKData(mode, psk, nonce, digest, payload_key): crypto_mode = cryptoMode(mode) LOG.debug('Creating PSK data: ') LOG.debug(' mode: {}'.format(crypto_mode.name)) LOG.debug(' iv ({0} bytes): {1}'.format(len(nonce), binascii.b2a_hex(nonce))) LOG.debug(' md ({0} bytes): {1}'.format(len(digest), binascii.b2a_hex(digest))) data = {'hash': digest} if payload_key: data['cek'] = payload_key asnData = native_decoder.decode( data, asn1Spec=manifest_definition.KeyTableEntry()) plainText = der_encoder.encode(asnData) LOG.debug('PSK plaintext ({0} bytes): {1}'.format( len(plainText), binascii.b2a_hex(plainText))) pskSig = { 'none-psk-aes-128-ccm-sha256': lambda key, iv, d: AESCCM(key[:128 // 8]).encrypt(iv, d, b''), 'psk-aes-128-ccm-sha256': lambda key, iv, d: AESCCM(key[:128 // 8]).encrypt(iv, d, b'') }.get(crypto_mode.name, lambda a, b, d: None)(psk, nonce, plainText) LOG.debug('PSK data ({0} bytes): {1}'.format(len(pskSig), binascii.b2a_hex(pskSig))) return pskSig
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 _encrypt(self, key: bytes, iv: bytes, aad: bytes): cipher = AESCCM(key, tag_length=8) ciphertext = cipher.encrypt(nonce=iv, data=self.plaintext, associated_data=aad) return ciphertext
def aesccm_mode_encryption(bitlength, filename, key): fd = open(filename, "r") data = fd.read() data = data.encode() fd.close() if not key: print("****Generating key with key length:" + str(bitlength)) key = AESCCM.generate_key(bit_length=bitlength) else: fd = shelve.open(key) key = fd["key"] key = key[0] key1 = AESCCM(key) nonce = os.urandom(12) print("***Encrypting your data***") ct = key1.encrypt(nonce, data, None) ls = [key, nonce] print("***Saving your data to file:" + filename + "_encrypted.db***") new_name = filename + "_encrypted" db = shelve.open(new_name) db["data"] = ct db.close() print("***saving you key and nonces to file:" + filename + "_keys.db") key_file = filename + "_keys" db = shelve.open(key_file) db["key"] = ls db.close()
def test_default_tag_length(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) nonce = os.urandom(12) pt = b"hello" ct = aesccm.encrypt(nonce, pt, None) assert len(ct) == len(pt) + 16
def main(): if len(sys.argv) <= 4: print("Need path to binary file and library name.") print("Exiting...") sys.exit() filepath_aad = sys.argv[1] # authenticated associated data filepath = sys.argv[2] use_encryption = sys.argv[3] libname = sys.argv[4] if not os.path.isfile(filepath): print("File {} does not exist. Exiting...".format(filepath)) sys.exit() if not os.path.isfile(filepath_aad): print("File {} does not exist. Exiting...".format(filepath_aad)) sys.exit() with open(filepath, "rb") as f: data = f.read() with open(filepath_aad, "rb") as f: data_aad = f.read() if use_encryption == "1": aesccm = AESCCM(key, tag_size) # Put the nonce at the start of the file. data_enc = nonce + aesccm.encrypt(nonce, data, data_aad) with open(libname, "wb") as f: f.write(data_enc) else: with open(libname, "wb") as f: f.write(data)
def encryptMessage(message, sessionKey, nonce): aesccm = AESCCM(sessionKey) encMessage = aesccm.encrypt(nonce, message, None) return encMessage
def aes_ccm_encrypt(key: Key, nonce: Nonce, data: bytes, mic_len=32, associated_data: Optional[bytes] = None) -> Tuple[ bytes, MIC]: tag_len = mic_len // 8 aes_ccm = AESCCM(key.key_bytes, tag_len) raw = aes_ccm.encrypt(nonce.as_be_bytes(), data, associated_data) mic = MIC(raw[-tag_len:]) return raw[:-tag_len], mic
def encrypt(self,key,msg): aesccm = AESCCM(key) nonce = get_random_bytes(13) ct = aesccm.encrypt(nonce, msg,None) return (nonce,ct) return msg
def test_nonce_too_long(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) pt = b"encrypt me" * 6600 # pt can be no more than 65536 bytes when nonce is 13 bytes nonce = os.urandom(13) with pytest.raises(ValueError): aesccm.encrypt(nonce, pt, None)
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 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 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 validate_chain(chain): # get last block (contains the keys) last_block = chain[len(chain) - 1] # get first block (ciphered fields) first_block = chain[0] if "owner_key" in last_block[1]["Data"]: manager_key = base64.b64decode(last_block[1]["Data"]["manager_key"]) owner_key = load_pem_private_key( base64.b64decode(last_block[1]["Data"]["owner_key"]), None, default_backend()) cipher_fields = first_block[1]["Data"]["anonymous_fields"] auction_id = first_block[1]["Data"]["auction_id"] flag = True deciphered_bids = [] for i in range(len(chain)): if "owner_key" in last_block[1]["Data"]: validation = validate_block(chain, i, AESCCM(manager_key), owner_key, cipher_fields) if i != 0 and i != len(chain) - 1: block = copy.copy(chain[i][1]) if len(validation) > 2: block["Data"]["user"] = validation[2][0] block["Data"]["bid"] = validation[2][1] deciphered_bids.append(block) else: deciphered_bids.append(copy.copy(chain[i][1])) else: validation = validate_block(chain, i, None, None, None) flag = flag and validation[0] print(validation[1]) # produce decrypted chain if "owner_key" in last_block[1]["Data"]: all_receipts_inside = decrypt_receipts(deciphered_bids, AESCCM(manager_key), owner_key, cipher_fields, auction_id) if all_receipts_inside: print("All your receipts are inside the auctions chain!") print("Valid Chain? ", flag) if len(deciphered_bids) > 2: bid_values = [int(b["Data"]["bid"]) for b in deciphered_bids[1:-1]] i = bid_values.index(max(bid_values)) b = deciphered_bids[1 + i] print("Winner is \"" + b["Data"]["user"] + "\" paying " + b["Data"]["bid"] + "€ !") else: if len(deciphered_bids) == 0: print( "This auction is still encrypted. Waiting for owners key....") else: print("There were no bids!") return flag
def test_java_bouncy_castle_ccm_matching(): K = codecs.decode("404142434445464748494a4b4c4d4e4f", "hex") N = codecs.decode("10111213141516", "hex") P = codecs.decode("68656c6c6f20776f726c642121", "hex") C = codecs.decode("39264f148b54c456035de0a531c8344f46db12b388", "hex") cipher = AESCCM(K, tag_length=8) ciphertext = cipher.encrypt(N, P, None) assert ciphertext == C
def test_invalid_tag_length(self, backend): key = AESCCM.generate_key(128) with pytest.raises(ValueError): AESCCM(key, tag_length=7) with pytest.raises(ValueError): AESCCM(key, tag_length=2) with pytest.raises(TypeError): AESCCM(key, tag_length="notanint")
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 _encrypt_ccm(secret_key, value, field_max_length=None): aesccm = AESCCM(secret_key) nonce = os.urandom(AES_CCM_NONCE_LENGTH) ct = aesccm.encrypt(nonce, value.encode("utf-8"), None) encrypted = base64.b64encode(nonce + ct) if field_max_length: msg = "Tried to encode a value too large for this field" assert (len(encrypted) + _RESERVED_FIELD_SPACE) <= field_max_length, msg return encrypted
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): aad = "authenticated but unencrypted data" aesccm = AESCCM(key) source_filename = 'files/' + filename target_filename = 'encrypted/' + filename file = open(source_filename, 'rb') target_file = open(target_filename, 'wb') raw = "" for line in file: raw = raw + line secret_data = aesccm.encrypt(nonce, raw, aad) target_file.write(secret_data) file.close() target_file.close()
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 send_data(self, data): if self.mode == "client": # aesccm = AESCCM(self.encA) encData = AESCCM(self.encA).encrypt(self.ivA, data, None) self.ivA = (int.from_bytes(self.ivA, "big") + 1).to_bytes( 12, "big") elif self.mode == "server": # aesccm = AESCCM(self.encB) encData = AESCCM(self.encB).encrypt(self.ivB, data, None) self.ivB = (int.from_bytes(self.ivB, "big") + 1).to_bytes( 12, "big") new_packet = DataPacket(data=encData) self.transport.write(new_packet.__serialize__()) print("CLIENT: CRAP OUT")
def configure(self): my_private_key = self.generate_private_key() self.my_pub_key_data = self.encode_pub_key(my_private_key.public_key()) self.bt_write(service_uuid, step1, True, "\x01\x00") self.bt_write(service_uuid, step1plus, True, "\x01\x00") self.bt_write(service_uuid, step1plus, False, CMD_GET_INFO) while self.state != WR_DID_STATE: if self.p.waitForNotifications(1.0): # handleNotification() was called continue print "Waiting..." # Perhaps do something else here remote_key = self.decode_pub_key(self.remote_key_data) e_share_key = self.create_e_share_key(remote_key, my_private_key) print("eShareKey:", e_share_key.encode("hex")) derived_key = HKDF(algorithm=hashes.SHA256(), length=64, salt=None, info=b'mible-setup-info', backend=default_backend()).derive(e_share_key) print("HKDF result:", derived_key.encode("hex")) token = derived_key[0:12] bind_key = derived_key[12:28] A = derived_key[28:44] print("token:", token.encode("hex")) print("bind_key:", bind_key.encode("hex")) print("A:", A.encode("hex")) aesccm = AESCCM(A) nonce = bytearray([16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]) did = "blt.3.129vl4ap05o01".encode() aad = "devID".encode() self.did_ct = aesccm.encrypt(nonce, did, aad) print("AES did CT:", self.did_ct.encode("hex")) self.bt_write(service_uuid, step1, False, CMD_WR_DID) while self.state != FINISHED_STATE: if self.p.waitForNotifications(1.0): # handleNotification() was called continue print "Waiting..."
def encrypter(): tools.empty_folder('key') tools.empty_folder('encrypted') key_1 = Fernet.generate_key() key_1_1 = Fernet.generate_key() key_1_2 = Fernet.generate_key() key_2 = ChaCha20Poly1305.generate_key() key_3 = AESGCM.generate_key(bit_length=128) key_4 = AESCCM.generate_key(bit_length=128) nonce13 = os.urandom(13) nonce12 = os.urandom(12) files = sorted(tools.list_dir('files')) for index in range(0, len(files)): if index % 4 == 0: Algo1_extented(files[index], key_1_1, key_1_2) elif index % 4 == 1: Algo2(files[index], key_2, nonce12) elif index % 4 == 2: Algo3(files[index], key_3, nonce12) else: Algo4(files[index], key_4, nonce13) secret_information = (key_1_1) + ":::::" + (key_1_2) + ":::::" + ( key_2) + ":::::" + (key_3) + ":::::" + (key_4) + ":::::" + ( nonce12) + ":::::" + (nonce13) Algo1(secret_information, key_1) public_key = open("./key/Taale_Ki_Chabhi.pem", "wb") public_key.write(key_1) public_key.close() tools.empty_folder('files')
def sendAES(data, key): repo_conn.send(bytes(json.dumps(data),"utf-8")) d = json.loads(recvall(repo_conn).decode("utf-8")) # for invalid otps if "response" in d.keys(): return d return json.loads(AESCCM(key).decrypt(base64.b64decode(d['nonce']), base64.b64decode(d['data']), None))
def encrypter(fname): tools.empty_folder('./encrypted/' + fname + '/files/' ) tools.empty_folder('./key/') key_1 = Fernet.generate_key() key_1_1 = Fernet.generate_key() key_1_2 = Fernet.generate_key() key_2 = ChaCha20Poly1305.generate_key() key_3 = AESGCM.generate_key(bit_length=128) key_4 = AESCCM.generate_key(bit_length=128) nonce13 = os.urandom(13) nonce12 = os.urandom(12) files = sorted(tools.list_dir('files')) for index in range(0,len(files)): if index%4 == 0: Algo1_extented(files[index],key_1_1,key_1_2, fname) elif index%4 == 1: Algo2(files[index],key_2,nonce12, fname) elif index%4 == 2: Algo3(files[index],key_3,nonce12, fname) else: Algo4(files[index],key_4,nonce13, fname) secret_information = (key_1_1)+":::::"+(key_1_2)+":::::"+(key_2)+":::::"+(key_3)+":::::"+(key_4)+":::::"+(nonce12)+":::::"+(nonce13) Algo1(secret_information,key_1, fname) # Static path to the image file for Steganography in_f = "./static/png.png" #out_f = './encrypted/' + fname + '/key/' + fname + '.png' out_f = './key/' + fname + '.png' in_img = cv2.imread(in_f) steg = Steganography(in_img) res = steg.encode_binary(key_1) cv2.imwrite(out_f, res) tools.empty_folder('files')
def data_handler(self, packet): if self.mode == "client": # aesccm = AESCCM(self.decA) decData = AESCCM(self.decA).decrypt(self.ivB, packet.data, None) self.ivB = (int.from_bytes(self.ivB, "big") + 1).to_bytes( 12, "big") elif self.mode == "server": # aesccm = AESCCM(self.decB) try: decData = AESCCM(self.decB).decrypt(self.ivA, packet.data, None) except Exception as error: print(error) self.ivA = (int.from_bytes(self.ivA, "big") + 1).to_bytes( 12, "big") self.higherProtocol().data_received(decData)
def oscore_missing_modules(): """Return a list of modules that are missing in order to use OSCORE, or a false value if everything is present""" missing = [] try: import cbor2 # noqa: F401 except ImportError: missing.append('cbor2') try: import cryptography # noqa: F401 except ImportError: missing.append('cryptography') else: try: from cryptography.hazmat.primitives.ciphers.aead import AESCCM AESCCM(b"x" * 16, 8) except (cryptography.exceptions.UnsupportedAlgorithm, ImportError): missing.append('a version of OpenSSL that supports AES-CCM') try: import filelock # noqa: F401 except ImportError: missing.append('filelock') try: import ge25519 # noqa: F401 except ImportError: missing.append('ge25519') return missing
def encrypt_message(message, public_key, symetric_key): """ Encrypts a message using a Advance Encryption Standard (AES) key used with the Counter with CBC-MAC (CCM) mode of operation """ if message != None: nonce = os.urandom(12) message = AESCCM(symetric_key).encrypt(nonce, message.encode("iso-8859-1"), None) nonce, *_ = encrypt(public_key, nonce) message = { 'nonce': nonce.decode("iso-8859-1"), 'message': message.decode("iso-8859-1") } return message
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_invalid_nonce_length(self, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) pt = b"hello" nonce = os.urandom(14) with pytest.raises(ValueError): aesccm.encrypt(nonce, pt, None) with pytest.raises(ValueError): aesccm.encrypt(nonce[:6], pt, None)
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_data_too_large(self): key = AESCCM.generate_key(128) aesccm = AESCCM(key) nonce = b"0" * 12 with pytest.raises(OverflowError): aesccm.encrypt(nonce, FakeData(), b"") with pytest.raises(OverflowError): aesccm.encrypt(nonce, b"", FakeData())
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_aesccm_unsupported_on_older_openssl(backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER): AESCCM(AESCCM.generate_key(128))
def test_params_not_bytes(self, nonce, data, associated_data, backend): key = AESCCM.generate_key(128) aesccm = AESCCM(key) with pytest.raises(TypeError): aesccm.encrypt(nonce, data, associated_data)
def test_bad_generate_key(self, backend): with pytest.raises(TypeError): AESCCM.generate_key(object()) with pytest.raises(ValueError): AESCCM.generate_key(129)
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)