I have a encrypted message in a file, encrypted by the following code.
I wrote a function to decrypt this message. I know the password used to encrypt it.
But I got the following error:
python3 decrypt.py enim_msg.txt
Traceback (most recent call last):
File "decrypt.py", line 45, in <module>
print(":: Decrypted: \n" + bytes.decode(decrypted))
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x88 in position 2: invalid start byte
How can I fix this problem pls ?
Is My decrypt function wrong ?
My code :
Encrypt function
import os
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
def encrypt(key, filename):
chunksize = 64*1024
outputFile = "en" + filename
filesize = str(os.path.getsize(filename)).zfill(16)
IV = Random.new().read(16)
encryptor = AES.new(key, AES.MODE_CBC, IV)
with open(filename, 'rb') as infile:
with open(outputFile, 'wb') as outfile:
outfile.write(filesize.encode('utf-8'))
outfile.write(IV)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - (len(chunk) % 16))
outfile.write(encryptor.encrypt(chunk))
def getKey(password):
hasher = SHA256.new(password.encode('utf-8'))
return hasher.digest()
Decrypt function I wrote
def decrypt(enc, password):
#print(":: enc => " + enc)
private_key = hashlib.sha256(password.encode("utf-8")).digest()
iv = enc[:16]
cipher = AES.new(private_key, AES.MODE_CBC, iv)
return cipher.decrypt(enc[16:])
How I call this function
password = "azerty123"
secret_file_path = sys.argv[1]
the_file = open(secret_file_path, "rb")
encrypted = the_file.read()
decrypted = decrypt(encrypted, password)
the_file.close()
print(":: Decrypted: \n" + bytes.decode(decrypted))
The bytes.decrypt() function by default expects an UTF-8 encoded string. But not every sequence of bytes is a valid UTF-8 sequence. In your case cipher.decrypt() (which may return any sequence of bytes) returned a byte-sequence, which is not a valid UTF-8 sequence. Thus the bytes.decode() function raised an error.
The actual reason why cipher.decrypt() returned a non-UTF-8 string is a bug in your code:
Your encrypted file format contains non-utf-8 data. Its format is like:
16 bytes len info (unencrypted, UTF-8 encoded)
16 bytes IV (unencrypted, binary i.e. non-UTF-8 encoded)
n bytes payload (encrypted, UTF-8 encoded)
You have to ensure that on decryption you only decode parts of your file, that are UTF-8 encoded. Furthermore you have to ensure that you decrypt only encrypted parts of your file (as mentioned in your comments)
Related
I am playing a CTF challenge . I have been given encrypted file and Code used for encryption where I've to find the time used for seed variable for decryption . But I'm unable to decrypt the output from bytes to string .
Here is the code used in the CTF challenge -
#! /usr/local/bin/python
from Crypto.Cipher import AES
from datetime import datetime
import hashlib
from time import strftime
seed = str(datetime.now())
key = hashlib.sha256(seed.encode('utf-8')).digest()
IV = 16 * '\x00'
mode = AES.MODE_CBC
encryptor = AES.new(key, mode, IV=IV)
text = open('flag.txt', 'r', encoding='utf-8').read()
text = text + "0" * (16-len(text)%16)
ciphertext = encryptor.encrypt(text)
target = open('flag.enc.txt', 'wb')
target.write(ciphertext)
target.close()
And here is the code I've used for decryption -
#! /usr/local/bin/python
from Crypto.Cipher import AES
from datetime import datetime
import hashlib
import base64
from time import strftime
seedOrg = '2021-07-06 03:16:51.'
IV = 16 * '\x00'
mode = AES.MODE_CBC
with open('/home/teja_mxx/Desktop/CapStone/encDec/flag.enc.txt', 'rb') as f:
encText = f.read()
print(encText)
for x in range(1):
if len(str(x)) < 9:
llen = len(str(x))
milli = ("0" * (9 - llen))+str(x)
seed = seedOrg+milli
key = hashlib.sha256(seed.encode('utf-8')).digest()
decryptor = AES.new(key, mode, IV=IV)
decryptedText = decryptor.decrypt(encText)
print(decryptedText.decode())
And I'm getting this error . How do I resolve it ?
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 4: invalid continuation byte
I am trying to encrypt/decrypt with pycrypto in python. for the most part things have worked smooth but I am getting an odd problem when decrypting data.I have tried to encrypt/decrypt some jpgs for testing and although they encrypt/decrypt without issue, the decrypted files cannot be opened/are corrupted. To try to find the problem I saved a textfile with a random sentence similar to "test this file for integrity blah blah blah" and it decrypts correctly only after ".... integrity blah blah blah", everything before integrity is still in garbled characters. I'm not that knowledgable on AES, but im assuming that this is an encoding/decoding or padding error.
Here is my code:
#encryption
iv = Random.new().read( AES.block_size)
filePath = input("Path to file for encryption: ")
selFile = open(filePath, 'rb')
getBytes = bytes(selFile.read())
encPW = input("Enter password: ")
hashpw = hashlib.sha256(encPW.encode('UTF-8').digest())
destination = input("Destination path for encrypted file: ")
aes = AES.new(hashpw, AES.Mode_CFB, iv)
encFile = base65.b64encode(aes.encrypt(getBytes))
writetofile = open(destination, 'wb')
writetofile.write(encFile)
writetofile.close()
print("Encryption successful")
#Decryption
iv = Random.new().read( AES.block_size)
filePath = input("Path to file for decryption: ")
selFile = open(filePath, 'rb')
getBytes = bytes(selFile.read())
decPW = input("Enter password: ")
hashdecpw = hashlib.sha256(encPW.encode('UTF-8').digest())
destination = input("Destination path for decrypted file: ")
aes = AES.new(hashdecpw, AES.Mode_CFB, iv)
decFile = aes.decrypt(getBytes)
writetofile = open(destination, 'wb')
writetofile.write(decFile)
writetofile.close()
print("Decryption successful")
Any ideas on what could be causing the loss of the first characters, and preventing me from encrypting/decrypting files correctly?
You have at least three issues:
You probably mean hashlib.sha256(encPW.encode('UTF-8')).digest() instead of hashlib.sha256(encPW.encode('UTF-8').digest()) (the closing brace is at the wrong position)
You're encoding the ciphertext with Base64 before writing it to a file. You've forgot to decode it after reading it back from the file before decrypting it. For example:
getBytes = base64.b64decode(bytes(selFile.read()))
This is the big one: You need the exact same IV during the decryption that you've used for encryption. The IV is not secret, but it needs to be unique for every encryption that you've done with the same key. Commonly the IV is written in front of the ciphertext and read back for decryption.
#encryption
encFile = base64.b64encode(iv + aes.encrypt(getBytes))
#decryption
getBytes = base64.b64decode(bytes(selFile.read()))
iv = getBytes[:16]
aes = AES.new(hashdecpw, AES.Mode_CFB, iv)
decFile = aes.decrypt(getBytes[16:])
You're generating a new IV for encryption and decryption seperately, which comes to yield such problems. Here's what I recommend doing:
def encrypt(inpath, outpath, password):
iv = Random.new().read(AES.block_size)
with open(inpath, "rb") as f:
contents = f.read()
# A context manager automatically calls f.close()
key = pbkdf2.crypt(password, "")
# See notes
aes = AES.new(key, AES.Mode_CFB, iv)
encrypted = aes.encrypt(contents)
with open(outpath, "wb") as f:
f.write(iv + b":")
f.write(encrypted)
print("Encryption successful")
def decrypt(inpath, outpath, password):
with open(inpath, "rb") as f:
contents = f.read()
iv, encrypted = contents.split(b":")
key = pbkdf2.crypt(password, "")
aes = AES.new(key, AES.Mode_CFB, iv)
decrypted = aes.decrypt(contents)
with open(outpath, "wb") as f:
f.write(decrypted)
print("Decryption successful")
Some notes:
An IV is not meant to be secret, so it can be randomly generated once and then written to a file to be used later for decryption (as shown in this example)
A hashing algorithm is not strong enough for deriving keys, which is why there are special tools called key derivation algorithms (like PBKDF2 in python). Use those instead!
I have not tested this code myself, so it may not work properly.
I am using PKCS1_OAEP crypto algorithm to encrypt a file. The file is encrypted successfully but unable to decrypt file, getting the error "Ciphertext with incorrect length."
Encryption Algorithm is here:
#!/usr/bin/python
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import zlib
import base64
fd = open('test.doc', 'rb')
message = fd.read()
fd.close()
print "[*] Original File Size: %d" % len(message)
#message = 'To be encrypted'
key = RSA.importKey(open('pubkey.der').read())
cipher = PKCS1_OAEP.new(key)
compressed = zlib.compress(message)
print "[*] Compressed File Size: %d" % len(compressed)
chunk_size = 128
ciphertext = ""
offset = 0
while offset < len(compressed):
chunk = compressed[offset:offset+chunk_size]
if len(chunk) % chunk_size != 0:
chunk += " " * (chunk_size - len(chunk)) # Padding with spaces
ciphertext += cipher.encrypt(chunk)
offset += chunk_size
print "[*] Encrypted File Size: %d" % len(ciphertext)
encoded = ciphertext.encode("base64")
print "[*] Encoded file size: %d" % len(encoded)
fd = open("enc.data", 'wb')
fd.write(encoded)
fd.close()
print "[+] File saved successfully!"
Decryption Algorithm is here:
#!/usr/bin/python
from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA
import zlib
import base64
key = RSA.importKey(open('privkey.der').read())
cipher = PKCS1_OAEP.new(key)
fd = open('enc.data', 'rb')
encoded = fd.read().strip('\n')
fd.close()
decoded = encoded.decode("base64")
chunk_size = 128
offset = 0
plaintext = ""
while offset < len(decoded):
plaintext += cipher.decrypt(decoded[offset:offset+chunk_size])
offset += chunk_size
#plaintext = cipher.decrypt(decoded)
decompress = zlib.decompress(plaintext)
fd = open('decr.doc', 'wb')
fd.write(decompress)
fd.close()
Using the following script to generate key
from Crypto.PublicKey import RSA
new_key = RSA.generate(2048, e=65537)
public_key = new_key.publickey().exportKey("PEM")
private_key = new_key.exportKey("PEM")
fileWrite(fileName, data):
fd = open(fileName, 'wb')
fd.write(data)
fd.close()
fileWrite('privkey.der', private_key)
fileWrite('pubkey.der', public_key)
Here is the Error Message
You encrypt with a 2048 bit RSA key, which gives encrypted blocks of 2048 bites (256 bytes). Your decrypt implementation assumes the encrypted blocks are 128 bytes where they are actually 256 bytes, and thus you get the 'incorrect length' error. Notice how your encrypted files size (64512) is more than double of the compressed file size (32223).
In general you would not use RSA for bulk encryption (as it's quite slow) but would instead combine it with a symmetric encryption like AES. You would then encrypt the data with a random AES key, and then encrypt the AES key with the RSA key. This way you get the speed of AES and the two keys of RSA. This is known as Hybrid Encryption.
I'm trying to encrypt the data in a file using AES encryption and then encrypt the AES key using RSA. But when i try to read the keys from the file it crops up with the error "RSA binascii.Error: Incorrect padding".
Traceback (most recent call last):
File "C:/Users/dbane_000/PycharmProjects/RSE/RSA.py", line 33, in <module>
key=RSA.importKey(f.read())
File "C:\Python27\lib\site-packages\Crypto\PublicKey\RSA.py", line 660, in importKey
der = binascii.a2b_base64(b('').join(lines[1:-1]))
binascii.Error: Incorrect padding
The error doesn't come always but maybe once for every five times that I run this code. What could be the reason?
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto import Random
import rsa
import base64
import os
BLOCK_SIZE = 32
PADDING = '{'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
random_generator = Random.new().read
rsakey = RSA.generate(1024, random_generator)
f=open('key.pem','w')
cipher = PKCS1_OAEP.new(rsakey.publickey())
f.write(rsakey.exportKey("PEM"))
f.write(rsakey.publickey().exportKey("PEM"))
f.close()
f=open('key.pem','r')
key=RSA.importKey(f.read())
pubkey=key.publickey()
f.close()
secret = os.urandom(BLOCK_SIZE)
print secret
crypto =pubkey.encrypt(secret, 32)
secret =key.decrypt(crypto)
print crypto
print secret
cipher = AES.new(secret)
# encode a string
f=open('plaintext.txt','r')
plaintext=f.read()
f.close()
encoded = EncodeAES(cipher, plaintext)
print 'Encrypted string:', encoded
f=open('cipher_data.txt','w')
f.write(encoded)
f.close()
# decode the encoded string
decoded = DecodeAES(cipher, encoded)
print 'Decrypted string:', decoded
f=open('plaintext.txt','r')
plaintext=f.read()
f.close()
f=open('decrypted.txt','w')
f.write(decoded)
f.close()
Please try to check the contents of the input files from where you are taking key or data to encrypt or decrypt. This type of error would may occur,if the data from f.read() is in a desired format to perform decrypt.. And please try to write those keys or data at begining or desired index and fetch from that index..
# please check at this statements
f=open('key.pem','w')
cipher = PKCS1_OAEP.new(rsakey.publickey())
f.write(rsakey.exportKey("PEM"))
f.write(rsakey.publickey().exportKey("PEM"))
f.close()
f=open('key.pem','r')
key=RSA.importKey(f.read())
pubkey=key.publickey()
f.close()
I hope this may help you..
I already have a working program, but the only thing that doesn't work is the decrypt_file() function I have. I can still copy the encrypted text from the file and put it in my decrypt() function and have it work, but when I try to use my supposed-to-be handy decrypt_file() function it throws an error. Now I know 99.999% sure that my encrypt() and decrypt() functions are fine, but there is something with the bytes and strings conversion when I read and encode the text file that throws an error; I just can't find the hangup. Please help!
My Program:
from Crypto import Random
from Crypto.Cipher import AES
def encrypt(message, key=None, key_size=256):
def pad(s):
x = AES.block_size - len(s) % AES.block_size
return s + ((bytes([x])) * x)
padded_message = pad(message)
if key is None:
key = Random.new().read(key_size // 8)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(padded_message)
def decrypt(ciphertext, key):
unpad = lambda s: s[:-s[-1]]
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext))[AES.block_size:]
return plaintext
def encrypt_file(file_name, key):
f = open(file_name, 'r')
plaintext = f.read()
plaintext = plaintext.encode('utf-8')
enc = encrypt(plaintext, key)
f.close()
f = open(file_name, 'w')
f.write(str(enc))
f.close()
def decrypt_file(file_name, key):
def pad(s):
x = AES.block_size - len(s) % AES.block_size
return s + ((str(bytes([x]))) * x)
f = open(file_name, 'r')
plaintext = f.read()
x = AES.block_size - len(plaintext) % AES.block_size
plaintext += ((bytes([x]))) * x
dec = decrypt(plaintext, key)
f.close()
f = open(file_name, 'w')
f.write(str(dec))
f.close()
key = b'\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e[EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18'
encrypt_file('to_enc.txt', key)
The text file I encrypted:
b';c\xb0\xe6Wv5!\xa3\xdd\xf0\xb1\xfd2\x90B\x10\xdf\x00\x82\x83\x9d\xbc2\x91\xa7i M\x13\xdc\xa7'
My error when attempting decrypt_file:
Traceback (most recent call last):
File "C:\Python33\testing\test\crypto.py", line 56, in <module>
decrypt_file('to_enc.txt', key)
File "C:\Python33\testing\test\crypto.py", line 45, in decrypt_file
plaintext += ((bytes([x]))) * x
TypeError: Can't convert 'bytes' object to str implicitly
[Finished in 1.5s]
When I replace line 45 with: plaintext += ((str(bytes([x])))) * x, this is the error I get:
Traceback (most recent call last):
File "C:\Python33\testing\test\crypto.py", line 56, in <module>
decrypt_file('to_enc.txt', key)
File "C:\Python33\testing\test\crypto.py", line 46, in decrypt_file
dec = decrypt(plaintext, key)
File "C:\Python33\testing\test\crypto.py", line 23, in decrypt
plaintext = unpad(cipher.decrypt(ciphertext))[AES.block_size:]
File "C:\Python33\lib\site-packages\Crypto\Cipher\blockalgo.py", line 295, in decrypt
return self._cipher.decrypt(ciphertext)
ValueError: Input strings must be a multiple of 16 in length
[Finished in 1.4s with exit code 1]
I took a closer look at your code, and saw that there were several problems with it. First one is that the crypto functions with with bytes, not text. So it's better to just keep the data as a byte string. This is done simply by putting a 'b' character in the mode. This way you can get rid of all the encoding and bytes conversion you were trying to do.
I rewrote the whole code also using newer Python idioms. Here it is.
#!/usr/bin/python3
from Crypto import Random
from Crypto.Cipher import AES
def pad(s):
return s + b"\0" * (AES.block_size - len(s) % AES.block_size)
def encrypt(message, key, key_size=256):
message = pad(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
return iv + cipher.encrypt(message)
def decrypt(ciphertext, key):
iv = ciphertext[:AES.block_size]
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = cipher.decrypt(ciphertext[AES.block_size:])
return plaintext.rstrip(b"\0")
def encrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
enc = encrypt(plaintext, key)
with open(file_name + ".enc", 'wb') as fo:
fo.write(enc)
def decrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
ciphertext = fo.read()
dec = decrypt(ciphertext, key)
with open(file_name[:-4], 'wb') as fo:
fo.write(dec)
key = b'\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e[EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18'
encrypt_file('to_enc.txt', key)
#decrypt_file('to_enc.txt.enc', key)
In Python 3 (which you are clearly using) the default mode for files you open is text, not binary. When you read from the file, you get strings rather than byte arrays. That does not go along with encryption.
In your code, you should replace:
open(file_name, 'r')
with:
open(file_name, 'rb')
The same for when you open the file for writing. At that point, you can get rid of all the various occurrences where you convert from string to binary and vice versa.
For instance, this can go away:
plaintext = plaintext.encode('utf-8')