File: encrypt2.cpp

package info (click to toggle)
botan1.10 1.10.8-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 12,288 kB
  • sloc: cpp: 61,853; python: 1,687; asm: 1,247; ansic: 252; perl: 89; sh: 52; makefile: 38; lisp: 34
file content (66 lines) | stat: -rw-r--r-- 1,688 bytes parent folder | download | duplicates (4)
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
/*
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/

#include <botan/botan.h>
#include <botan/pbkdf2.h>
#include <botan/hmac.h>
#include <botan/sha160.h>

#include <fstream>

using namespace Botan;

int main()
   {
   Botan::LibraryInitializer init;

   AutoSeeded_RNG rng;

   std::string passphrase = "secret";

   std::ifstream infile("readme.txt");
   std::ofstream outfile("readme.txt.enc");

   PKCS5_PBKDF2 pbkdf2(new HMAC(new SHA_160));

   const u32bit PBKDF2_ITERATIONS = 8192;

   SecureVector<byte> salt(8);
   rng.randomize(&salt[0], salt.size());

   SecureVector<byte> master_key = pbkdf2.derive_key(48, passphrase,
                                                     &salt[0], salt.size(),
                                                     PBKDF2_ITERATIONS).bits_of();

   KDF* kdf = get_kdf("KDF2(SHA-1)");

   SymmetricKey key = kdf->derive_key(20, master_key, "cipher key");

   SymmetricKey mac_key = kdf->derive_key(20, master_key, "hmac key");

   InitializationVector iv = kdf->derive_key(8, master_key, "cipher iv");

   Pipe pipe(new Fork(
                new Chain(
                   get_cipher("Blowfish/CBC/PKCS7", key, iv, ENCRYPTION),
                   new Base64_Encoder,
                   new DataSink_Stream(outfile)
                   ),
                new Chain(
                   new MAC_Filter("HMAC(SHA-1)", mac_key),
                   new Hex_Encoder)
                )
      );

   outfile.write((const char*)salt.begin(), salt.size());

   pipe.start_msg();
   infile >> pipe;
   pipe.end_msg();

   SecureVector<byte> hmac = pipe.read_all(1);
   outfile.write((const char*)hmac.begin(), hmac.size());
   }