aboutsummaryrefslogtreecommitdiffstats
path: root/src/cmd/dsa_sign.cpp
blob: edbf135c3fe63a476d6a352b3d1c580f82bb9f2f (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
#include "apps.h"

#if defined(BOTAN_HAS_DSA)

#include <botan/dsa.h>
#include <botan/pubkey.h>
#include <botan/base64.h>
#include <fstream>

namespace {

int dsa_sign(int argc, char* argv[])
   {
   using namespace Botan;

   const std::string SUFFIX = ".sig";

   if(argc != 4)
      {
      std::cout << "Usage: " << argv[0] << " keyfile messagefile passphrase"
                << std::endl;
      return 1;
      }

   try {
      std::string passphrase(argv[3]);

      std::ifstream message(argv[2], std::ios::binary);
      if(!message)
         {
         std::cout << "Couldn't read the message file." << std::endl;
         return 1;
         }

      std::string outfile = argv[2] + SUFFIX;
      std::ofstream sigfile(outfile.c_str());
      if(!sigfile)
         {
         std::cout << "Couldn't write the signature to "
                   << outfile << std::endl;
         return 1;
         }

      AutoSeeded_RNG rng;

      std::auto_ptr<PKCS8_PrivateKey> key(
         PKCS8::load_key(argv[1], rng, passphrase)
         );

      DSA_PrivateKey* dsakey = dynamic_cast<DSA_PrivateKey*>(key.get());

      if(!dsakey)
         {
         std::cout << "The loaded key is not a DSA key!\n";
         return 1;
         }

      PK_Signer signer(*dsakey, "EMSA1(SHA-1)");

      DataSource_Stream in(message);
      byte buf[4096] = { 0 };
      while(size_t got = in.read(buf, sizeof(buf)))
         signer.update(buf, got);

      sigfile << base64_encode(signer.signature(rng)) << "\n";
   }
   catch(std::exception& e)
      {
      std::cout << "Exception caught: " << e.what() << std::endl;
      }
   return 0;
   }

REGISTER_APP(dsa_sign);

}

#endif