icebreaker606
icebreaker606

Reputation: 1

My Python program says "AttributeError: 'str' object has no attribute 'encode' on line 4"

I use https://create.withcode.uk

So I found a AES (Advanced Encryption Standard) implementation in Python, but just the encoding and the decoding part:

def encrypt(string, password):
    pad = lambda s : s + str.encode(chr(16 - len(s) % 16) * (16 - len(s) % 16))

    password = str.encode(password)
    string = str.encode(string)

    salt = os.urandom(8) # Unpredictable enough for cryptographic use
    salted = b''
    dx = b''

    while len(salted) < 48:
        dx = md5_encode(dx + password + salt, True)
        salted += dx

    key = salted[0:32]
    iv = salted[32:48]
    
    cipher = AES.new(key, AES.MODE_CBC, iv)
    encrypted_64 = base64.b64encode(cipher.encrypt(pad(string))).decode('ascii')
    
    json_data = {
        'ct': encrypted_64,
        'iv': iv.hex(),
        's': salt.hex()
    }

    return json.dumps(json_data, separators = (',', ':'))

Which works perfectly btw. Then after I did some "sentence = input('blah blah blah') and some password = input('blah blah'), after that, i did encrypt(sentence, password). But I'm really not that sure I did it correctly because it says : AttributeError: 'str' object has no attribute 'encode' on line 4

I'm new to Python.

Upvotes: 0

Views: 3844

Answers (1)

norie
norie

Reputation: 9867

str should be replaced by the string you want to encode, and the encoding you want to apply goes in the brackets.

password = password.encode(encoding='UTF-8')
string = string.encode(encoding='UTF-8')

Upvotes: 1

Related Questions