blob: ca60bb0a6d06a01dcc46abf96ca2f4b17e0cb445 [file] [log] [blame]
Steven Valdezb8a35502017-04-28 16:17:54 -04001/* Copyright (c) 2017, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
15// cavp_sha_test processes a NIST CAVP SHA test vector request file and emits
16// the corresponding response. An optional sample vector file can be passed to
17// verify the result.
18
19#include <stdlib.h>
20
21#include <openssl/crypto.h>
22#include <openssl/digest.h>
23
Adam Langley58e44992017-04-28 16:45:49 -070024#include "../crypto/test/file_test.h"
Steven Valdezb8a35502017-04-28 16:17:54 -040025#include "cavp_test_util.h"
26
27
28struct TestCtx {
29 std::string hash;
30};
31
32static bool TestSHA(FileTest *t, void *arg) {
33 TestCtx *ctx = reinterpret_cast<TestCtx *>(arg);
34
35 const EVP_MD *md = EVP_get_digestbyname(ctx->hash.c_str());
36 if (md == nullptr) {
37 return false;
38 }
39 const size_t md_len = EVP_MD_size(md);
40
41 std::string out_len;
42 if (!t->GetInstruction(&out_len, "L") ||
43 md_len != strtoul(out_len.c_str(), nullptr, 0)) {
44 return false;
45 }
46
47 std::string msg_len_str;
48 std::vector<uint8_t> msg;
49 if (!t->GetAttribute(&msg_len_str, "Len") ||
50 !t->GetBytes(&msg, "Msg")) {
51 return false;
52 }
53
54 size_t msg_len = strtoul(msg_len_str.c_str(), nullptr, 0);
55 if (msg_len % 8 != 0 ||
56 msg_len / 8 > msg.size()) {
57 return false;
58 }
59 msg_len /= 8;
60
61 std::vector<uint8_t> out;
62 out.resize(md_len);
63 unsigned digest_len;
64 if (!EVP_Digest(msg.data(), msg_len, out.data(), &digest_len, md, nullptr) ||
65 digest_len != out.size()) {
66 return false;
67 }
68
69 printf("%s", t->CurrentTestToString().c_str());
70 printf("MD = %s\r\n\r\n", EncodeHex(out.data(), out.size()).c_str());
71
72 return true;
73}
74
75static int usage(char *arg) {
76 fprintf(stderr, "usage: %s <hash> <test file>\n", arg);
77 return 1;
78}
79
80int main(int argc, char **argv) {
81 CRYPTO_library_init();
82
83 if (argc != 3) {
84 return usage(argv[0]);
85 }
86
87 TestCtx ctx = {std::string(argv[1])};
88
89 printf("# Generated by");
90 for (int i = 0; i < argc; i++) {
91 printf(" %s", argv[i]);
92 }
93 printf("\r\n\r\n");
94
95 return FileTestMainSilent(TestSHA, &ctx, argv[2]);
96}