/2.0/Tests/Misc/hash functions #26667.php

# · PHP · 46 lines · 31 code · 9 blank · 6 comment · 4 complexity · 5095a4a02773473257a2506073a6935b MD5 · raw file

  1. [expect php]
  2. [file]
  3. <?php
  4. function test_hash($algo, $init)
  5. {
  6. echo "\n$algo, incremental: ";
  7. $h = hash_init($algo);
  8. for($i=0;$i<10;++$i) hash_update($h, '' . $init*2 + $i);
  9. echo '(copying state) ';
  10. $h2 = hash_copy($h);
  11. for($i=0;$i<10;++$i) hash_update($h, '' . $init*2 + $i);
  12. var_dump(hash_final($h));
  13. echo "\n$algo, from copied state: ";
  14. var_dump(hash_final($h2));
  15. echo "\n$algo, HMAC, incremental: ";
  16. $h = hash_init($algo, HASH_HMAC, 'HMAC key. It can be very long, but in this case it will be rehashed to fit the block size of the hashing algorithm...'.$init*147);
  17. for($i=0;$i<10;++$i) hash_update($h, '' . $init*4 + $i);
  18. //echo '(copying state) ';
  19. //$h2 = hash_copy($h);// causes PHP crashes sometimes, reported as PHP Bug #52240
  20. for($i=0;$i<10;++$i) hash_update($h, '' . $init*3 + $i);
  21. var_dump(hash_final($h));
  22. //echo "\n$algo, HMAC, from copied state: ";
  23. //var_dump(hash_final($h2));// BUG IN PHP, HMAC key is not copied, but only referenced ... hash_final on $h clears the HMAC key in $h2 too... reported as PHP Bug #52240
  24. echo "\n$algo, at once, short data: ";
  25. var_dump(hash($algo, 'some string to be hashed ... ' . $init * 123 . ' ...'));
  26. echo "\n$algo, at once, HMAC: ";
  27. var_dump(hash_hmac($algo, 'some string to be hashed ... ' . $init * 123 . ' ...', 'HMAC key. It can be very long, but in this case it will be rehashed to fit the block size of the hashing algorithm.'));
  28. }
  29. // fixed // http://bugs.php.net/bug.php?id=52240 // PHP Bug, see for future updates of this test
  30. test_hash('adler32', 12345678);
  31. test_hash('crc32', 2345678);
  32. test_hash('crc32b', 345678);
  33. test_hash('md2', 45678);
  34. test_hash('md4', 5678);
  35. test_hash('md5', 678);
  36. // add more tests as other hashing algorithms will be implemented
  37. ?>