aboutsummaryrefslogtreecommitdiffstats
path: root/src/tests/test_mac.cpp
blob: 6ab87274f12e672f43046365f0196f8f87bd03df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* (C) 2014,2015 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "tests.h"

#if defined(BOTAN_HAS_MAC)

#include <botan/lookup.h>
#include <botan/mac.h>
#include <botan/hex.h>
#include <iostream>
#include <fstream>

using namespace Botan;

namespace {

size_t mac_test(const std::string& algo,
                const std::string& key_hex,
                const std::string& in_hex,
                const std::string& out_hex)
   {
   const std::vector<std::string> providers = get_mac_providers(algo);
   size_t fails = 0;

   if(providers.empty())
      {
      std::cout << "Unknown algo " << algo << std::endl;
      ++fails;
      }

   for(auto provider: providers)
      {
      std::unique_ptr<MessageAuthenticationCode> mac(get_mac(algo, provider));

      if(!mac)
         {
         std::cout << "Unable to get " << algo << " from " << provider << std::endl;
         ++fails;
         continue;
         }

      const std::vector<byte> in = hex_decode(in_hex);
      const std::vector<byte> exp = hex_decode(out_hex);

      mac->set_key(hex_decode(key_hex));

      mac->update(in);

      const std::vector<byte> out = unlock(mac->final());

      if(out != exp)
         {
         std::cout << algo << " " << provider << " got " << hex_encode(out) << " != " << hex_encode(exp) << std::endl;
         ++fails;
         }

      if(in.size() > 2)
         {
         mac->set_key(hex_decode(key_hex));
         mac->update(in[0]);
         mac->update(&in[1], in.size() - 2);
         mac->update(in[in.size()-1]);

         const std::vector<byte> out2 = unlock(mac->final());

         if(out2 != exp)
            {
            std::cout << algo << " " << provider << " got " << hex_encode(out2) << " != " << hex_encode(exp) << std::endl;
            ++fails;
            }
         }
      }

   return fails;
   }

}

size_t test_mac()
   {
   auto test = [](const std::string& input)
      {
      std::ifstream vec(input);

      return run_tests_bb(vec, "Mac", "Out", true,
             [](std::map<std::string, std::string> m) -> size_t
             {
             return mac_test(m["Mac"], m["Key"], m["In"], m["Out"]);
             });
      };

   return run_tests_in_dir(TEST_DATA_DIR "/mac", test);
   }

#else

SKIP_TEST(mac);

#endif // BOTAN_HAS_MAC