How to use AES_ENCRYPT properly?

2019-04-09 19:04发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

You should not just encrypt the password in database, but store a presentation of the password in the database.

See this question for lengthy explanation.