test-sha1.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /*
  2. * Test program for SHA1 and MD5
  3. * Copyright (c) 2003-2006, Jouni Malinen <j@w1.fi>
  4. *
  5. * This software may be distributed under the terms of the BSD license.
  6. * See README for more details.
  7. */
  8. #include "includes.h"
  9. #include "common.h"
  10. #include "crypto/crypto.h"
  11. static int cavp_shavs(const char *fname)
  12. {
  13. FILE *f;
  14. int ret = 0;
  15. char buf[15000], *pos, *pos2;
  16. u8 msg[6400];
  17. int msg_len = 0, tmp_len;
  18. u8 md[20], hash[20];
  19. int ok = 0;
  20. printf("CAVP SHAVS test vectors from %s\n", fname);
  21. f = fopen(fname, "r");
  22. if (f == NULL) {
  23. printf("%s does not exist - cannot validate CAVP SHAVS test vectors\n",
  24. fname);
  25. return 0;
  26. }
  27. while (fgets(buf, sizeof(buf), f)) {
  28. pos = os_strchr(buf, '=');
  29. if (pos == NULL)
  30. continue;
  31. pos2 = pos - 1;
  32. while (pos2 >= buf && *pos2 == ' ')
  33. *pos2-- = '\0';
  34. *pos++ = '\0';
  35. while (*pos == ' ')
  36. *pos++ = '\0';
  37. pos2 = os_strchr(pos, '\r');
  38. if (!pos2)
  39. pos2 = os_strchr(pos, '\n');
  40. if (pos2)
  41. *pos2 = '\0';
  42. else
  43. pos2 = pos + os_strlen(pos);
  44. if (os_strcmp(buf, "Len") == 0) {
  45. msg_len = atoi(pos);
  46. } else if (os_strcmp(buf, "Msg") == 0) {
  47. tmp_len = os_strlen(pos);
  48. if (msg_len == 0 && tmp_len == 2)
  49. tmp_len = 0;
  50. if (msg_len != tmp_len * 4) {
  51. printf("Unexpected Msg length (msg_len=%u tmp_len=%u, Msg='%s'\n",
  52. msg_len, tmp_len, pos);
  53. ret++;
  54. break;
  55. }
  56. if (hexstr2bin(pos, msg, msg_len / 8) < 0) {
  57. printf("Invalid hex string '%s'\n", pos);
  58. ret++;
  59. break;
  60. }
  61. } else if (os_strcmp(buf, "MD") == 0) {
  62. const u8 *addr[1];
  63. size_t len[1];
  64. tmp_len = os_strlen(pos);
  65. if (tmp_len != 2 * 20) {
  66. printf("Unexpected MD length (MD='%s'\n",
  67. pos);
  68. ret++;
  69. break;
  70. }
  71. if (hexstr2bin(pos, md, 20) < 0) {
  72. printf("Invalid hex string '%s'\n", pos);
  73. ret++;
  74. break;
  75. }
  76. addr[0] = msg;
  77. len[0] = msg_len / 8;
  78. if (sha1_vector(1, addr, len, hash) < 0 ||
  79. os_memcmp(hash, md, 20) != 0)
  80. ret++;
  81. else
  82. ok++;
  83. }
  84. }
  85. fclose(f);
  86. if (ret)
  87. printf("Test case failed\n");
  88. else
  89. printf("%d test vectors OK\n", ok);
  90. return ret;
  91. }
  92. int main(int argc, char *argv[])
  93. {
  94. int ret = 0;
  95. if (cavp_shavs("CAVP/SHA1ShortMsg.rsp"))
  96. ret++;
  97. if (cavp_shavs("CAVP/SHA1LongMsg.rsp"))
  98. ret++;
  99. return ret;
  100. }