⌘BABAKOV.NET Let's code!
100% [light] [ru]

AES_ENCRYPT and AES_DECRYPT Functions in MySQL

The AES_ENCRYPT() and AES_DECRYPT() functions perform symmetric encryption and decryption of data using the AES (Advanced Encryption Standard) algorithm, using 128-bit encoding. There is an option to expand to 256-bit, but 128-bit is chosen as the standard in MySQL, as it is considered secure and faster.

The syntax of the functions:

AES_ENCRYPT(\'Шифруемая строка\',\'Ключ\');
AES_DECRYPT(\'Дешифруемая строка\',\'Ключ\');
--Входные параметры AES_ENCRYPT() могут быть любой длины.
--Если любой из входных параметров равен NULL - то и результат выполнения тоже будет NULL.
--Ключ в AES_DECRYPT() должен совпадать с ключом в AES_ENCRYPT().



Here is a working example of using the functions: 

First, let's create a table of users with passwords that we will work with:


CREATE TABLE `test_users` (
  `name` varchar(50) NOT NULL,
  `crypt_pass` varbinary(50) DEFAULT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



Now, let's add a user to the table with a password encrypted using the AES_ENCRYPT() function:

insert into test_users (name,crypt_pass) values (\'Петр\', aes_encrypt(\'12345_!\',\'Мой ключ\'));



Now, let's look at the data in the test_users table:

select * from test_users;



And after executing the query, we will see:

+------+------------------+
| name | crypt_pass       |
+------+------------------+
| Петр | ┐hэ▌╗╖К<iП!┴Ь╓R |
+------+------------------+



Now we see that our password is encrypted.

Let's try to output the password in its original form using the AES_DECRYPT() function:

select name, aes_decrypt(crypt_pass,\'Мой ключ\') from test_users;



After executing the query, we will see not what we expected:

+------+------------------------------------+
| name | aes_decrypt(crypt_pass,\'Мой ключ\') |
+------+------------------------------------+
| Петр | {Здесь билиберда или NULL}         |
+------+------------------------------------+



The reason may be corrected by using only the Latin alphabet as the key, or in this way:

select name, cast(aes_decrypt(crypt_pass,\'Мой ключ\') as char(50)) from test_users;


Correcting the error by specifying the data types.

That's all.
Questions are welcome.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.