Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AES_ENCRYPT properly?

I'm trying to use AES encryption (AES_ENCRYPT in MySQL) for user passwords but I came up with a bunch of different problems.

This is the SQL query that I use to store a new user into the database:

INSERT INTO user VALUES (
    '15',
    'John',
    'Doe',
    '123 Fake St.',
    AES_ENCRYPT('mypassword', 'mysalt'),
    'mysalt'
)

Where the salt would be a random string in a real case.

It works fine. I mean, I'm able to retrieve the original password. In this example, AES_DECRYPT(user.password, 'mysalt') WHERE user.id = 15 retrieves mypassword. But I might be overlooking some things.

  • Is it secure to save the salt along with the password? Aside from security through obscurity thing.

  • What is the best format to store the hashed password? I'm using
    VARBINARY but the stored string looks like 8�p�����_�Z�\.

  • And finally, how long should the password be and how long should the salt be?

Thanks

like image 750
federico-t Avatar asked Jan 18 '23 01:01

federico-t


2 Answers

Typically, there is no actual need to reverse encrypt a password. Having that ability inherently decreases the security of the system. Instead, use an irreversible hash function. I suggest SHA-256 (or larger) which produces a string result:

 SHA2 (CONCAT (user.name, user.password, 'some salt', user.id), 256)

I have also frustrated bulk rainbow tables from being any use by rolling in other data always known at password validation time.

SHA2 requires MySQL 5.5 or later. If you are using an earlier version, SHA1() is nearly as good, and generally much better than MD5, AES, etc.

like image 165
wallyk Avatar answered Jan 20 '23 14:01

wallyk


Please consider using a password hash instead of a cryptographic hash. The goals are different. See https://security.stackexchange.com/a/6415/25424 for more info. Password frameworks like what are mentioned on https://stackoverflow.com/a/6337021/516813 take care of a lot of details for you like the salting.

like image 26
chacham15 Avatar answered Jan 20 '23 14:01

chacham15