Skip to content
Advertisement

Cant encrypt strings with special characters with pycrypto AES

Description

I want to store people’s names in MySQL database. Because the data is sensitive information i want to encrypt it with AES. I am using PyCrypto AES module. The code that I am using is:

JavaScript

The key used for encryption is a random long string.

Problem

Lets say the string (example name) i want to encrypt is “Strah”. I get the folowing cipher text.

JavaScript

But if the name includes some special characters like č,š or ž and i want to encrypt a name like “Štrah” i will get the following error:

JavaScript

So the question is, what should I do to encrypt strings with special characters.

Advertisement

Answer

The problem here is that the cipher internally operates on bytes, but you’re giving it a string. You’re padding the string to a multiple of 16, but when that string is encoded to bytes, it’s no longer a multiple a 16.

JavaScript

The solution is to encode the string yourself instead of letting the cipher do it for you. You have to make 2 small changes:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement