1 /* 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.
17 
18 #include <stdlib.h>
19 
20 #include <openssl/crypto.h>
21 #include <openssl/digest.h>
22 
23 #include "../crypto/test/file_test.h"
24 #include "../crypto/test/test_util.h"
25 #include "cavp_test_util.h"
26 
27 namespace {
28 
29 struct TestCtx {
30   std::string hash;
31 };
32 
33 }
34 
TestSHA(FileTest * t,void * arg)35 static bool TestSHA(FileTest *t, void *arg) {
36   TestCtx *ctx = reinterpret_cast<TestCtx *>(arg);
37 
38   const EVP_MD *md = EVP_get_digestbyname(ctx->hash.c_str());
39   if (md == nullptr) {
40     return false;
41   }
42   const size_t md_len = EVP_MD_size(md);
43 
44   std::string out_len;
45   if (!t->GetInstruction(&out_len, "L") ||
46       md_len != strtoul(out_len.c_str(), nullptr, 0)) {
47     return false;
48   }
49 
50   std::string msg_len_str;
51   std::vector<uint8_t> msg;
52   if (!t->GetAttribute(&msg_len_str, "Len") ||
53       !t->GetBytes(&msg, "Msg")) {
54     return false;
55   }
56 
57   size_t msg_len = strtoul(msg_len_str.c_str(), nullptr, 0);
58   if (msg_len % 8 != 0 ||
59       msg_len / 8 > msg.size()) {
60     return false;
61   }
62   msg_len /= 8;
63 
64   std::vector<uint8_t> out;
65   out.resize(md_len);
66   unsigned digest_len;
67   if (!EVP_Digest(msg.data(), msg_len, out.data(), &digest_len, md, nullptr) ||
68       digest_len != out.size()) {
69     return false;
70   }
71 
72   printf("%s", t->CurrentTestToString().c_str());
73   printf("MD = %s\r\n\r\n", EncodeHex(out).c_str());
74 
75   return true;
76 }
77 
usage(char * arg)78 static int usage(char *arg) {
79   fprintf(stderr, "usage: %s <hash> <test file>\n", arg);
80   return 1;
81 }
82 
cavp_sha_test_main(int argc,char ** argv)83 int cavp_sha_test_main(int argc, char **argv) {
84   if (argc != 3) {
85     return usage(argv[0]);
86   }
87 
88   TestCtx ctx = {std::string(argv[1])};
89 
90   FileTest::Options opts;
91   opts.path = argv[2];
92   opts.callback = TestSHA;
93   opts.arg = &ctx;
94   opts.silent = true;
95   opts.comment_callback = EchoComment;
96   return FileTestMain(opts);
97 }
98