aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/misc/rfc3394/rfc3394.cpp
blob: 8e69933c71788e7663c4128808f28b465746b7b9 (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
/*
* AES Key Wrap (RFC 3394)
* (C) 2011 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/rfc3394.h>
#include <botan/nist_keywrap.h>
#include <botan/block_cipher.h>

namespace Botan {

secure_vector<uint8_t> rfc3394_keywrap(const secure_vector<uint8_t>& key,
                                       const SymmetricKey& kek)
   {
   if(kek.size() != 16 && kek.size() != 24 && kek.size() != 32)
      throw Invalid_Argument("Bad KEK length " + std::to_string(kek.size()) + " for NIST key wrap");

   const std::string cipher_name = "AES-" + std::to_string(8*kek.size());
   std::unique_ptr<BlockCipher> aes(BlockCipher::create_or_throw(cipher_name));
   aes->set_key(kek);

   std::vector<uint8_t> wrapped = nist_key_wrap(key.data(), key.size(), *aes);
   return secure_vector<uint8_t>(wrapped.begin(), wrapped.end());
   }

secure_vector<uint8_t> rfc3394_keyunwrap(const secure_vector<uint8_t>& key,
                                         const SymmetricKey& kek)
   {
   if(key.size() < 16 || key.size() % 8 != 0)
      throw Invalid_Argument("Bad input key size for NIST key unwrap");

   if(kek.size() != 16 && kek.size() != 24 && kek.size() != 32)
      throw Invalid_Argument("Bad KEK length " + std::to_string(kek.size()) + " for NIST key unwrap");

   const std::string cipher_name = "AES-" + std::to_string(8*kek.size());
   std::unique_ptr<BlockCipher> aes(BlockCipher::create_or_throw(cipher_name));
   aes->set_key(kek);

   return nist_key_unwrap(key.data(), key.size(), *aes);
   }

}