def decrypt(input_cipher_string, key, mac_key=None): """ Decrypt the inputted cipher text based on the encryption type. Decrypted plain text will be unpadded before it is returned. Args: :param input_cipher_string: Cipher text to decrypt :param key: Decryption key :param mac_key: (Default = None) MAC key for MAC verification Raises: InvalidMACException: If the cipher string MAC and the calculated MAC do not match, this exception will be raised Returns: bytes: Decrypted plain text in a bytes string """ cipher_string = CipherString.parseString(input_cipher_string) init_vector = base64.b64decode(cipher_string.init_vector) cipher_text = base64.b64decode(cipher_string.cipher_text) mac = None if(cipher_string.mac is not None): mac = base64.b64decode(cipher_string.mac) # AES-CBC-256 if(cipher_string.type is CipherString.TYPE_AESCBC256_B64): cipher = AES.new(key, AES.MODE_CBC, iv=init_vector) plain_text = cipher.decrypt(cipher_text) plain_text = Padding.unpad( plain_text, AES.block_size ) # AES-CBC-256 + HMAC-SHA256 elif(cipher_string.type is CipherString.TYPE_AESCBC256_HMACSHA256_B64): # Verify HMAC first calc_mac = Hash.HMAC.new( mac_key, msg=(init_vector + cipher_text), digestmod=Hash.SHA256 ).digest() if(not Bitwarden.doubleHMACVerify(mac_key, mac, calc_mac)): # These MACs are not the same raise InvalidMACException(mac, calc_mac) # Now decrypt cipher text cipher = AES.new(key, AES.MODE_CBC, iv=init_vector) plain_text = cipher.decrypt(cipher_text) plain_text = Padding.unpad( plain_text, AES.block_size ) # Other Cipher Types else: # TODO: Implement other cipher types plain_text = cipher_string return plain_text
def decode(salted_ciphertext_bytes, key): """ Decrypts an AES256 enciphered String via provided key & 128bit salt Keyword Parameter: salted_ciphertext_bytes -- Bytes, representing a randomly generated (one-time-use) 128bit long AES Initialization Vector & an AES256 encyphered String which was salted with the one-time IV. The first 128bits of 'salted_ciphertext_bytes' represent the salt, with remainder containing the encoded cyphertext. key -- Bytes, representing an 256bit AES private key. >>> key = (b'\\x02\\xd2d\\xfb\\x84Q\\xed?\\x92\\xda\\xcd\\x9a/)' ... b'\\x15\\xdc\\xb5~\\\\\\x03\\xeby\\xa7\\xfb&#\\xb8' ... b'\\xd1y+a\\x86') >>> ciphertext = (b'\\x94\\x99$y\\x83B\\x85N\\x94E\\x01L\\xe5\\xba' ... b'\\xea\\xdf\\t\\xbc\\x84\\xf8L\\xd5adz\\x1bl' ... b'\\x9f\\x9c\\x1db\\xb1') >>> decode(ciphertext, key) 'Hello, World!' """ assert len(key) >= 256 / 8, "Private key must be 256bit, minimum" # per convention for this Module, the first 128 ciphertext bits represent # the randomly generated Initialization Vector used during encryption salt_byte_length = int(128 / 8) salt = salted_ciphertext_bytes[:salt_byte_length] ciphertext = salted_ciphertext_bytes[salt_byte_length:] #per dlitz.net/software/pycrypto/api/current/Crypto.Cipher.AES-module.html aes256_cbc = AES.new(key, AES.MODE_CBC, IV=salt) padded_plaintext_bytes = aes256_cbc.decrypt(ciphertext) plaintext_bytes = Padding.unpad(padded_plaintext_bytes, 16, style='pkcs7') return plaintext_bytes.decode('utf-8')
def decrypt(self, cipherPacket, key): iv, cipherText = self._splitCipherBytes(cipherPacket) print(cipherText) aesCipher = AES.new(key, AES.MODE_CBC, iv=iv) decipheredText = aesCipher.decrypt(cipherText) plainText = Padding.unpad(decipheredText, 16).decode() return plainText
def decrypt(self, raw): try: decoded = base64.b64decode(raw) decrypted = self.cipher.decrypt(decoded) return str(Padding.unpad(decrypted, self.bs), 'utf-8') except (TypeError, ValueError): raise ValueError('Dữ liệu không hợp lệ')
def decrypt(self, encrypted): encrypted = base64.b64decode(encrypted) iv = encrypted[:AES.block_size] cipher = AES.new(self.key, AES.MODE_EAX, iv) data = Padding.unpad(cipher.decrypt(encrypted[AES.block_size:]), AES.block_size, "pkcs7") return data.decode("utf-8")
def _decrypt_data(self, data): """Make data readable.""" if not self._key or data is None: return data return Padding.unpad( self._aes.decrypt(b64decode(data)), 16).decode()
def decrypt(ciphertext: bytes, key: bytes, iv: bytes) -> bytes: """ Decrypt the `ciphertext` with AES-CBC algorithm. `key` and `iv` are exactly the same as `encrypt`. **Note that the return type is `bytes`.** """ cipher = AES.new(key, AES.MODE_CBC, iv=iv) return Padding.unpad(cipher.decrypt(ciphertext), 16)
def decrypt_string_003(self, string_to_decrypt, encryption_key, auth_key, uuid): components = string_to_decrypt.split(':') if len(components) == 6: version, auth_hash, local_uuid, IV, ciphertext, auth_params = components else: version, auth_hash, local_uuid, IV, ciphertext = components if local_uuid != uuid: print('Note UUID does not match.') print('This could be caused by a conflicted copy of a note.') print('Rename or delete the conflicted copy to fix.') print('Could also be a sign of tampering. Exiting for security...') logging.debug('UUID: {}, Local UUID: {}'.format(uuid, local_uuid)) sys.exit(1) string_to_auth = ':'.join([version, uuid, IV, ciphertext]) local_auth_hash = hmac.new(unhexlify(auth_key), string_to_auth.encode(), 'sha256').digest() auth_hash = unhexlify(auth_hash) if not hmac.compare_digest(local_auth_hash, auth_hash): print('Auth hash does not match. This could indicate tampering or ' 'that something is wrong with the server. Exiting.') logging.debug('Auth Hash: {}, Local Auth Hash: {}'.format( auth_hash, local_auth_hash)) sys.exit(1) cipher = AES.new(unhexlify(encryption_key), AES.MODE_CBC, unhexlify(IV)) result = cipher.decrypt(b64decode(ciphertext)) result = Padding.unpad(result, AES.block_size).decode() return result
def decrypt(self, bin_encrypted, key, iv): dec_key = SHA256.new(key.encode()).digest() cipher = AES.new(dec_key, self.mode, iv) decrypted = cipher.decrypt(bin_encrypted) bin_data = Padding.unpad(decrypted, AES.block_size, self.padding_alg) # return binary data return bin_data
def decodeDES(self, key, data, mode=DES.MODE_ECB, block_size=8, style='pkcs7'): """ DES解密 :param key: 秘钥key :param data: 未加密数据 :param mode: 加密模式 :var MODE_ECB: :ref:`Electronic Code Book (ECB) <ecb_mode>` :var MODE_CBC: :ref:`Cipher-Block Chaining (CBC) <cbc_mode>` :var MODE_CFB: :ref:`Cipher FeedBack (CFB) <cfb_mode>` :var MODE_OFB: :ref:`Output FeedBack (OFB) <ofb_mode>` :var MODE_CTR: :ref:`CounTer Mode (CTR) <ctr_mode>` :var MODE_OPENPGP: :ref:`OpenPGP Mode <openpgp_mode>` :var MODE_EAX: :ref:`EAX Mode <eax_mode>` :param block_size: 填充block大小:默认为8 :param style: 填充算法:‘pkcs7’(default),‘iso7816’or‘x923’ :return: 解密结果 byte string """ cipher = DES.new(key.encode('utf-8'), mode=mode) plaintext = cipher.decrypt(data) plaintext = Padding.unpad(plaintext, block_size=block_size, style=style) return plaintext
def decrypt(self, message): cipher = AES.new(self.key, self.mode, self.key) plain_text = cipher.decrypt(message) try: return Padding.unpad(plain_text, 16) except ValueError: return plain_text
def decrypt(key, iv, data): try: cryptor = AES.new(key, AES.MODE_CBC, iv) new = Padding.unpad(cryptor.decrypt(data), 16) return new except Exception as e: return print(f'AESCBC.decrypt : {str(e)}')
def DecryptStringForNCX(self, s: str): cipher = AES.new(b'libcckeylibcckey', AES.MODE_CBC, iv=b'libcciv libcciv ') padded_plaintext = cipher.decrypt(bytes.fromhex(s)) return Padding.unpad(padded_plaintext, AES.block_size, stype='pkcs7').decode('ascii')
def decrypt_string_003(self, string_to_decrypt, encryption_key, auth_key, uuid): components = string_to_decrypt.split(':') if len(components) == 6: version, auth_hash, local_uuid, IV, ciphertext, auth_params = components else: version, auth_hash, local_uuid, IV, ciphertext = components if local_uuid != uuid: print('UUID does not match. This could indicate tampering or ' 'that something is wrong with the server. Exiting.') sys.exit(1) string_to_auth = ':'.join([version, uuid, IV, ciphertext]) local_auth_hash = hmac.new(unhexlify(auth_key), string_to_auth.encode(), 'sha256').digest() auth_hash = unhexlify(auth_hash) if not hmac.compare_digest(local_auth_hash, auth_hash): print('Auth hash does not match. This could indicate tampering or ' 'that something is wrong with the server. Exiting.') sys.exit(1) cipher = AES.new(unhexlify(encryption_key), AES.MODE_CBC, unhexlify(IV)) result = cipher.decrypt(b64decode(ciphertext)) result = Padding.unpad(result, AES.block_size).decode() return result
def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) data = Padding.unpad(cipher.decrypt(enc[AES.block_size:]), AES.block_size, 'pkcs7') return data.decode('utf-8')
def _get_authentication_key_data(file_path, pin): """Open the auth key file""" from resources.lib.kodi import ui # Keep these imports within the method otherwise if the packages are not installed, # the addon crashes and the user does not read the warning message try: # The crypto package depends on the library installed (see Wiki) from Crypto.Cipher import AES from Crypto.Util import Padding except ImportError: from Cryptodome.Cipher import AES from Cryptodome.Util import Padding try: file_content = load_file(file_path) iv = '\x00' * 16 cipher = AES.new((pin + pin + pin + pin).encode("utf-8"), AES.MODE_CBC, iv.encode("utf-8")) decoded = Padding.unpad(padded_data=cipher.decrypt(base64.b64decode(file_content)), block_size=16) return json.loads(decoded.decode('utf-8')) except ValueError: # ValueError should always means wrong decryption due to wrong key ui.show_ok_dialog(get_local_string(30342), get_local_string(30106)) return '' except Exception as exc: # pylint: disable=broad-except LOG.warn('Exception raised: {}', exc) ui.show_ok_dialog(get_local_string(30342), get_local_string(30343)) return None
def decrypt_aes_cbc(self, encrypted, key, iv): key = AESCipher.mk_bytes(key) iv = AESCipher.mk_bytes(iv) res = AES.new(key, AES.MODE_CBC, iv=iv).decrypt(encrypted) res = Padding.unpad(res, AES.block_size) return res
def decrypt(self, cypher_text): # decypher = DES3.new(key, des_mode, iv) decrypted_output = b'' for i in range(len(cypher_text) // self.block_size): decrypted_output += self.cypher.decrypt( cypher_text[i * self.block_size:(i + 1) * self.block_size]) return Padding.unpad(decrypted_output, self.block_size)
def cbc_decrypt(key, encrypted): if len(key) == 0: print('Error: Enter key') sys.exit(2) if len(encrypted) == 0: print('Error: No password to decrypt') sys.exit(2) enc_iv = encrypted[:AES.block_size] encrypted_password = encrypted[AES.block_size:] # decrypt iv using AES_ECB cipher_ECB = AES.new(key, AES.MODE_ECB) iv = cipher_ECB.decrypt(enc_iv) # create AES-CBC cipher object cipher_CBC = AES.new(key, AES.MODE_CBC, iv) # decrypt ciphertext padded_password = cipher_CBC.decrypt(encrypted_password) password = Padding.unpad(padded_password, AES.block_size) password = password.decode('utf-8') return password
def decode_files(mode, key, files): try: total_files = len(files) for i, file_path in enumerate(files, start=1): print("{}/{}: Decoding {} ...".format(i, total_files, file_path)) with open(file_path, mode='rb') as file: file_bytes = file.read() nonce, ciphertext = file_bytes.split(SEPARATOR, maxsplit=1) if mode in IV_MODES: iv = nonce nonce = None else: iv = None plain = decode(mode, key, ciphertext, iv=iv, nonce=nonce) output_path = file_path.replace('.aes', '') with open(output_path, mode='wb') as file: try: file.write( Padding.unpad(plain, AES.block_size, style='iso7816')) except ValueError: file.write(plain) print("Successfully decoded into {}".format(output_path)) except ValueError as e: print( "There was problem with decryption: {}, make sure proper key and mode of operation is provided, " "program will now close".format(e)) return except FileNotFoundError as e: print("File '{}' not found, program will now close".format(e.filename)) return
def decrypt_message(ifIncrease, msg, statefile, sharedkey, pubkey): rcv = read_state(statefile) ## If message number is not greater than the one in our state file, do not decrypt # Seperate parts of the message sqn = msg[0:4] signature = msg[4:4 + 256] nonce = msg[260:260 + AES.block_size] cipher_text = msg[260 + AES.block_size:] # Verify Sqn number if (verify_sqn(sqn, rcv) is False): return ("Sequence number verification failed") content = sqn + nonce + cipher_text is_verified = verify_signature(content, signature, pubkey) if (is_verified == False): print("Verification failed") return # Create AES CIPHER cipher = AES.new(sharedkey, AES.MODE_CBC, nonce) # decrypt ciphertext plaintext = cipher.decrypt(cipher_text) plain = Padding.unpad(plaintext, AES.block_size, style='pkcs7') # plaintext = unpad(plaintext, AES.block_size) update_state(statefile, rcv) return (plain.decode('utf-8'))
def hybrid_decrypt(self, participant_address, enc_msg): #get private keypair from keyfile kfile = open( NET_PATH + '/' + participant_address + '/keypairs/rsa-key.pem', 'r') keystr = kfile.read() kfile.close() privkey = RSA.import_key(keystr) #parse the encrypted text from the encrypted AES key enc_payload = enc_msg[0:len(enc_msg) - 131] enc_key = enc_msg[-128:] #initialize RSA cipher to get decrypted AES key (private key) cipher = PKCS1_OAEP.new(privkey) key = cipher.decrypt(enc_key) #initialize AES cipher iv = b'\x00' * AES.block_size cipher = AES.new(key, AES.MODE_CBC, iv) #get plaintext payload = cipher.decrypt(enc_payload) payload = Padding.unpad(payload, AES.block_size) return payload
def recv_stream_transfer(file_path, chunk_size, connection): '''Receive file using stream protocol. Recieves chunks of size X using connection, and then writes them to new file at file_path. The end is padded.''' total_length = chunk_size + 32 aes_key = get_random_bytes(24) share_key(aes_key, connection) with open(file_path, mode='wb') as local_file: while True: message = connection.recv(total_length) aes_nonce = message[:16] tag = message[16:32] message = message[32:] aes_cipher = AES.new(aes_key, AES.MODE_GCM, nonce=aes_nonce) decrypted_msg = aes_cipher.decrypt_and_verify(message, tag) #decrypted_msg = b'' #for chunk in range(round(chunk_size/16)): # to_decrypt = message[chunk * 16: (chunk_size + 1) * 16] # if chunk == 0: # decrypted_msg += aes_cipher.decrypt_and_verify(to_decrypt, tag) # else: # decrypted_msg += aes_cipher.decrypt(to_decrypt) if message != b'0': local_file.write(Padding.unpad(decrypted_msg, 16)) if len(message) < 512: break
def decrypt(key, encrypted_data): cipher = AES.new(key, AES.MODE_ECB) data_encrypted_decoded = base64.b64decode(encrypted_data) data_decrypted = cipher.decrypt(data_encrypted_decoded) data = Padding.unpad(data_decrypted, BLOCKSIZE) data = data.decode('utf-8') return data
def aes_decrypt(self, data: bytes): cipher = AES.new(self.aes_key, AES.MODE_CBC, self.aes_iv) try: return Padding.unpad(cipher.decrypt(data), 16) except ValueError: raise CryptoError( 'Decryption failed while trying to un pad. (probably bad decryption key/iv)' )
def aes_decrypt(data: bytes, key: bytes, mode: str = 'cbc', iv=None) -> bytes: """ AES 解密 """ if not iv: iv = key cipher = AES.new(key, AES_MODE_MAPPING.get(mode, AES.MODE_CBC), iv=iv) return Padding.unpad(cipher.decrypt(data), AES.block_size)
def decrypt_message(message, date): byte_key = Encryption.get_key(date).encode() w = DES.new(byte_key, DES.MODE_CBC, byte_key) message = base64.b64decode(message.replace("-", "+").encode()) message = w.decrypt(message) message = Padding.unpad(message, 8, 'pkcs7').decode() return message
def decrypt_aes_cbc_src(encrypted, key, iv, bits=256): """使用 key 和 iv 原始字符解密""" key = AESCipher.mk_key(key, int(bits / 8)) iv = AESCipher.mk_key(iv, AES.block_size) res = AES.new(key, AES.MODE_CBC, iv=iv).decrypt(encrypted) res = Padding.unpad(res, AES.block_size) return res
def __DecryptContents(self, contents: bytes, contentKeyBase64: str) -> bytes: contentKey = base64.b64decode(contentKeyBase64) keyAes = AES.new(self.DeviceIdUserIdKey, AES.MODE_ECB) decryptedContentKey = keyAes.decrypt(contentKey) contentAes = AES.new(decryptedContentKey, AES.MODE_ECB) decryptedContents = contentAes.decrypt(contents) return Padding.unpad(decryptedContents, AES.block_size, "pkcs7")
def decryptAES(key, mess): iv = mess[:AES.block_size] encs = mess[AES.block_size:] h = SHA256.new() h.update(key.encode()) hashed_password = h.hexdigest() key = hashed_password[:16] cipher = AES.new(key.encode(), AES.MODE_CBC, iv) return Padding.unpad(cipher.decrypt(encs), 128, style='iso7816')