douyou8047 2011-04-22 16:55
浏览 56

使用mcrypt,PHP和MySQL进行加密

I am trying to use mcrypt to store a password on my database. First of all, it WORKS, but only some of the time.

Here is my encryption code:

    //Encryption/Decryption key
    $key = $username.$username.$username.$username.$username;
    //Encryption Algorithm
    $cipher_alg = MCRYPT_RIJNDAEL_256;

    $iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND);
    $password = mcrypt_encrypt($cipher_alg, $key, $pass1, MCRYPT_MODE_CBC, $iv);

This then uploads the $username, the $iv and the $password to the MySQL database.

Here is my decryption code:

    //Encryption/Decryption key
    $key = $username.$username.$username.$username.$username;

    //Encryption Algorithm
    $cipher_alg = MCRYPT_RIJNDAEL_256;

    $dbpass = mcrypt_decrypt($cipher_alg, $key, $encpass, MCRYPT_MODE_CBC, $random);
    $dbpass = trim($dbpass); // Trim the fat

The $username, $iv, and $encpass(encrypted password) are retrieved from the database and the key is recreated using the username.

This WORKS but only sometimes. I can't figure out why. My only assumption is that the database can't accept some of characters the encryption produces such as quotations.

Any help would be greatly appreciated!

  • 写回答

4条回答 默认 最新

  • dongsashe6006 2011-04-22 16:59
    关注

    If you are storing a user's password in the database, you should be using one-way hashing

    Here is just a very minimalist example

    $username = $_POST['username'];
    $password = $_POST['password'];
    $salt     = 'Some Salt';
    
    $result = mysql_query("SELECT username, password
                           WHERE username = '".mysql_real_escape_string($username)."'
                           AND   password = '".mysql_real_escape_string(sha1($password . $salt))."'
                           LIMIT 1");
    
    if(mysql_num_rows($result)) {
    // we have a match
    }
    else {
    // no match
    }
    

    You would have to be inserting user passwords with an appended salt using sha1 in my example. Keep in mind, this is just a suggestion for storing user passwords in the database.

    评论

报告相同问题?