What's faster/better to use: the MySQL or PHP md5 function?

后端 未结 5 1472
[愿得一人]
[愿得一人] 2021-02-19 13:44

I checked the passwords for the users against the DB.

What is faster, the MySQL MD5 function

... pwd = MD5(\'.$pwd.\')

相关标签:
5条回答
  • 2021-02-19 14:03

    I don't know which is faster, but if you do it in PHP you avoid the possibility of SQL injection.

    0 讨论(0)
  • 2021-02-19 14:05

    Measure it, it's the only way to be certain.

    0 讨论(0)
  • 2021-02-19 14:06

    Is performance really an issue here? It's likely to be marginal.

    • Doing it in MySQL makes the DB do more work, which is a good thing
    • Doing it in MySQL means the cleartext password gets passed further along (and the DB connection is often unencrypted).
    • This has nothing to do with SQL injection. You could fix the first version without moving the MD5 function. Also if there was a bug in PHP's MD5 function there's still a possibility of an injection attack.
    0 讨论(0)
  • 2021-02-19 14:08

    If your application is only calcullating md5 when someone registers on your site, or is logging in, own many calls to md5 will you do per hour ? Couple of hundreds ? If so, I don't think the really small difference between PHP and MySQL will be significant at all.

    The question should be more like "where do I put the fact that password are stored using md5" than "what makes me win almost nothing".

    And, as a sidenote, another question could be : where can you afford to spend resources for that kind of calculations ? If you have 10 PHP servers and one DB server already under heavy load, you get your answer ;-)

    But, just for fun :

    mysql> select benchmark(1000000, md5('test'));
    +---------------------------------+
    | benchmark(1000000, md5('test')) |
    +---------------------------------+
    |                               0 |
    +---------------------------------+
    1 row in set (2.24 sec)
    

    And in PHP :

    $before = microtime(true);
    for ($i=0 ; $i<1000000 ; $i++) {
        $a = md5('test');
    }
    $after = microtime(true);
    echo ($after-$before) . "\n";
    

    gives :

    $ php ~/developpement/tests/temp/temp.php
    3.3341760635376
    

    But you probably won't be calculating a million md5 like this, will you ?

    (And this has nothing to do with preventing SQL injections : just escape/quote your data ! always ! or use prepared statements)

    0 讨论(0)
  • 2021-02-19 14:10

    I would say, read the column value out of mysql, then compare the result with the computed hash in your client code (e.g. php).

    The main reason for doing this is that it avoids stupid things such as the database collating the column in a non-binary fashion (e.g. case-insensitive etc), which is generally undesirable for a hash.

    0 讨论(0)
提交回复
热议问题