I've created a encrypting and decrypting script for files, and it has worked pretty well for one day. Now that i tried to encrypt a little bit longer text, I got a error saying "binascii.Error: Incorrect padding", and the full error message saying:
Traceback (most recent call last):
File "C:\Users\Heikki\Desktop\Encryptor\decrypter.py", line 48, in <module>
main()
File "C:\Users\Heikki\Desktop\Encryptor\decrypter.py", line 39, in main
decrypt(sys.argv[1], sys.argv[2], sys.argv[3])
File "C:\Users\Heikki\Desktop\Encryptor\decrypter.py", line 21, in decrypt
f = Fernet(secret)
File "C:\Users\Heikki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\fernet.py", line 34, in __init__
key = base64.urlsafe_b64decode(key)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\lib\base64.py", line 133, in urlsafe_b64decode
return b64decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Incorrect padding
I tried doing my best with research and only thing i relise was, that, if the key has a underscore("_") in it, it throws this error message. This might be a problem with fernet module? Or is there a walk around for me to do? (The key is generated by myself, usually works)
Edit: Faced a new error:
Traceback (most recent call last):
File "C:\Users\Heikki\Desktop\Encryptor\decrypter.py", line 48, in <module>
main()
File "C:\Users\Heikki\Desktop\Encryptor\decrypter.py", line 39, in main
decrypt(sys.argv[1], sys.argv[2], sys.argv[3])
File "C:\Users\Heikki\Desktop\Encryptor\decrypter.py", line 21, in decrypt
f = Fernet(secret)
File "C:\Users\Heikki\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\fernet.py", line 34, in __init__
key = base64.urlsafe_b64decode(key)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\lib\base64.py", line 133, in urlsafe_b64decode
return b64decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2032.0_x64__qbz5n2kfra8p0\lib\base64.py", line 87, in b64decode
return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (41) cannot be 1 more than a multiple of 4
Full Encrypting Script:
import subprocess
import sys
#def install(package):
#subprocess.check_call([sys.executable, "-m", "pip", "install", package])
#for x in ["keyboard", "fernet", "cryptography", "colorama", "tk"]:
#nstall(x)
import os
import random
from string import ascii_letters
import time
import keyboard
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import tkinter
from tkinter import filedialog
from colorama import init, Fore, Back, Style
init(convert=True)
def encrypt(filename, key):
f = Fernet(key)
with open(filename, "rb") as file:
file_data = file.read()
encrypted_data = f.encrypt(file_data)
with open(filename, "wb") as file:
file.write(encrypted_data)
print(Fore.CYAN + Style.BRIGHT + f"----> {filename} is now encrypted!")
time.sleep(2.5)
os.system('cls')
def generate_keys(length, filename, encrypt_type):
if encrypt_type == '-r':
letters = []
for x in ascii_letters:
letters.append(x)
for n in range(9):
letters.append(str(n))
keys = ""
for _ in range(length):
keys = keys + random.choice(letters)
os.system('cls')
print(Fore.WHITE + Style.BRIGHT + "Setting password to : " + Fore.GREEN + Style.BRIGHT + keys + Fore.YELLOW + Style.BRIGHT + " -----> " + filename)
print(Fore.WHITE + Style.BRIGHT + "Press space to continue...")
keyboard.wait("space")
keys = keys.encode("utf-8")
password = b"%b" % keys
elif encrypt_type == "-o":
print(Fore.WHITE + Style.BRIGHT + "Setting password to : " + Fore.GREEN + Style.BRIGHT + sys.argv[2] + Fore.YELLOW + Style.BRIGHT + " -----> " + filename)
print(Fore.WHITE + Style.BRIGHT + "Press space to continue...")
keyboard.wait("space")
passwd = sys.argv[2].encode("utf-8")
password = b"%b" % passwd
salt = os.urandom(16)
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=390000,
)
key = base64.urlsafe_b64encode(kdf.derive(password))
secret_in_string = ""
for l in str(key):
if l == "b" or l == "'":
pass
else:
secret_in_string += l
print(Fore.WHITE + Style.BRIGHT + "Secret: " + Fore.GREEN + Style.BRIGHT + secret_in_string)
print(Fore.WHITE + Style.BRIGHT + "Press space to continue...")
keyboard.wait("space")
os.system("cls")
encrypt(filename, key)
def main():
usage = f"""Usage: python3 {sys.argv[0]} <type>.
Types:
-o Your own password
-r Random password"""
if ".py" in sys.argv[0]:
try:
encrypt_type = sys.argv[1]
except IndexError:
os.system('cls')
print(Fore.GREEN + Style.BRIGHT + usage)
sys.exit(1)
elif ".exe" in sys.argv[0]:
encrypt_type = input(Fore.GREEN + Style.DIM + "Encryption type: " + Fore.GREEN + Style.DIM + "-o" + Fore.GREEN + Style.DIM + " = own password or " + Fore.GREEN + Style.DIM + "-r" + Fore.GREEN + Style.DIM + " = random password\n ------> ")
if len(sys.argv) < 2:
os.system("cls")
print(Fore.GREEN + Style.BRIGHT + usage)
print("Press space to continue...")
keyboard.wait('space')
os.system('cls')
main()
tkinter.Tk().withdraw()
file_path = filedialog.askopenfilenames()
file_list = []
for files in file_path:
file_list.append(files)
if encrypt_type == "-o":
try:
sys.argv[2]
x = ""
for i in file_list:
generate_keys(x, i, encrypt_type)
except IndexError:
os.system('cls')
print(Fore.GREEN + Style.BRIGHT + f"""Usage: python3 {sys.argv[0]} -o <password>""")
exit()
if encrypt_type == '-r':
os.system("cls")
leng = input(Fore.MAGENTA + Style.BRIGHT + "Key length: ")
leng = int(leng)
for i in file_list:
generate_keys(leng, i, encrypt_type)
else:
pass
if __name__ == "__main__":
main()
Steps that (should) let you reproduce the error
- Create a .txt file with this text
gAAAAABjIzfWRxEMpJoBfMHfaFgkijsIGP8jW5qHyDCB8JL9tjUh5vg66480E4pYft209yMyvmhkIti73AIHZkqdZzjRfQtpzFLNMSNFfTGFau5Jv_HkmYLO6H1Uax547-3_HTk4FU5jAr3WEMS5d5jsVhTdTkwkPllWrfcwkQFt5Ivxx0drkf5j9-MH63kSEQScFBVMQ3UYD3ZPqfTFcomalNQ98lLCejmogkWkqsk2HIt-51TlVIo= - Create the decrypt.py script with contents:
from colorama import Fore, Back, Style, init
import sys
import os
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import base64
init(convert=True)
def decrypt(filename, keys, secret):
password = keys
if password != 'x':
print("Wrong password: ", password)
exit()
else:
pass
secret = secret.encode('utf8')
f = Fernet(secret)
with open(filename, "rb") as file:
file_data = file.read()
decrypted_data = f.decrypt(file_data)
with open(filename, "wb") as file:
file.write(decrypted_data)
os.system('cls')
print(Fore.CYAN + Style.BRIGHT + f"----> {filename} is now decrypted!")
def main():
try:
checker = os.path.exists(sys.argv[1])
if checker == True:
pass
if checker == False:
print(Fore.RED + Style.BRIGHT + f"[-] No such file or directory: {sys.argv[1]}")
exit()
try:
decrypt(sys.argv[1], sys.argv[2], sys.argv[3])
except IndexError:
print(Fore.RED + Style.BRIGHT + "[-] Not enough keys found in arguments...")
print( f"Usage: {sys.argv[0]} <filename> <password> <secret>")
exit()
except IndexError:
print(Fore.RED + Style.BRIGHT + f"Usage: {sys.argv[0]} <filename> <password> <secret>")
if __name__ == "__main__":
main()
- Run this command on the file:
python3 decrypter.py secret.txt x 3VYammLNTGfhVzejS9kQ9ai9q_qcN_M4hyEyIwa4d0=(dont worry about the 'x' its there just for now, because im trying to create a password system for it (but it needs to be there))