aboutsummaryrefslogtreecommitdiffstats
path: root/src/cmd/pkcs8.cpp
blob: 7bc1c25614116eca8a87b40c3a021ffed8721585 (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
/*
* (C) 2015 René Korthaus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "apps.h"
#include <iostream>
#include <fstream>
#include <string>
#include <memory>
#include <chrono>

#if defined(BOTAN_HAS_PUBLIC_KEY_CRYPTO)
#include <botan/pk_keys.h>
#include <botan/pkcs8.h>
#include <botan/x509_key.h>

using namespace Botan;

namespace {

int pkcs8(const std::vector<std::string> &args)
   {
   OptionParser opts("in=|out=|passin=|passout=|pbe=|pubout");
   opts.parse(args);

   const std::string passin = opts.value_or_else("passin", "");
   const std::string passout = opts.value_or_else("passout", "");
   const std::string pbe = opts.value_or_else("pbe", "");

   if(args.size() < 3)
      {
      opts.help(std::cout, "pkcs8");
      return 1;
      }

   try
      {
      std::ofstream out_key(opts.value("out"));
         
      if (!out_key)
         {
         std::cout << "Couldn't write key" << std::endl;
         return 1;
         }

      AutoSeeded_RNG rng;
      std::unique_ptr<Private_Key> key(PKCS8::load_key(opts.value("in"), rng, passin));
                
      if(opts.is_set("pubout"))
         {
         out_key << X509::PEM_encode(*key);
         }
         else
         {
         if(passout.empty())
            out_key << PKCS8::PEM_encode(*key);
         else
            out_key << PKCS8::PEM_encode(*key, rng, passout, std::chrono::milliseconds(300), pbe);
         }
       }
   catch(std::exception& e)
      {
      std::cout << "Exception caught: " << e.what() << std::endl;
      return 2;
      }

   return 0;
   }

REGISTER_APP(pkcs8);

}

#endif