Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Encrypting and Decrypting a string from Input() not working using Python and Pycryptodome

$
0
0

I'm trying to create a application that will encrypt and decrypt data based on a key generated from a password that the user used. I'm using Pycryptodome and I get this error:ValueError: Data must be padded to 16 byte boundary in CBC mode

Below is the code

from Crypto.Protocol.KDF import PBKDF2from Crypto.Cipher import AESfrom Crypto.Util.Padding import pad, unpadclass SingleEncryption:    def __init__(self, password):        self.password = password        # self.salt = random data        self.key = PBKDF2(self.password, self.salt, dkLen=32)    def saveKey(self):        if input(f"Would you like to save this key ({self.key}) to a file? Y/N ") == "Y":            file_out = open(input("Where should I save it? "), "wb")            file_out.write(self.key)            file_out.close()        else:            print(f"Key not saved, the key is {self.key}")    def encrypt(self, data):        cipher = AES.new(self.key, AES.MODE_CBC)        ciphered_data = cipher.encrypt(pad(data, AES.block_size))        return ciphered_data    def decrypt(self, cipher_data):        cipher2 = AES.new(self.key, AES.MODE_CBC,)        original_data = unpad(cipher2.decrypt(cipher_data), AES.block_size)        return original_dataif __name__ == "__main__":    encrypt = SingleEncryption(input("Encryption password? "))    while True:        q = input("Encrypt, Decrypt, or Quit? ")        if q == "Encrypt":            print(encrypt.encrypt(input("What to encrypt? ").encode()))        elif q == "Decrypt":            print(encrypt.decrypt(input("Encrypted data? ").encode()))        elif q == "Quit":            break        else:            print("Incorrect input, it is case sensitive.")

Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>