blob: 59c7e10358f5a8a0f7138ba6b6fefe0c1e2c4844 [file] [log] [blame]
Robert Sloan8ff03552017-06-14 12:40:58 -07001/* 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_hmac_test processes a NIST CAVP HMAC test vector request file and emits
16// the corresponding response.
17
18#include <stdlib.h>
19
20#include <openssl/crypto.h>
21#include <openssl/hmac.h>
22
23#include "../crypto/test/file_test.h"
24#include "cavp_test_util.h"
25
26
27static bool TestHMAC(FileTest *t, void *arg) {
28 std::string md_len_str;
29 if (!t->GetInstruction(&md_len_str, "L")) {
30 return false;
31 }
32 const size_t md_len = strtoul(md_len_str.c_str(), nullptr, 0);
33
34 const EVP_MD *md;
35 switch (md_len) {
36 case 20:
37 md = EVP_sha1();
38 break;
39 case 28:
40 md = EVP_sha224();
41 break;
42 case 32:
43 md = EVP_sha256();
44 break;
45 case 48:
46 md = EVP_sha384();
47 break;
48 case 64:
49 md = EVP_sha512();
50 break;
51 default:
52 return false;
53 }
54
55 std::string count_str, k_len_str, t_len_str;
56 std::vector<uint8_t> key, msg;
57 if (!t->GetAttribute(&count_str, "Count") ||
58 !t->GetAttribute(&k_len_str, "Klen") ||
59 !t->GetAttribute(&t_len_str, "Tlen") ||
60 !t->GetBytes(&key, "Key") ||
61 !t->GetBytes(&msg, "Msg")) {
62 return false;
63 }
64
65 size_t k_len = strtoul(k_len_str.c_str(), nullptr, 0);
66 size_t t_len = strtoul(t_len_str.c_str(), nullptr, 0);
67 if (key.size() < k_len) {
68 return false;
69 }
70 unsigned out_len;
71 uint8_t out[EVP_MAX_MD_SIZE];
72 if (HMAC(md, key.data(), k_len, msg.data(), msg.size(), out, &out_len) ==
73 NULL) {
74 return false;
75 }
76
77 if (out_len < t_len) {
78 return false;
79 }
80
81 printf("%s", t->CurrentTestToString().c_str());
82 printf("Mac = %s\r\n\r\n", EncodeHex(out, t_len).c_str());
83
84 return true;
85}
86
87static int usage(char *arg) {
88 fprintf(stderr, "usage: %s <test file>\n", arg);
89 return 1;
90}
91
92int cavp_hmac_test_main(int argc, char **argv) {
93 if (argc != 2) {
94 return usage(argv[0]);
95 }
96
97 FileTest::Options opts;
98 opts.path = argv[1];
99 opts.callback = TestHMAC;
100 opts.silent = true;
101 opts.comment_callback = EchoComment;
102 return FileTestMain(opts);
103}