hash-common.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* hash-common.c - Common code for hash algorithms
  2. * Copyright (C) 2008 Free Software Foundation, Inc.
  3. *
  4. * This file is part of Libgcrypt.
  5. *
  6. * Libgcrypt is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU Lesser General Public License as
  8. * published by the Free Software Foundation; either version 2.1 of
  9. * the License, or (at your option) any later version.
  10. *
  11. * Libgcrypt is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this program; if not, see <http://www.gnu.org/licenses/>.
  18. */
  19. #include <config.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #ifdef HAVE_STDINT_H
  24. # include <stdint.h>
  25. #endif
  26. #include "g10lib.h"
  27. #include "hash-common.h"
  28. /* Run a selftest for hash algorithm ALGO. If the resulting digest
  29. matches EXPECT/EXPECTLEN and everything else is fine as well,
  30. return NULL. If an error occurs, return a static text string
  31. describing the error.
  32. DATAMODE controls what will be hashed according to this table:
  33. 0 - Hash the supplied DATA of DATALEN.
  34. 1 - Hash one million times a 'a'. DATA and DATALEN are ignored.
  35. */
  36. const char *
  37. _gcry_hash_selftest_check_one (int algo,
  38. int datamode, const void *data, size_t datalen,
  39. const void *expect, size_t expectlen)
  40. {
  41. const char *result = NULL;
  42. gcry_error_t err = 0;
  43. gcry_md_hd_t hd;
  44. unsigned char *digest;
  45. if (_gcry_md_get_algo_dlen (algo) != expectlen)
  46. return "digest size does not match expected size";
  47. err = _gcry_md_open (&hd, algo, 0);
  48. if (err)
  49. return "gcry_md_open failed";
  50. switch (datamode)
  51. {
  52. case 0:
  53. _gcry_md_write (hd, data, datalen);
  54. break;
  55. case 1: /* Hash one million times an "a". */
  56. {
  57. char aaa[1000];
  58. int i;
  59. /* Write in odd size chunks so that we test the buffering. */
  60. memset (aaa, 'a', 1000);
  61. for (i = 0; i < 1000; i++)
  62. _gcry_md_write (hd, aaa, 1000);
  63. }
  64. break;
  65. default:
  66. result = "invalid DATAMODE";
  67. }
  68. if (!result)
  69. {
  70. digest = _gcry_md_read (hd, algo);
  71. if ( memcmp (digest, expect, expectlen) )
  72. result = "digest mismatch";
  73. }
  74. _gcry_md_close (hd);
  75. return result;
  76. }