Search code examples
phpencryptioncryptographymd5sha1

How best to use the encryption method for confirm code


How best to use the encryption method for confirm code on email notification: md5, sha1 or sha256

I make email notification for confirm some actions by email;

I generated confirm code with salt and some parameters.

How best to use the encryption method for confirm code?


Solution

  • You have two main options here:

    1. generated some random data, store it in your database associated with that profile, and put only this data on the link;
    2. generate some kind of secure hash based on, say, the user id, and then pass both the user id and that hash on the link

    The first option is secure (supposing you are using either a real random number generator or a very, very good pseudo-random number generator), but you have to store data on a database.

    I usually prefer the second option, since there's no need to store anything on a database, and no need to query the database to check if the link is valid.

    Choose a secret key that only your server will know, then define exactly what parameters you want to validate in the URL (for instance, only the user id might be enough; however if you want the link to expire, you could add a timestamp to the url and validate both the user id and the timestamp with your hash). Mix your secret key with the parameters, generate a hash based on this, and create a link specifying both your parameters and the hash. When the user clicks the link, you take the parameters from the url, combine them again with the secret key, hash the result and compare with the hash that came with the url.

    A secure way to do this is to use HMAC, which is Hash-based Message Authentication Code. See: http://php.net/manual/en/function.hash-hmac.php.

    Note that this mechanism exposes the data you are validating in the url. If the data is secret (ie, suppose you want to send the link to the user containing both the username and his password, without saving anything at all on the database before he clicks the link), you must use Authenticated Encryption, which is a mix of an encryption algorithm (which guarantees that no one can read the data) and an authentication algorithm (which guarantees that no one can temper with the encrypted data to produce something meaningful -- only your server is able to generate such code).