Below is a test. When I try to decode the same string for the second time I get a error message and I really have no clue why or where to search for. Please advise.
Error:
Traceback (most recent call last):
File "test.py", line 28, in <module>
telnr_to_string = str(telnr_decrypt, 'utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9e in position 0: invalid start byte
Code:
from Crypto.Cipher import AES
from Crypto.Util.Padding import *
from urllib.request import urlopen
import os
import urllib
import subprocess
import re
import time
import base64
import random
file_key = open("key.txt")
key = file_key.read()
key = key.encode()
file_iv = open("iv.txt")
iv = file_iv.read()
iv = iv.encode()
obj2 = AES.new(key, AES.MODE_CBC, iv)
z=1
while z < 3:
x=''
telnr_decrypt=''
telnr=''
telnr_to_string=''
telnr_cleaned=''
x=(b'\x9e\xde\x98p:\xa3\x04\x92\xb5!2K[\x8e\\\xee')
telnr_decrypt = obj2.decrypt(x)
telnr_to_string = str(telnr_decrypt, 'utf-8')
telnr_cleaned = re.sub("[^0-9]", "", telnr_to_string)
print (telnr_cleaned)
z=z+1
Just move obj2 = AES.new(key, AES.MODE_CBC, iv) into the while loop. Don't worry, cipher objects are not very stateful objects; they don't do much other than to store the key (or, for AES, probably the internal subkeys) and maintain a small buffer. Generally it is therefore a bad idea to reuse or cache them.
If you call encrypt / decrypt multiple times in succession then the methods act as if you would be encrypting one big message. In other words, they allow you to encryption / decrypt in a piecemeal fashion so that message-sized buffers can be avoided. This is not very explicitly documented, but you can see this in figure 2 in the documentation.
For CBC mode it means that the operation is identical to setting the IV to the last block of ciphertext. If the IV is wrong then the first block of plaintext will be randomized. Random bytes do generally not contain valid UTF-8 encoding, which means that decoding to string will (likely) fail.
Related
I'm new to encryption/decryption, but I have sensitive data that I need to store as encrypted data. Our ETL has a built in encryption process which outputs the following
{
"data":{
"transformation":"AES/GCM/noPadding",
"iv":"jlemHiOD8uiyMsqY",
"type":"JSON",
"ciphertext":"TOtsmTYG1jKCZXewFNPBk5xWf+q4AO8OSZPoYw==",
"key_params":{
"symmetric":{
"key_algorithm":"AES"
}
}
}
}
From here, I'd like to use pycryptodome to decrypt the data when I need to consume the data. I am trying to run the following python script to decrypt but am running into some errors. I think it has to do with how the data is formatted?
import pandas as pd
from Crypto.Cipher import AES
test_encrypted_value = TOtsmTYG1jKCZXewFNPBk5xWf+q4AO8OSZPoYw==
aes_iv = 'jIemHiOD8uiyMsqY'
aes_key = '4E645267556B586E3272357538782F41'
cipher = AES.new(aes_key, AES.MODE_GCM, aes_iv)
error - TypeError: Nonce must be bytes, bytearray or memoryview
If I remove the IV, I also get an error on the key passed. Which leads me to think I am passing the wrong data type/format.
error - TypeError: Object type <class 'str'> cannot be passed to C code
UPDATE
Per the responses, I updated my code to transform data format. Additionally, I changed my example and saved the expected value. I am expecting the decrypted value to be 158100.
import pandas as pd
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
import codecs
import base64
test_encrypted_value = 'SUXiDF6Dgtc8y3eY8Euqi/IYbSlQquLJAUKmZw=='
aes_iv = 'lMF2Jrruo9rR57Uy'
aes_key = '4E645267556B586E3272357538782F41'
byte_key = codecs.decode(aes_key, 'hex_codec')
base64_iv = base64.b64decode(aes_iv)
base64_encrypted_value = base64.b64decode(test_encrypted_value)
cipher = AES.new(byte_key, AES.MODE_GCM, base64_iv)
plaintext = cipher.decrypt(ciphertext)
print(plaintext.decode())
I am now getting the below error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb9 in position 1: invalid start byte
For what it's worth, encryption is through snaplogic 'Encrypt Field' found here - https://docs-snaplogic.atlassian.net/wiki/spaces/SD/pages/1438346/Encrypt+Field
I am also generating the AES key at the following link with the 128-bit and HEX option set - https://www.allkeysgenerator.com/Random/Security-Encryption-Key-Generator.aspx
You need to pass the data in bytes format. Your aes_iv and test_encrypted_value is in the base64 format, while your aes_key is in the hex format. In order to use it, you must first convert those to bytes.
byte_key = codecs.decode(aes_key, 'hex_codec')
base64_iv = base64.b64decode(aes_iv)
base64_encrypted_value = base64.b64decode(test_encrypted_value)
I have been struggling with this for hours. I have the following production code (parsed out for simplicity) that runs just fine in Python 2.7:
import hashlib
import hmac
string1 = 'firststring'
string2 = 'secondstring'
digest = hmac.new(key=string1, msg=string2, digestmod=hashlib.sha256).digest()
print('hmac_digest = ' + digest) # digest is a string
The output is a string like so:
hmac_digest = �!�Ni��I.u�����x�l*>a?. �
But when I run this with Python3.7, I get the following error:
Traceback (most recent call last):
File "/home/xxxx/work/py23.py", line 7, in <module>
digest = hmac.new(key=string1, msg=string2, digestmod=hashlib.sha256).digest()
File "/usr/lib/python3.7/hmac.py", line 153, in new
return HMAC(key, msg, digestmod)
File "/usr/lib/python3.7/hmac.py", line 49, in __init__
raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'str'
Process finished with exit code 1
After a quite a bit of research I understood that hmac has changed in 3.4 and beyond. Therefore I redid my code to the following:
import hashlib
import hmac
import base64
string1 = 'firststring'
string2 = 'secondstring'
digest = hmac.new(key=string1.encode('utf-8'), msg=string2.encode('utf-8'), digestmod=hashlib.sha256).digest()
digest = base64.encodebytes(digest).decode('utf-8') # need to convert to string
print('hmac_digest = ' + digest)
But the output I get is completely different!
hmac_digest = 5CEZhgMDTmmFxkkudbGPxaLSytl4+gdsKj4PYT8uAJk=
How do I correctly port this code to python3.7 so I get the exact same output as 2.7?
Thanks in advance!
The issue you're hitting is that in Python 2, strings are effectively just bytes, while in Python 3 strings are unicode strings, and there is a new bytes data type for raw bytes. You can read more about the issues involved in the Python 3 porting guide (and elsewhere).
The minimal set of changes to get your code to work is probably something like this:
import hashlib
import hmac
string1 = 'firststring'.encode('utf-8')
string2 = 'secondstring'.encode('utf-8')
digest = hmac.new(key=string1, msg=string2, digestmod=hashlib.sha256).digest()
print('hmac_digest = ' + repr(digest)) # digest is a string
This will output:
hmac_digest = b'\xe4!\x19\x86\x03\x03Ni\x85\xc6I.u\xb1\x8f\xc5\xa2\xd2\xca\xd9x\xfa\x07l*>\x0fa?.\x00\x99'
We're printing out the repr() of the hmac because it's just a collection of bytes. If you really wanted to print this out you would normally convert it to a hex string:
digest = hmac.new(key=string1, msg=string2, digestmod=hashlib.sha256).hexdigest()
Which would result in:
hmac_digest = 'e421198603034e6985c6492e75b18fc5a2d2cad978fa076c2a3e0f613f2e0099'
Thanks to Josh Lee for his answer in UnicodeDecodeError, invalid continuation byte
His suggestion about using 'latin-1' to decode the digest output solved the problem for me!
Here's how my code looks in Python 3.7 now and gives me the exact same output as my code in Python 2.7:
import hashlib
import hmac
string1 = 'firststring'.encode('utf-8') # can use 'latin-1'
string2 = 'secondstring'.encode('utf-8') # can use 'latin-1'
digest = hmac.new(key=string1, msg=string2, digestmod=hashlib.sha256).digest()
print('hmac_digest = ' + digest.decode('latin-1')) # Use only 'latin-1' to decode because 'utf-8' or 'ascii' will throw a UnicodeDecodeError
I'm using Laravel's encryptString method to encrypt some data on my website. This uses OpenSSL's 256-bit AES-CBC encryption without any serialization. I'm now trying to decrypt that data in Python but I keep getting errors about key length and can't seem to figure out why.
Example data to decrypt: eyJpdiI6ImdxY0VcLzFodmpISFV4allSWmJDdEpRPT0iLCJ2YWx1ZSI6IkxXd0ZJaUd2bTUweW5pNm0wUjQwOFM2N1wvWEs5SlYrNB4xNlR7Qkh1U3FvPSIsIm1hYyI6Ijc5ZWM0YTYxYjljZGFiNzgwNjY2NDU1ZmQ5Yjc1ZmJlOGU4NzBkMjQzMzA3MmVhYzE3NzY4ZmU1MWIyMjZlOTQifQ==
Example Key to use for decryption (from laravel .env):
base64:/AZejP0lh3McL/+Vy5yZcADdTcR65qnx5Jqinuw7raK=
I changed those values around so actually decrypting with those values won't give any real data, just figured it'd be good for example. I then try to decrypt this data in Python 3.7 with:
import base64
from Crypto.Cipher import AES
def decrypt(enc, key):
IV = 16 * '\x00'
decobj = AES.new(key, AES.MODE_CBC, IV)
data = decobj.decrypt(base64.b64decode(enc))
print(str(data.decode()))
if __name__ == "__main__":
key = b"/AZejP0lh3McL/+Vy5yZcADdTcR65qnx5Jqinuw7raK="
decrypt("eyJpdiI6ImdxY0VcLzFodmpISFV4allSWmJDdEpRPT0iLCJ2YWx1ZSI6IkxXd0ZJaUd2bTUweW5pNm0wUjQwOFM2N1wvWEs5SlYrNB4xNlR7Qkh1U3FvPSIsIm1hYyI6Ijc5ZWM0YTYxYjljZGFiNzgwNjY2NDU1ZmQ5Yjc1ZmJlOGU4NzBkMjQzMzA3MmVhYzE3NzY4ZmU1MWIyMjZlOTQifQ==", key)
And it seems like this should work, but when I run it I get the error: ValueError: Incorrect AES key length (60 bytes) so I'm not sure what I'm doing wrong. I've tried padding/unpadding the data/key but that doesn't seem to change anything. I'm wondering if I'm getting the wrong key to use for decryption from Laravel, but from what I could tell in the linked documentation, it should just be the APP_KEY in my .env file.
If anyone could help me or point me in the right direction, that would be amazing!
This question is unique to other similar questions because I'm trying to figure out primarily if I'm getting the correct AES key from Laravel, I don't actually overly need help decrypting, I just think I'm grabbing the wrong key from Laravel.
EDIT: New code that seems like it works:
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
def decrypt(enc, key):
IV = 16 * '\x00'.encode()
decobj = AES.new(key, AES.MODE_CBC, IV)
data = decobj.decrypt(pad(base64.b64decode(enc), 16))
print(base64.b64decode(data))
if __name__ == "__main__":
key = base64.b64decode(b"/AZejP0lh3McL/+Vy5yZcADdTcR65qnx5Jqinuw7raK=")
decrypt("eyJpdiI6ImdxY0VcLzFodmpISFV4allSWmJDdEpRPT0iLCJ2YWx1ZSI6IkxXd0ZJaUd2bTUweW5pNm0wUjQwOFM2N1wvWEs5SlYrNB4xNlR7Qkh1U3FvPSIsIm1hYyI6Ijc5ZWM0YTYxYjljZGFiNzgwNjY2NDU1ZmQ5Yjc1ZmJlOGU4NzBkMjQzMzA3MmVhYzE3NzY4ZmU1MWIyMjZlOTQifQ==", key)
The print statement now prints some bytes, but when I run .decode() on it I get the error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfa in position 0: invalid start byte and can't seem to figure out what I need to do to make it be able to be printed as a string.
Question: ...trying to decrypt that data in Python but I keep getting errors about key length
I can use your key, in the code of the linked answer, after doing .b64decode(....
The example code .encode(... and decode(... works as expecte.
Conclusion: There is nothing wrong, with your Key!
key = b"/AZejP0lh3McL/+Vy5yZcADdTcR65qnx5Jqinuw7raK="
key = base64.b64decode(key)
But with your code, I got TypeError, related to the IV parameter:
expect_byte_string(iv)
File "/usr/local/lib/python3.4/dist-packages/Crypto/Util/_raw_api.py", line 172, in expect_byte_string
TypeError: Only byte strings can be passed to C code
Fixed with IV = 16 * '\x00'.encode(), results in ValueError, related to enc:
data = decobj.decrypt(base64.b64decode(enc))
File "/usr/local/lib/python3.4/dist-packages/Crypto/Cipher/_mode_cbc.py", line 209, in decrypt
ValueError: Error 3 while decrypting in CBC mode
This leads to github issues:10
Error 3 means "ERR_NOT_ENOUGH_DATA"
According to the linked GitHub page, you have to reread the documentation, about padding data while you are encoding.
Working example from GitHub:
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
key = b"/AZejP0lh3McL/+Vy5yZcADdTcR65qnx5Jqinuw7raK="
key = base64.b64decode(key)
BLOCK_SIZE = 32
encryption_suite = AES.new(key, AES.MODE_CBC, b'This is an IV...')
cipher_text = encryption_suite.encrypt(pad(b'A really secret message...', BLOCK_SIZE))
decryption_suite = AES.new(key, AES.MODE_CBC, b'This is an IV...')
print(unpad(decryption_suite.decrypt(cipher_text), BLOCK_SIZE).decode())
>>> A really secret message...
Tested with Python: 3.4.2
Full Working Code with MAC Validation
Adding to Gonzalo's submission, Laravel's encrypted message is a base64 json-encoded array consisting of the following key pairs:
[
'iv' => 'generated initialization vector (iv)',
'value' => 'encrypted, base64ed, signed value',
'mac' => 'message authentication code (mac)'
]
The 'value' is signed using a message authentication code (MAC) to verify that the value has not changed during transit.
The MAC extracted from the payload (encrypted message) should be checked against the
mac extracted from the 'value' (this can be done using the key, iv, and value). Laravel's encryption scheme can be found on GitHub: src/Illuminate/Encryption/Encrypter.php
Referencing a discussion thread on Laravel, I traced a partial solution on Github: orian/crypt.py (which is a fork of fideloper/crypt.py).
I have forked off of Orian's code and fixed an input parameter issue. The code works as expected as long as the encryption key (passed in as an input to decrypt()) is base64 decoded and does not include the 'base64:' that is typically prepended to the APP_KEY environmental variable string assignment found in the .env file.
Solution: pilatuspc12ng/crypt.py
The code snippet of the crypt.py is shown below:
import base64
import json
from Crypto.Cipher import AES
from phpserialize import loads
import hashlib
import hmac
def decrypt(payload, key):
"""
Decrypt strings that have been encrypted using Laravel's encrypter (AES-256 encryption).
Plain text is encrypted in Laravel using the following code:
>>> ciphertext = Crypt::encrypt('hello world');
The ciphertext is a base64's json-encoded array consisting of the following keys:
[
'iv' => 'generated initialization vector (iv)',
'value' => 'encrypted, base64ed, signed value',
'mac' => 'message authentication code (mac)'
]
The 'value' is signed using a message authentication code (MAC) so verify that the value has not changed during
transit.
Parameters:
payload (str): Laravel encrypted text.
key (str): Encryption key (base64 decoded). Make sure 'base64:' has been removed from string.
Returns:
str: plaintext
"""
data = json.loads(base64.b64decode(payload))
if not valid_mac(key, data):
return None
value = base64.b64decode(data['value'])
iv = base64.b64decode(data['iv'])
return unserialize(mcrypt_decrypt(value, iv, key)).decode("utf-8")
def mcrypt_decrypt(value, iv, key):
AES.key_size=128
crypt_object=AES.new(key=key,mode=AES.MODE_CBC,IV=iv)
return crypt_object.decrypt(value)
def unserialize(serialized):
return loads(serialized)
def valid_mac(key, data):
dig = hmac.new(key, digestmod=hashlib.sha256)
dig.update(data['iv'].encode('utf8'))
dig.update(data['value'].encode('utf8'))
dig = dig.hexdigest()
return dig==data['mac']
I notice this haven't been active for a while but I'm trying to do the same and can't seem to make it work.
What I noticed is that the encoded password string stored by Laravel is a base 64 encoded json object, which wasn't taken into consideration in the original question:
pass_obj = base64.b64decode('eyJpdiI6ImdxY0VcLzFodmpISFV4allSWmJDdEpRPT0iLCJ2YWx1ZSI6IkxXd0ZJaUd2bTUweW5pNm0wUjQwOFM2N1wvWEs5SlYrNB4xNlR7Qkh1U3FvPSIsIm1hYyI6Ijc5ZWM0YTYxYjljZGFiNzgwNjY2NDU1ZmQ5Yjc1ZmJlOGU4NzBkMjQzMzA3MmVhYzE3NzY4ZmU1MWIyMjZlOTQifQ==')
print(pass_obj)
>>> b'{"iv":"gqcE\\/1hvjHHUxjYRZbCtJQ==","value":"LWwFIiGvm50yni6m0R408S67\\/XK9JV+4\x1e16T{BHuSqo=","mac":"79ec4a61b9cdab780666455fd9b75fbe8e870d2433072eac17768fe51b226e94"}'
From that you can get the IV and the encrypted value, both seem to be base64 encoded. But I still get a decoding error at the end like;
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfa in position 0: invalid start byte
Here is my complete code;
password = 'eyJpdiI6ImJGNDNNZjN3YWtpcDQ5VEJVXC9IazF3PT0iLCJ2YWx1ZSI6IkNVRW1VQUY1dXArYlFkU3NlY1pnZUE9PSIsIm1hYyI6ImM3ODk0NWQ0NjgxMzM4YjE0M2JhN2MzZWRmOWEwMWJiMjI2Y2FhYmUxYjFhYzAyYjY4YWZkZGE3N2EyMDYwNWYifQ=='
key = 'some secret key that i can't share'.encode()
p_obj = json.loads(base64.b64decode(password).decode())
decobj = AES.new(key, AES.MODE_CBC, base64.b64decode(p_obj['iv']))
data = decobj.decrypt(base64.b64decode(p_obj['value']))
print(data)
>>> b'l\xee:f\x9eZ\x90rP\x99\xca&#\x1d1\x9f'
data.decode()
>>> Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xee in position 1: invalid continuation byte
#Pecans did you ever figure this out?
Thank you.
Full working code EDIT
I fugured it out, I had a problem with my key initially. So here's the full snippet for future reference;
import base64
import json
from phpserialize import unserialize
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
key = b'my secret key'
enc_pass = 'eyJpdiI6ImJGNDNNZjN3YWtpcDQ5VEJVXC9IazF3PT0iLCJ2YWx1ZSI6IkNVRW1VQUY1dXArYlFkU3NlY1pnZUE9PSIsIm1hYyI6ImM3ODk0NWQ0NjgxMzM4YjE0M2JhN2MzZWRmOWEwMWJiMjI2Y2FhYmUxYjFhYzAyYjY4YWZkZGE3N2EyMDYwNWYifQ=='
p_obj = json.loads(base64.b64decode(password).decode())
decobj = AES.new(key, AES.MODE_CBC, base64.b64decode(p_obj['iv']))
data = decobj.decrypt(base64.b64decode(p_obj['value']))
dec_pass = unserialize(unpad(data, 16)).decode()
You will have the decrypted password in dec_pass.
Note that sometimes Laravel generates the key in base64. In that case the string will be something like base64:sdfsdjfhjsdf32, then you have to decode first.
Cheers!
I have to decrypt Data with AES in CBC Mode and Zero-Byte-Padding.
Heres my Code (similar to the one in the Documentation):
from Cryptodome.Cipher import AES
from base64 import b64decode
from Cryptodome.Util.Padding import unpad
key = b64decode('QkFDR0FubzR0WkdIUkp2WQ==')
iv = b64decode('zBN6M2DMdbAsLcSc')
ct = b64decode('Ie+LMEUM66aEDJkKI61i0+Frh/g9xA8Pb7FR1bVSLohl21V4BHo1ZH7BSNkClaPy/ejKw8r6lDFhUuIzu2JfNHn3W9h6sdM3ZiSniBNQP/dFrhrmc3I7xuZIvfTQqoyV6/DsFSZnyoObrCeF7Wi3VvPnNk9f3/PCQ2hAXPiA1soA05ALkGRgBPen8kxm8NEUTxogc8kSQ01P7/yvodKxn+iqmyG4x5CXOei7ePNovKxxj/c+xhVLm+Aaz2HundQ0zo0fmKBHUnAquzWzTTpRX1fq74XQdQG5gmv8XbiMac+KfyutbGiRU/nPPXPo5cPo9Ghkw++ZN8iApOdU5zXyXW0ChwvIrRmw7w0GFqNhX0JCdivmlnj2g3NhHvwKANgYn3lLOoNB+tOpQfQ/CVs6qzFzBDx2o6URpGwodEOuSIKMINCeQ/QmcosGdVOVMs4LvTwG2U88uUW2zt1elrt8q9NR5mSqJiX9YOVMEnLTms30eKLbJ3zwCMEzD/40bIcfwvdx1olx8x/HgB9flJT7fy0V3HCNwlLOejHUvTa9v8iB3hwwmK1691YR+LVzK1zD7xtBeyvhjeF69axdkW9yW+GLDqPop/Tmj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fKIOnD8bU0U82aE2Pq23/bUga4t84rhys4sskAUhEj/sWSCpiC8p1RTfuXQsvTfdW0AJ5mMZzOgFDqZ1YKOjp4cs0XknzJoj7jbisoiLv9AQZLeHSIEiqmSKLUiYgk6cOwuHVDafyCf2SudSPh5cnWck5RYdwUzWyxeuPhKO6knJnOJB6SDf99KZFbQz1xd2xo7Rk2PSkngOHSdfHfya5jj2jzLH1hmT5UzJfpLVxDGYVHRV+RwZbzJup3guSnayZQreKm4BV7wTXUf9a+u9RMl88ddAZh9DrLZZGMvE2hpzTsihXHrYXKmfxNP/SA4Khy6ZpR8Bvfil4muOr')
cipher = AES.new(key, AES.MODE_CBC, iv)
pt = unpad(cipher.decrypt(ct), AES.block_size)
print("MSG:", pt)
So here are my questions:
If i run it I get this Error: ValueError: Error 65537 while instantiating the CBC mode. It occurs when it runs line 8 (cipher = AES.new(key, AES.MODE_CBC, iv) and i don't know why. I saw the other Question about that error, but there he tried to decrypt an input, that wasn't declarated, which doesn't seem to be the case here.
Solved: Like 'SquareRootOfTwentyThree' said, the length of my IV wasn't correct... Base64 encodes 8b to 6b. I will post the updated code with the (new) Questions under this.
from Cryptodome.Cipher import AES
from base64 import b64decode,b64encode
key = bytes.fromhex('42414347416E6F34745A4748524A7659')
ct =b64decode('zBN6M2DMdbAsLcScIe+LMEUM66aEDJkKI61i0+Frh/g9xA8Pb7FR1bVSLohl21V4BHo1ZH7BSNkClaPy/ejKw8r6lDFhUuIzu2JfNHn3W9h6sdM3ZiSniBNQP/dFrhrmc3I7xuZIvfTQqoyV6/DsFSZnyoObrCeF7Wi3VvPnNk9f3/PCQ2hAXPiA1soA05ALkGRgBPen8kxm8NEUTxogc8kSQ01P7/yvodKxn+iqmyG4x5CXOei7ePNovKxxj/c+xhVLm+Aaz2HundQ0zo0fmKBHUnAquzWzTTpRX1fq74XQdQG5gmv8XbiMac+KfyutbGiRU/nPPXPo5cPo9Ghkw++ZN8iApOdU5zXyXW0ChwvIrRmw7w0GFqNhX0JC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G3U2g5e18brGfdlVajow/DtBRhM1qFoJlebGMbbTpcQSXQS+qVPpcGAos49lHU48r3e2lTPG0539l47fMdH/5CKLhaKeZgzvOnp5PVLc6ZYh0ad2TH/5I0L8gakQXnS1AHZ9BXMzx3x8DhzTeO8H4VDiHyBLdGYOT4VtiPxDjnc8WLhZoFkeW1pGR8RiJc7m1+ZGu2Q/VPfW1yqEYtJIBMEIXHA4qJ1IaU5tRfh2F3i6fKIOnD8bU0U82aE2Pq23/bUga4t84rhys4sskAUhEj/sWSCpiC8p1RTfuXQsvTfdW0AJ5mMZzOgFDqZ1YKOjp4cs0XknzJoj7jbisoiLv9AQZLeHSIEiqmSKLUiYgk6cOwuHVDafyCf2SudSPh5cnWck5RYdwUzWyxeuPhKO6knJnOJB6SDf99KZFbQz1xd2xo7Rk2PSkngOHSdfHfya5jj2jzLH1hmT5UzJfpLVxDGYVHRV+RwZbzJup3guSnayZQreKm4BV7wTXUf9a+u9RMl88ddAZh9DrLZZGMvE2hpzTsihXHrYXKmfxNP/SA4Khy6ZpR8Bvfil4muOr')
iv = ct[:16]
ciph = AES.new(key, AES.MODE_CBC, iv)
res = ciph.decrypt(ct[16:])
print(res)
print(b64encode(res))
The task I have to solve says, the msg uses Zero-Byte-Padding (Null-Padding) and if I i run it i get Zero-Bytes at the end. So Can i assume the decryption gone right? Because the thing is, I cant read the secret out of the message..
Thank you in Advance!
Greetings,
SomeDude
This example works fine example:
import hashlib
m = hashlib.md5()
m.update(b"Nobody inspects")
r= m.digest()
print(r)
Now, I want to do the same thing but with a variable: var= "hash me this text, please". How could I do it following the same logic of the example ?
The hash.update() method requires bytes, always.
Encode unicode text to bytes first; what you encode to is a application decision, but if all you want to do is fingerprint text for then UTF-8 is a great choice:
m.update(var.encode('utf8'))
The exception you get when you don't is quite clear however:
>>> import hashlib
>>> hashlib.md5().update('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing
If you are getting the hash of a file, open the file in binary mode instead:
from functools import partial
hash = hashlib.md5()
with open(filename, 'rb') as binfile:
for chunk in iter(binfile, partial(binfile.read, 2048)):
hash.update(chunk)
print hash.hexdigest()
Try this. Hope it helps.
The variable var has to be utf-8 encoded. If you type in a string i.e. "Donald Duck", the var variable will be b'Donald Duck'. You can then hash the string with hexdigest()
#!/usr/bin/python3
import hashlib
var = input('Input string: ').encode('utf-8')
hashed_var = hashlib.md5(var).hexdigest()
print(hashed_var)
I had the same issue as the OP. I couldn't get either of the previous answers to work for me for some reason, but a combination of both helped come to this solution.
I was originally hashing a string like this;
str = hashlib.sha256(b'hash this text')
text_hashed = str.hexdigest()
print(text_hashed)
Result;d3dba6081b7f171ec5fa4687182b269c0b46e77a78611ad268182d8a8c245b40
My solution to hash a variable;
text = 'hash this text'
str = hashlib.sha256(text.encode('utf-8'))
text_hashed = str.hexdigest()
print(text_hashed)
Result; d3dba6081b7f171ec5fa4687182b269c0b46e77a78611ad268182d8a8c245b40