NCBI C++ ToolKit
ncbi_encrypt.cpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 /* $Id: ncbi_encrypt.cpp 92179 2020-12-22 18:06:52Z grichenk $
2  * ===========================================================================
3  *
4  * PUBLIC DOMAIN NOTICE
5  * National Center for Biotechnology Information
6  *
7  * This software/database is a "United States Government Work" under the
8  * terms of the United States Copyright Act. It was written as part of
9  * the author's official duties as a United States Government employee and
10  * thus cannot be copyrighted. This software/database is freely available
11  * to the public for use. The National Library of Medicine and the U.S.
12  * Government have not placed any restriction on its use or reproduction.
13  *
14  * Although all reasonable efforts have been taken to ensure the accuracy
15  * and reliability of the software and data, the NLM and the U.S.
16  * Government do not and cannot warrant the performance or results that
17  * may be obtained by using this software or data. The NLM and the U.S.
18  * Government disclaim all warranties, express or implied, including
19  * warranties of performance, merchantability or fitness for any particular
20  * purpose.
21  *
22  * Please cite the author in any work or product based on this material.
23  *
24  * ===========================================================================
25  *
26  * Author: Aleksey Grichenko
27  *
28  * File Description:
29  * Encryption/decryption utility and key generator for CNcbiEncrypt.
30  *
31  */
32 
33 #include <ncbi_pch.hpp>
34 #include <corelib/ncbiapp.hpp>
35 #include <corelib/ncbiargs.hpp>
37 #include <util/random_gen.hpp>
38 
39 #include <common/test_assert.h> /* This header must go last */
40 
42 
43 
44 //////////////////////////////////////////////////////////////////////////////
45 //
46 // NCBI encryption application
47 //
48 
49 
51 {
52 public:
53  void Init(void);
54  int Run(void);
55 private:
56  void GenerateKey(void);
57  void Encrypt(void);
58  void Decrypt(void);
59 };
60 
61 
63 {
64  unique_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
65 
66  string prog_description = "NCBI encryption utility\n";
67  arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
68  prog_description, false);
69 
70  arg_desc->AddFlag("encrypt", "Encrypt input data (default action)", true);
71  arg_desc->AddFlag("decrypt", "Decrypt input data", true);
72  arg_desc->AddFlag("generate_key", "Generate encryption key", true);
73 
74  arg_desc->AddDefaultKey("i", "Input",
75  "input data file", CArgDescriptions::eInputFile, "-");
76  arg_desc->AddDefaultKey("o", "Output",
77  "output data file", CArgDescriptions::eOutputFile, "-");
78  arg_desc->AddOptionalKey("password", "Password",
79  "Password used for key generation", CArgDescriptions::eString);
80  arg_desc->AddOptionalKey("domain", "Domain",
81  "Domain to use for encryption", CArgDescriptions::eString);
82 
83  arg_desc->AddOptionalKey("severity", "Severity",
84  "Log message severity when reporting an outdated key usage",
86  arg_desc->SetConstraint("severity",
88  .AllowValue("Info")
89  .AllowValue("Warning")
90  .AllowValue("Error")
91  .AllowValue("Critical"));
92 
93  arg_desc->SetDependency("encrypt", CArgDescriptions::eExcludes, "decrypt");
94  arg_desc->SetDependency("generate_key", CArgDescriptions::eExcludes, "i");
95  arg_desc->SetDependency("generate_key", CArgDescriptions::eExcludes, "encrypt");
96  arg_desc->SetDependency("generate_key", CArgDescriptions::eExcludes, "decrypt");
97  arg_desc->SetDependency("generate_key", CArgDescriptions::eExcludes, "domain");
98  arg_desc->SetDependency("password", CArgDescriptions::eExcludes, "domain");
99  arg_desc->SetDependency("severity", CArgDescriptions::eRequires, "generate_key");
100 
101  SetupArgDescriptions(arg_desc.release());
102 }
103 
104 
106 {
107  const CArgs& args = GetArgs();
108  if ( args["generate_key"] ) {
109  GenerateKey();
110  }
111  else if ( args["decrypt"] ) {
112  Decrypt();
113  }
114  else { // Do not check 'encrypt' flag - this is the default operation
115  Encrypt();
116  }
117  return 0;
118 }
119 
120 
122 {
123  const CArgs& args = GetArgs();
124  string seed;
125  if ( args["password"] ) {
126  seed = args["password"].AsString();
127  }
128  else {
129  CRandom rand;
130  rand.Randomize();
131  seed.resize(32, 0);
132  for (size_t i = 0; i < seed.size(); i++) {
133  seed[i] = rand.GetRand(0, 255);
134  }
135  }
137  CNcbiOstream& out = args["o"].AsOutputFile();
138  out << key;
139  if ( args["severity"] ) {
140  out << "/" << args["severity"].AsString();
141  }
142  out << endl;
143 }
144 
145 
147 {
148  const CArgs& args = GetArgs();
149  string encr;
150  CNcbiIstream& in = args["i"].AsInputFile();
152  tmp << in.rdbuf();
153  string data = CNcbiOstrstreamToString(tmp);
154 
155  if ( args["password"] ) {
156  encr = CNcbiEncrypt::Encrypt(data, args["password"].AsString());
157  }
158  else if ( args["domain"] ) {
159  encr = CNcbiEncrypt::EncryptForDomain(data, args["domain"].AsString());
160  }
161  else {
162  encr = CNcbiEncrypt::Encrypt(data);
163  }
164 
165  CNcbiOstream& out = args["o"].AsOutputFile();
166  out << encr;
167  out.flush();
168 }
169 
170 
172 {
173  const CArgs& args = GetArgs();
174  string decr;
175  CNcbiIstream& in = args["i"].AsInputFile();
177  tmp << in.rdbuf();
178  string data = CNcbiOstrstreamToString(tmp);
180 
181  if ( args["password"] ) {
182  decr = CNcbiEncrypt::Decrypt(data, args["password"].AsString());
183  }
184  else if ( args["domain"] ) {
185  decr = CNcbiEncrypt::DecryptForDomain(data, args["domain"].AsString());
186  }
187  else {
188  decr = CNcbiEncrypt::Decrypt(data);
189  }
190 
191  CNcbiOstream& out = args["o"].AsOutputFile();
192  out << decr;
193  out.flush();
194 }
195 
196 
197 /////////////////////////////////////////////////////////////////////////////
198 // MAIN
199 
200 int main(int argc, const char* argv[])
201 {
202  return CNcbiEncryptApp().AppMain(argc, argv);
203 }
CArgAllow_Strings –.
Definition: ncbiargs.hpp:1641
CArgDescriptions –.
Definition: ncbiargs.hpp:541
CArgs –.
Definition: ncbiargs.hpp:379
int Run(void)
Run the application.
void Encrypt(void)
void GenerateKey(void)
void Init(void)
Initialize the application.
void Decrypt(void)
static string GenerateKey(const string &seed)
Generate an encryption/decryption key from the seed string.
static string DecryptForDomain(const string &encrypted_string, const string &domain)
Decrypt data using domain key.
static string EncryptForDomain(const string &original_string, const string &domain)
Encrypt data using domain key.
static string Encrypt(const string &original_string)
Encrypt a string using key from the 1st line of the 1st NCBI keys file.
static string Decrypt(const string &encrypted_string)
Decrypt a string using the matching key found in the NCBI keys files.
CNcbiOstrstreamToString class helps convert CNcbiOstrstream to a string Sample usage:
Definition: ncbistre.hpp:802
CRandom::
Definition: random_gen.hpp:66
std::ofstream out("events_result.xml")
main entry point for tests
static char tmp[3200]
Definition: utf8.c:42
char data[12]
Definition: iconv.c:80
virtual const CArgs & GetArgs(void) const
Get parsed command line arguments.
Definition: ncbiapp.cpp:305
int AppMain(int argc, const char *const *argv, const char *const *envp=0, EAppDiagStream diag=eDS_Default, const char *conf=NcbiEmptyCStr, const string &name=NcbiEmptyString)
Main function (entry point) for the NCBI application.
Definition: ncbiapp.cpp:819
virtual void SetupArgDescriptions(CArgDescriptions *arg_desc)
Setup the command line argument descriptions.
Definition: ncbiapp.cpp:1195
const CNcbiArguments & GetArguments(void) const
Get the application's cached unprocessed command-line arguments.
@ eRequires
One argument requires another.
Definition: ncbiargs.hpp:956
@ eExcludes
One argument excludes another.
Definition: ncbiargs.hpp:957
@ eInputFile
Name of file (must exist and be readable)
Definition: ncbiargs.hpp:595
@ eString
An arbitrary string.
Definition: ncbiargs.hpp:589
@ eOutputFile
Name of file (must be writable)
Definition: ncbiargs.hpp:596
TValue GetRand(void)
Get the next random number in the interval [0..GetMax()] (inclusive)
Definition: random_gen.hpp:238
void Randomize(void)
Re-initialize (re-seed) the generator using platform-specific randomization.
Definition: random_gen.cpp:267
IO_PREFIX::ostream CNcbiOstream
Portable alias for ostream.
Definition: ncbistre.hpp:149
IO_PREFIX::istream CNcbiIstream
Portable alias for istream.
Definition: ncbistre.hpp:146
static void TruncateSpacesInPlace(string &str, ETrunc where=eTrunc_Both)
Truncate spaces in a string (in-place)
Definition: ncbistr.cpp:3201
int i
const struct ncbi::grid::netcache::search::fields::KEY key
int main(int argc, const char *argv[])
USING_NCBI_SCOPE
Defines the CNcbiApplication and CAppException classes for creating NCBI applications.
Defines command line argument related classes.
std::istream & in(std::istream &in_, double &x_)
Defines NCBI C++ secure resources API.
static int seed
Definition: test_table.cpp:132
Modified on Wed Jun 19 17:00:37 2024 by modify_doxy.py rev. 669887