I have a program that attempts to encrypt a message using aes. The problem arises when I have to encrypt the message and I get TypeError: Object type <class 'str'> cannot be passed to C code
. I found that if I encode it to utf-8 it works, but then when I try to decrypt it it doesn't get rid of the b'...' and the base64 decryption fails, making my iv not 16 bytes. Whenever I try to decode the first line of the file using aes.decrypt(file.readline().decode("utf-8"))
it says I can't use decode on a str.
from Crypto.Cipher import AES
from Crypto import Random
def pad(s):
pad = s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
return str(pad)
def unpad(s):
unpad = s[:-ord(s[len(s)-1:])]
return str(unpad)
class AESCipher:
def __init__( self, key ):
self.key = key
def encrypt( self, s ):
raw = pad(s)
iv = Random.new().read( AES.block_size )
cipher = AES.new( self.key, AES.MODE_CBC, iv )
return base64.b64encode( iv + cipher.encrypt( raw.encode("utf-8") ) )
def decrypt( self, enc ):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] ))
I'm new to encryption so I don't really know if this has been answered before and I just don't know how to word it, but I've been looking around for a few hours and haven't found anything. Thank you. Again, sorry if this isn't worded properly.