whiletrue
whiletrue

Reputation: 58

Encrypting unicode strings with pyaes

The following code works well:

import os, pyaes
key = os.urandom (16)
aes = pyaes.AESModeOfOperationCTR (key)
encrypted = aes.encrypt ('Hello world')
aes = pyaes.AESModeOfOperationCTR (key)
decrypted = aes.decrypt (encrypted)
print (encrypted)
print (decrypted)

But when I try to encode a unicode string, like a string containing hebrew letters for example, it raises an error:

ValueError: bytes must be in range(0, 256)

How can I encode unicode characters?

Upvotes: 0

Views: 2643

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114038

Unicode can be more than one byte wide, however your AES encoder/decoder expects a string of single bytes.

You need to encode your unicode into single bytes (typically utf8 works for this):

unicode_string = u"\u00b0C"
encrypted = aes.encrypt(unicode_string.encode("utf8"))

then when you decrypt it you need to decode it:

decrypted = aes.decrypt(encrypted).decode("utf8")

Upvotes: 1

Related Questions