PageRenderTime 43ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/core/src/main/php/security/checksum/MessageDigest.class.php

http://github.com/xp-framework/xp-framework
PHP | 77 lines | 25 code | 5 blank | 47 comment | 2 complexity | 2ad4e499bd6bf57ddcf4c0a4200693f3 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /* This class is part of the XP framework
  3. *
  4. * $Id$
  5. */
  6. uses(
  7. 'security.NoSuchAlgorithmException',
  8. 'security.checksum.DefaultDigestImpl',
  9. 'security.checksum.CRC16DigestImpl'
  10. );
  11. /**
  12. * Factor class for message digests
  13. *
  14. * Creating a message digest incrementally
  15. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  16. * <code>
  17. * $digest= MessageDigest::newInstance('md5');
  18. * while ($in->available() > 0) {
  19. * $digest->update($in->read());
  20. * }
  21. * $md5= new MD5($digest->final());
  22. * </code>
  23. *
  24. * Verifying
  25. * ~~~~~~~~~
  26. * <code>
  27. * if ($md5->verify(new MD5('...'))) {
  28. * // Checksums match
  29. * }
  30. * </code>
  31. *
  32. * @test xp://net.xp_framework.unittest.security.checksum.MessageDigestTest
  33. * @see xp://security.checksum.DefaultDigestImpl
  34. */
  35. class MessageDigest extends Object {
  36. protected static $implementations= array();
  37. /**
  38. * Register an implementation
  39. *
  40. * @param string algorithm
  41. * @param lang.XPClass<security.checksum.MessageDigestImpl> class
  42. * @throws lang.IllegalArgumentException
  43. */
  44. public static function register($algorithm, XPClass $impl) {
  45. if (!$impl->isSubclassOf('security.checksum.MessageDigestImpl')) {
  46. throw new IllegalArgumentException('Implementation class must be a security.checksum.MessageDigestImpl');
  47. }
  48. self::$implementations[$algorithm]= $impl;
  49. }
  50. /**
  51. * Returns a list of names of supported algorithms
  52. *
  53. * @return string[] algorithms
  54. */
  55. public static function supportedAlgorithms() {
  56. return array_keys(self::$implementations);
  57. }
  58. /**
  59. * Creates a new instance given an algorithm name
  60. *
  61. * @param string algorithm
  62. * @return security.checksum.MessageDigestImpl
  63. * @throws security.NoSuchAlgorithmException
  64. */
  65. public static function newInstance($algorithm) {
  66. if (!isset(self::$implementations[$algorithm])) {
  67. throw new NoSuchAlgorithmException('Unsupported algorithm "'.$algorithm.'"');
  68. }
  69. return self::$implementations[$algorithm]->newInstance($algorithm);
  70. }
  71. }
  72. ?>