aboutsummaryrefslogtreecommitdiffstats
path: root/doc/examples/credentials.h
blob: e97d28e5d24396b6fb6512901e0471c2a823992a (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

#ifndef EXAMPLE_CREDENTIALS_MANAGER_H__
#define EXAMPLE_CREDENTIALS_MANAGER_H__

#include <botan/credentials_manager.h>
#include <iostream>

bool value_exists(const std::vector<std::string>& vec,
                  const std::string& val)
   {
   for(size_t i = 0; i != vec.size(); ++i)
      if(vec[i] == val)
         return true;
   return false;
   }

class Credentials_Manager_Simple : public Botan::Credentials_Manager
   {
   public:
      Credentials_Manager_Simple(Botan::RandomNumberGenerator& rng) : rng(rng) {}

      std::vector<Botan::X509_Certificate> cert_chain(
         const std::vector<std::string>& cert_key_types,
         const std::string& type,
         const std::string& context)
         {
         std::vector<Botan::X509_Certificate> certs;

         try
            {
            if(type == "tls-server")
               {
               const std::string hostname = (context == "" ? "localhost" : context);

               if(value_exists(cert_key_types, "RSA"))
                  {
                  Botan::X509_Certificate cert(hostname + ".crt");
                  Botan::Private_Key* key = Botan::PKCS8::load_key(hostname + ".key", rng);

                  certs_and_keys[cert] = key;
                  certs.push_back(cert);
                  }
               else if(value_exists(cert_key_types, "DSA"))
                  {
                  Botan::X509_Certificate cert(hostname + ".dsa.crt");
                  Botan::Private_Key* key = Botan::PKCS8::load_key(hostname + ".dsa.key", rng);

                  certs_and_keys[cert] = key;
                  certs.push_back(cert);
                  }
               }
            else if(type == "tls-client")
               {
               Botan::X509_Certificate cert("user-rsa.crt");
               Botan::Private_Key* key = Botan::PKCS8::load_key("user-rsa.key", rng);

               certs_and_keys[cert] = key;
               certs.push_back(cert);
               }
            }
         catch(std::exception& e)
            {
            std::cout << e.what() << "\n";
            }

         return certs;
         }

      Botan::Private_Key* private_key_for(const Botan::X509_Certificate& cert,
                                          const std::string& type,
                                          const std::string& context)
         {
         return certs_and_keys[cert];
         }

   private:
      Botan::RandomNumberGenerator& rng;
      std::map<Botan::X509_Certificate, Botan::Private_Key*> certs_and_keys;
   };

#endif