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 test_aes(ctx): m = swig.opa_math_common_swig c = swig.opa_crypto_swig BS = 16 for i in range(100): key = os.urandom(BS) a = os.urandom(random.randint(0, BS - 1)) a1_pad = Padding.pad(a, BS) a2_pad = c.pkcs7(a, BS) c1 = AES.new(key, AES.MODE_ECB).encrypt(a1_pad) c2 = c.Aes(key, True).encrypt_raw(a2_pad) print(c1) print(c2) assert c1 == c2 for i in range(100): print(i) key = os.urandom(BS) a = os.urandom(random.randint(60, 100)) a1_pad = Padding.pad(a, BS) a2_pad = c.pkcs7(a, BS) c1 = AES.new(key, AES.MODE_ECB).encrypt(a1_pad) c2 = c.Aes(key, True).encrypt_ecb(a2_pad) print(c1) print(c2) assert c1 == c2 m2_pad = c.Aes(key, False).decrypt_ecb(c2) m2, ok = c.rpkcs7(m2_pad, BS) assert c1 == c2 print(m2, a, m2_pad) assert m2 == a for i in range(100): iv = os.urandom(BS) print(i) key = os.urandom(BS) a = os.urandom(random.randint(60, 100)) a1_pad = Padding.pad(a, BS) a2_pad = c.pkcs7(a, BS) c1 = AES.new(key, AES.MODE_CBC, iv=iv).encrypt(a1_pad) c2 = c.Aes(key, True).encrypt_cbc(a2_pad, iv) print(c1) print(c2) assert c1 == c2 m2_pad = c.Aes(key, False).decrypt_cbc(c2, iv) m2, ok = c.rpkcs7(m2_pad, BS) assert c1 == c2 print(m2, a, m2_pad) assert m2 == a
def encrypt(self, raw, key, iv): enc_key = SHA256.new(key.encode()).digest() cipher = AES.new(enc_key, self.mode, iv) if type(raw) == str: data = Padding.pad(raw.encode('utf-8'), AES.block_size, self.padding_alg) else: data = Padding.pad(raw, AES.block_size, self.padding_alg) bin_encrypted = cipher.encrypt(data) return bin_encrypted
def enkripcija(self, ulaz): ulaz = Padding.pad(ulaz, self.velicina_bloka) # popuni blok izlaz = '' for i in range(len(ulaz) // self.velicina_bloka): # posebno svaki blok izlaz += self.x.encrypt(ulaz[i * self.velicina_bloka:(i + 1) * self.velicina_bloka]) return izlaz
def encrypt(msg, encrypt_key, hash_key): """ Encrypt and hash a message. Args: param msg: Bytes to encrypt param encrypt_key: Base64 encoded encryption key param hash_key: Base64 encoded hash key Returns: Base 64 encoded message """ encrypt_key = base64.b64decode(encrypt_key) hash_key = base64.b64decode(hash_key) padded_msg = Padding.pad(msg, BLOCK_SIZE, style="pkcs7") cipher = AES.new(encrypt_key, AES.MODE_CBC) encrypted_msg = cipher.encrypt(padded_msg) msg_hash = hmac.new(hash_key, cipher.iv + encrypted_msg, digestmod=hashlib.sha256).digest() return base64.b64encode(cipher.iv + encrypted_msg + msg_hash)
def encryptionAES(self, data, nonce): password = "******" key = hasher.sha256(password.encode('utf-8')).digest() data = Padding.pad(data.encode('utf-8'), 16) encryptor = AES.new(key, AES.MODE_CBC, IV=nonce) ciphertext = encryptor.encrypt(data) return ciphertext
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 getDES3(self, key, data, mode=DES3.MODE_ECB, block_size=8, style='pkcs7'): """ DES3加密 :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 """ data = Padding.pad(data.encode('utf-8'), block_size=block_size, style=style) cipher = DES3.new(key.encode('utf-8'), mode=mode) return cipher.encrypt(data)
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 encode(plaintext_string, key, salt): """ AES256 encrypts a string, using provided key & 128bit salt The first 128bits of the returned ciphertext is an exact copy of the provided salt (to facilitate decryption). To store salt separately from the actual ciphertext, simply split off the first 128bits. Keyword Parameter: plaintext_string -- String to be enciphered. key -- Bytes, representing an 256bit AES private key. salt -- Bytes, representing a randomly generated (one-time-use), 128bit long AES Initialization Vector which will be used to salt the resulting ciphertext. >>> key = (b'\\x02\\xd2d\\xfb\\x84Q\\xed?\\x92\\xda\\xcd\\x9a/)' ... b'\\x15\\xdc\\xb5~\\\\\\x03\\xeby\\xa7\\xfb&#\\xb8' ... b'\\xd1y+a\\x86') >>> s = b'\\x94\\x99$y\\x83B\\x85N\\x94E\\x01L\\xe5\\xba\\xea\\xdf' >>> encode("Hello, World!", key, s) b'\\x94\\x99$y\\x83B\\x85N\\x94E\\x01L\\xe5\\xba\\xea\\xdf\\t\\xbc\\x84\\xf8L\\xd5adz\\x1bl\\x9f\\x9c\\x1db\\xb1' """ assert len(key) >= 256 / 8, "Private key must be 256bit, minimum" assert len(salt) == 128 / 8, "Expected (exactly) 128bit long salt" #per dlitz.net/software/pycrypto/api/current/Crypto.Cipher.AES-module.html aes256_cbc = AES.new(key, AES.MODE_CBC, IV=salt) # PKCS#7 CMS pad the input(AES requires input length as multiple of 16 bit) try: plaintext_bytes = plaintext_string.encode('utf-8') except AttributeError: plaintext_bytes = plaintext_string #Seems like it's already bytes padded_plaintext = Padding.pad(plaintext_bytes, 16, style='pkcs7') ciphertext = aes256_cbc.encrypt(padded_plaintext) # store our known-length iv for reuse,by simply prepending to ciphertext return salt + ciphertext #(safe to do) salt just stops rainbow table
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 protect_firmware(infile, outfile, version, message): with open(infile, 'rb') as f: #gets firmware fw = f.read() metadata = struct.pack( "<HH", version, len(fw)) #packs metadata: version, length of unencrypted firmware fw = fw + message.encode() + b'\00' #adds message to end of firmware with open("secret_build_output.txt", 'rb') as sec_output: aes_key = sec_output.read(16) #get symmetric key rsa_key = RSA.import_key(sec_output.read()) #get private key cipher = AES.new(aes_key, AES.MODE_CBC) #creates AES object encrypted_fw = cipher.encrypt(Padding.pad( fw, AES.block_size)) #encrypts firmware metadata += struct.pack( "<H", len(encrypted_fw)) #adds the length of encrypted firmware to metadata hashed_fw = SHA256.new( data=metadata + cipher.iv + encrypted_Fw) #hashes the metadata, IV, and encrypted firmware signature = pkcs1_15.new(rsa_key).sign( hashed_fw) #signs the hashed firmware fw_blob = signature + metadata + cipher.iv + encrypted_fw #creates blob to be sent to bootloader with open(outfile, "w+b") as out: #writes firmware blob to another file out.write(fw_blob) return 0
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(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 _encrypt_data(self, data): """Make data secure.""" if not self._key or data is None: return data return b64encode(self._aes.encrypt(Padding.pad(data.encode(), 16))).decode()
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 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 encrypt(file, key_receiver): """ FUNCION: encrypt(file, key_receiver) ARGS_IN: file - nombre del fichero a encriptar key_receiver - clave publica del receptor DESCRIPCION: cifra un fichero dado por el metodo basado en RSA establecido ARGS_OUT: contenido cifrado (clave, iv, info cifrada - util en enc_sign) """ status = 'OK' # Creacion clave simetrica (de sesion) y vector de inicializacion key_simetric = get_random_bytes(AES_KEY_LEN) init_vector = get_random_bytes(IV_LEN) # Cifrado mensaje with open(file, 'r') as f: cipher_aes = AES.new(key_simetric, AES.MODE_CBC, init_vector) content = Padding.pad(f.read(), 16) ciphertext = cipher_aes.encrypt(content) # Cifrado clave de sesion key = RSA.importKey(key_receiver) cipher_rsa = PKCS1_OAEP.new(key) key_enc = cipher_rsa.encrypt(key_simetric) # Generacion fichero de salida f_name = 'enc_' + file with open(f_name, 'wb') as file_out: file_out.write(key_enc) file_out.write(init_vector) file_out.write(ciphertext) print 'Encriptando', file, '...', status return key_enc + init_vector + ciphertext
def ecb_enc(key, plaintext, ciphertext): #define Encryption function from Crypto import Random from Crypto.Cipher import AES from Crypto.Util import Padding f1 = open(key, 'r') #Opening the key.txt file in read mode sk_hex = f1.read() f1.close() #Closing the key.txt file sk = int(sk_hex, 16).to_bytes(32, byteorder='big') #sk = (f1.read()).strip('\n') #Reading the Secret Key f2 = open(plaintext, 'r') #Opening the plaintext.txt file in read mode message = (f2.readline()).strip('\n') #Reading the PlainText/Message f2.close() #Closing the plaintext.txt file obj = AES.new(sk, AES.MODE_ECB) padded_message = Padding.pad(str.encode(message), 16, 'pkcs7') #print(len((padded_message))) cipher = obj.encrypt(padded_message) cipher_hex = hex(int.from_bytes(cipher, byteorder='big', signed=False)) f4 = open(ciphertext, 'w') #Opening the ciphertext.txt file in write mode f4.write(cipher_hex) #Writing the CipherText f4.close() #Closing the ciphertext.txt file print(cipher) print(cipher_hex) #Printing the CipherText to command prompt
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 _encrypt_request_data(self, data, second_key): key = b'B@41Ner2' + second_key decryptor = AES.new(key, AES.MODE_ECB) data = data.encode('utf-8') data = Padding.pad(data, 16) enc = decryptor.encrypt(data) return base64.standard_b64encode(enc)
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 cbc_encrypt(key, password): if len(key) != 16: print('Error: Key must be 16 bytes') sys.exit(2) if len(password) == 0: print('Error: Password is missing.') sys.exit(2) # generate a random IV and encrypt it in ECB mode iv = Random.get_random_bytes(AES.block_size) cipher_ECB = AES.new(key, AES.MODE_ECB) enc_iv = cipher_ECB.encrypt(iv) # create an AES-CBC cipher object cipher_CBC = AES.new(key, AES.MODE_CBC, iv) # add padding padded_password = Padding.pad(password.encode('utf-8'), AES.block_size) # encrypt the plaintext encrypted_password = cipher_CBC.encrypt(padded_password) encrypted = enc_iv + encrypted_password return encrypted
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 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 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 encrypt(self, input): input = Padding.pad(input, self.block_size) output = b'' for i in range(len(input) // self.block_size): output += self.cypher.encrypt(input[i * self.block_size:(i + 1) * self.block_size]) return output
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 encrypt(key, **kwargs): payload = kwargs.get('FRMPayload').encode() pld_len = len(payload) // 2 payload = Padding.pad(payload, 16) k = math.ceil(pld_len / 16) cryptor = AES.new(key, AES.MODE_ECB) S = b'' for i in range(1, k + 1): kwargs['i'] = '{:0>2x}'.format(i) _A_each = DeviceOp._A(**kwargs) Ai = bytearray.fromhex(_A_each) Si = cryptor.encrypt(Ai) S += Si return b''.join(DeviceOp.bytes_xor(S, payload))[:pld_len * 2 + 1]