blob: 2827023e6796f379eb2b9e800d3126d9aaa700f8 [file] [log] [blame]
Yingdi Yu8d7468f2014-02-21 14:49:45 -08001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
2/*
3 * Copyright (c) 2013, Regents of the University of California
4 * BSD license, See the LICENSE file for more information
5 * Author: Yingdi Yu <yingdi@cs.ucla.edu>
6 */
7
8#ifndef NDNSEC_UTIL_HPP
9#define NDNSEC_UTIL_HPP
10
11#include <iostream>
12#include <fstream>
13#include <string>
14#include <cstring>
15
16#include <boost/program_options/options_description.hpp>
17#include <boost/program_options/variables_map.hpp>
18#include <boost/program_options/parsers.hpp>
19#include <boost/date_time/posix_time/posix_time.hpp>
20#include <boost/tokenizer.hpp>
21#include <boost/asio.hpp>
22#include <boost/exception/all.hpp>
23
24
25#include <cryptopp/base64.h>
26#include <cryptopp/files.h>
27
28#include "security/key-chain.hpp"
29
30bool
31getPassword(std::string& password, const std::string& prompt)
32{
33 int result = false;
34
35 char* pw0 = NULL;
36
37 pw0 = getpass(prompt.c_str());
38 if(!pw0)
39 return false;
40 std::string password1 = pw0;
41 memset(pw0, 0, strlen(pw0));
42
43 pw0 = getpass("Confirm:");
44 if(!pw0)
45 {
46 char* pw1 = const_cast<char*>(password1.c_str());
47 memset(pw1, 0, password1.size());
48 return false;
49 }
50
51 if(!password1.compare(pw0))
52 {
53 result = true;
54 password.swap(password1);
55 }
56
57 char* pw1 = const_cast<char*>(password1.c_str());
58 memset(pw1, 0, password1.size());
59 memset(pw0, 0, strlen(pw0));
60
61 if(password.empty())
62 return false;
63
64 return result;
65}
66
67ndn::shared_ptr<ndn::IdentityCertificate>
68getIdentityCertificate(const std::string& fileName)
69{
70 std::istream* ifs;
71 std::istream* ffs = 0;
72 if(fileName == "-")
73 ifs = &std::cin;
74 else
75 {
76 ifs = new std::ifstream(fileName.c_str());
77 ffs = ifs;
78 }
79
80 ndn::OBufferStream os;
81 try
82 {
83 CryptoPP::FileSource ss2(*ifs, true, new CryptoPP::Base64Decoder(new CryptoPP::FileSink(os)));
84
85 if(ffs)
86 delete ffs;
87 ffs = 0;
88 ifs = 0;
89
90 }
91 catch(const CryptoPP::Exception& e)
92 {
93 if(ffs)
94 delete ffs;
95 ffs = 0;
96 ifs = 0;
97
98 std::cerr << "ERROR: " << e.what() << std::endl;
99 return ndn::shared_ptr<ndn::IdentityCertificate>();
100 }
101
102 try
103 {
104 ndn::shared_ptr<ndn::IdentityCertificate> identityCertificate = ndn::make_shared<ndn::IdentityCertificate>();
105 identityCertificate->wireDecode(ndn::Block(os.buf()));
106 return identityCertificate;
107 }
108 catch(const ndn::SecPublicInfo::Error& e)
109 {
110 std::cerr << "ERROR: " << e.what() << std::endl;
111 return ndn::shared_ptr<ndn::IdentityCertificate>();
112 }
113 catch(const ndn::SecTpm::Error& e)
114 {
115 std::cerr << "ERROR: " << e.what() << std::endl;
116 return ndn::shared_ptr<ndn::IdentityCertificate>();
117 }
118}
119
120#endif //NDNSEC_UTIL_HPP