1/* Copyright (c) 2015, 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#include <stdio.h>
16#include <string.h>
17
18#include <vector>
19
20#include <openssl/crypto.h>
21#include <openssl/poly1305.h>
22
23#include "../test/file_test.h"
24
25
26// |CRYPTO_poly1305_finish| requires a 16-byte-aligned output.
27#if defined(OPENSSL_WINDOWS)
28// MSVC doesn't support C++11 |alignas|.
29#define ALIGNED __declspec(align(16))
30#else
31#define ALIGNED alignas(16)
32#endif
33
34static bool TestPoly1305(FileTest *t, void *arg) {
35  std::vector<uint8_t> key, in, mac;
36  if (!t->GetBytes(&key, "Key") ||
37      !t->GetBytes(&in, "Input") ||
38      !t->GetBytes(&mac, "MAC")) {
39    return false;
40  }
41  if (key.size() != 32 || mac.size() != 16) {
42    t->PrintLine("Invalid test");
43    return false;
44  }
45
46  // Test single-shot operation.
47  poly1305_state state;
48  CRYPTO_poly1305_init(&state, key.data());
49  CRYPTO_poly1305_update(&state, in.data(), in.size());
50  ALIGNED uint8_t out[16];
51  CRYPTO_poly1305_finish(&state, out);
52  if (!t->ExpectBytesEqual(out, 16, mac.data(), mac.size())) {
53    t->PrintLine("Single-shot Poly1305 failed.");
54    return false;
55  }
56
57  // Test streaming byte-by-byte.
58  CRYPTO_poly1305_init(&state, key.data());
59  for (size_t i = 0; i < in.size(); i++) {
60    CRYPTO_poly1305_update(&state, &in[i], 1);
61  }
62  CRYPTO_poly1305_finish(&state, out);
63  if (!t->ExpectBytesEqual(out, 16, mac.data(), mac.size())) {
64    t->PrintLine("Streaming Poly1305 failed.");
65    return false;
66  }
67
68  return true;
69}
70
71int main(int argc, char **argv) {
72  CRYPTO_library_init();
73
74  if (argc != 2) {
75    fprintf(stderr, "%s <test file>\n", argv[0]);
76    return 1;
77  }
78
79  return FileTestMain(TestPoly1305, nullptr, argv[1]);
80}
81