Open-Transactions  0.93.0-ge03d287
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
OTCrypto.cpp
Go to the documentation of this file.
1 /************************************************************
2  *
3  * OTCrypto.cpp
4  *
5  * Abstract base class for all crypto code (ideally.)
6  *
7  * Plus: initial implementation based on OpenSSL.
8  * (OTCrypto_OpenSSL)
9  *
10  */
11 
12 /************************************************************
13  -----BEGIN PGP SIGNED MESSAGE-----
14  Hash: SHA1
15 
16  * OPEN TRANSACTIONS
17  *
18  * Financial Cryptography and Digital Cash
19  * Library, Protocol, API, Server, CLI, GUI
20  *
21  * -- Anonymous Numbered Accounts.
22  * -- Untraceable Digital Cash.
23  * -- Triple-Signed Receipts.
24  * -- Cheques, Vouchers, Transfers, Inboxes.
25  * -- Basket Currencies, Markets, Payment Plans.
26  * -- Signed, XML, Ricardian-style Contracts.
27  * -- Scripted smart contracts.
28  *
29  * Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym)
30  *
31  * EMAIL:
33  *
34  * BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ
35  *
36  * KEY FINGERPRINT (PGP Key in license file):
37  * 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E
38  *
39  * OFFICIAL PROJECT WIKI(s):
40  * https://github.com/FellowTraveler/Moneychanger
41  * https://github.com/FellowTraveler/Open-Transactions/wiki
42  *
43  * WEBSITE:
44  * http://www.OpenTransactions.org/
45  *
46  * Components and licensing:
47  * -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3
48  * -- otlib.........A class library.......LICENSE:...LAGPLv3
49  * -- otapi.........A client API..........LICENSE:...LAGPLv3
50  * -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3
51  * -- otserver......Server Application....LICENSE:....AGPLv3
52  * Github.com/FellowTraveler/Open-Transactions/wiki/Components
53  *
54  * All of the above OT components were designed and written by
55  * Fellow Traveler, with the exception of Moneychanger, which
56  * was contracted out to Vicky C ([email protected]).
57  * The open-source community has since actively contributed.
58  *
59  * -----------------------------------------------------
60  *
61  * LICENSE:
62  * This program is free software: you can redistribute it
63  * and/or modify it under the terms of the GNU Affero
64  * General Public License as published by the Free Software
65  * Foundation, either version 3 of the License, or (at your
66  * option) any later version.
67  *
68  * ADDITIONAL PERMISSION under the GNU Affero GPL version 3
69  * section 7: (This paragraph applies only to the LAGPLv3
70  * components listed above.) If you modify this Program, or
71  * any covered work, by linking or combining it with other
72  * code, such other code is not for that reason alone subject
73  * to any of the requirements of the GNU Affero GPL version 3.
74  * (==> This means if you are only using the OT API, then you
75  * don't have to open-source your code--only your changes to
76  * Open-Transactions itself must be open source. Similar to
77  * LGPLv3, except it applies to software-as-a-service, not
78  * just to distributing binaries.)
79  *
80  * Extra WAIVER for OpenSSL, Lucre, and all other libraries
81  * used by Open Transactions: This program is released under
82  * the AGPL with the additional exemption that compiling,
83  * linking, and/or using OpenSSL is allowed. The same is true
84  * for any other open source libraries included in this
85  * project: complete waiver from the AGPL is hereby granted to
86  * compile, link, and/or use them with Open-Transactions,
87  * according to their own terms, as long as the rest of the
88  * Open-Transactions terms remain respected, with regard to
89  * the Open-Transactions code itself.
90  *
91  * Lucre License:
92  * This code is also "dual-license", meaning that Ben Lau-
93  * rie's license must also be included and respected, since
94  * the code for Lucre is also included with Open Transactions.
95  * See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt
96  * The Laurie requirements are light, but if there is any
97  * problem with his license, simply remove the Lucre code.
98  * Although there are no other blind token algorithms in Open
99  * Transactions (yet. credlib is coming), the other functions
100  * will continue to operate.
101  * See Lucre on Github: https://github.com/benlaurie/lucre
102  * -----------------------------------------------------
103  * You should have received a copy of the GNU Affero General
104  * Public License along with this program. If not, see:
105  * http://www.gnu.org/licenses/
106  *
107  * If you would like to use this software outside of the free
108  * software license, please contact FellowTraveler.
109  * (Unfortunately many will run anonymously and untraceably,
110  * so who could really stop them?)
111  *
112  * DISCLAIMER:
113  * This program is distributed in the hope that it will be
114  * useful, but WITHOUT ANY WARRANTY; without even the implied
115  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
116  * PURPOSE. See the GNU Affero General Public License for
117  * more details.
118 
119  -----BEGIN PGP SIGNATURE-----
120  Version: GnuPG v1.4.9 (Darwin)
121 
122  iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC
123  vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk
124  KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m
125  aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU
126  LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1
127  sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn
128  oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN
129  TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg
130  x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh
131  nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G
132  M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd
133  kamH0Y/n11lCvo1oQxM+
134  =uSzz
135  -----END PGP SIGNATURE-----
136  **************************************************************/
137 
138 #include "stdafx.hpp"
139 
140 #include "crypto/OTCrypto.hpp"
141 #include "OTLog.hpp"
142 #include "crypto/OTPassword.hpp"
143 #include "crypto/OTPasswordData.hpp"
144 #include "util/OTPaths.hpp"
145 #include "OTPseudonym.hpp"
146 #include "crypto/OTSignature.hpp"
147 #include "OTStorage.hpp"
148 #include "util/stacktrace.h"
149 
150 #include <bigint/BigIntegerLibrary.hh>
151 
152 #include <thread>
153 
154 extern "C" {
155 #ifdef _WIN32
156 #else
157 #include <arpa/inet.h> // For htonl()
158 #include <unistd.h>
159 #include <sys/types.h>
160 #include <sys/resource.h>
161 #endif
162 }
163 
164 #if defined(OT_CRYPTO_USING_OPENSSL)
165 
166 extern "C" {
167 #include <openssl/bio.h>
168 #include <openssl/buffer.h>
169 #include <openssl/evp.h>
170 #include <openssl/pem.h>
171 #include <openssl/rsa.h>
172 #include <openssl/dsa.h>
173 #include <openssl/err.h>
174 #include <openssl/ui.h>
175 #include <openssl/rand.h>
176 #include <openssl/crypto.h>
177 #include <openssl/asn1.h>
178 #include <openssl/objects.h>
179 #include <openssl/ssl.h>
180 #include <openssl/sha.h>
181 #include <openssl/conf.h>
182 #include <openssl/x509v3.h>
183 
184 #ifndef OPENSSL_NO_ENGINE
185 #include <openssl/engine.h>
186 #endif
187 }
188 
190 #include "crypto/OpenSSL_BIO.hpp"
191 
192 #elif defined(OT_CRYPTO_USING_GPG)
193 
194 #else
195 
196 #endif
197 
198 #ifdef __APPLE__
199 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
200 #endif
201 
202 namespace opentxs
203 {
204 
205 // OpenSSL / Crypto-lib d-pointer
206 #if defined(OT_CRYPTO_USING_GPG)
207 
208 // Someday }:-) OTCrypto_GPG
209 
210 #elif defined(OT_CRYPTO_USING_OPENSSL)
211 
213 {
214 public:
215  // These are protected because they contain OpenSSL-specific parameters.
216 
217  bool SignContractDefaultHash(const OTString& strContractUnsigned,
218  const EVP_PKEY* pkey,
219  OTSignature& theSignature, // output
220  const OTPasswordData* pPWData = nullptr) const;
221 
223  const OTString& strContractToVerify, const EVP_PKEY* pkey,
224  const OTSignature& theSignature,
225  const OTPasswordData* pPWData = nullptr) const;
226 
227  // Sign or verify using the actual OpenSSL EVP_PKEY
228  //
229  bool SignContract(const OTString& strContractUnsigned, const EVP_PKEY* pkey,
230  OTSignature& theSignature, // output
231  const OTString& strHashType,
232  const OTPasswordData* pPWData = nullptr) const;
233 
234  bool VerifySignature(const OTString& strContractToVerify,
235  const EVP_PKEY* pkey, const OTSignature& theSignature,
236  const OTString& strHashType,
237  const OTPasswordData* pPWData = nullptr) const;
238 
239  static const EVP_MD* GetOpenSSLDigestByName(const OTString& theName);
240 };
241 
242 #else // Apparently NO crypto engine is defined!
243 
244 // Perhaps error out here...
245 
246 #endif // if defined (OT_CRYPTO_USING_OPENSSL), elif defined
247  // (OT_CRYPTO_USING_GPG), else, endif.
248 
249 // class OTCrypto
250 //
251 // To someday get us to the point where we can easily swap crypto libs.
252 // For now, just for static init / cleanup functions we can call from
253 // OTLog Init/Cleanup, and move the more "crypto" related stuff to this file.
254 //
255 
256 // todo optimzation maybe this should be 10000 instead of 65535
257 //
258 #define OT_DEFAULT_ITERATION_COUNT 65535 // in bytes
259 #define OT_DEFAULT_SYMMETRIC_SALT_SIZE 8 // in bytes
260 #define OT_DEFAULT_SYMMETRIC_KEY_SIZE 16 // in bytes
261 #define OT_DEFAULT_SYMMETRIC_KEY_SIZE_MAX 64 // in bytes == 512 bits
262 #define OT_DEFAULT_SYMMETRIC_IV_SIZE 16 // in bytes
263 #define OT_DEFAULT_SYMMETRIC_BUFFER_SIZE 4096 // in bytes
264 #define OT_DEFAULT_PUBLIC_KEYSIZE 128 // in bytes == 4096 bits
265 #define OT_DEFAULT_PUBLIC_KEYSIZE_MAX 512 // in bytes == 1024 bits
266 #define OT_DEFAULT_DIGEST_1_SIZE 32 // in bytes == 256 bits.
267 #define OT_DEFAULT_DIGEST_2_SIZE 64 // in bytes == 512 bits.
268 
269 #define OT_KEY_ITERATION_COUNT "iteration_count"
270 #define OT_KEY_SYMMETRIC_SALT_SIZE "symmetric_salt_size"
271 #define OT_KEY_SYMMETRIC_KEY_SIZE "symmetric_key_size"
272 #define OT_KEY_SYMMETRIC_KEY_SIZE_MAX "symmetric_key_size_max"
273 #define OT_KEY_SYMMETRIC_IV_SIZE "symmetric_iv_size"
274 #define OT_KEY_SYMMETRIC_BUFFER_SIZE "symmetric_buffer_size"
275 #define OT_KEY_PUBLIC_KEYSIZE "public_keysize"
276 #define OT_KEY_PUBLIC_KEYSIZE_MAX "public_keysize_max"
277 #define OT_KEY_DIGEST_1_SIZE "digest_1_size"
278 #define OT_KEY_DIGEST_2_SIZE "digest_2_size"
279 
280 const int32_t* OTCryptoConfig::sp_nIterationCount = nullptr;
281 const int32_t* OTCryptoConfig::sp_nSymmetricSaltSize = nullptr;
282 const int32_t* OTCryptoConfig::sp_nSymmetricKeySize = nullptr;
283 const int32_t* OTCryptoConfig::sp_nSymmetricKeySizeMax = nullptr;
284 const int32_t* OTCryptoConfig::sp_nSymmetricIvSize = nullptr;
285 const int32_t* OTCryptoConfig::sp_nSymmetricBufferSize = nullptr;
286 const int32_t* OTCryptoConfig::sp_nPublicKeysize = nullptr;
287 const int32_t* OTCryptoConfig::sp_nPublicKeysizeMax = nullptr;
288 const int32_t* OTCryptoConfig::sp_nDigest1Size = nullptr;
289 const int32_t* OTCryptoConfig::sp_nDigest2Size = nullptr;
290 
291 bool OTCryptoConfig::GetSetAll()
292 {
293  OTSettings config(OTPaths::GlobalConfigFile());
294 
295  config.Reset();
296 
297  if (!config.Load()) return false;
298 
299  if (!GetSetValue(config, OT_KEY_ITERATION_COUNT, OT_DEFAULT_ITERATION_COUNT,
300  sp_nIterationCount))
301  return false;
302  if (!GetSetValue(config, OT_KEY_SYMMETRIC_SALT_SIZE,
303  OT_DEFAULT_SYMMETRIC_SALT_SIZE, sp_nSymmetricSaltSize))
304  return false;
305  if (!GetSetValue(config, OT_KEY_SYMMETRIC_KEY_SIZE,
306  OT_DEFAULT_SYMMETRIC_KEY_SIZE, sp_nSymmetricKeySize))
307  return false;
308  if (!GetSetValue(config, OT_KEY_SYMMETRIC_KEY_SIZE_MAX,
310  sp_nSymmetricKeySizeMax))
311  return false;
312  if (!GetSetValue(config, OT_KEY_SYMMETRIC_IV_SIZE,
313  OT_DEFAULT_SYMMETRIC_IV_SIZE, sp_nSymmetricIvSize))
314  return false;
315  if (!GetSetValue(config, OT_KEY_SYMMETRIC_BUFFER_SIZE,
316  OT_DEFAULT_SYMMETRIC_BUFFER_SIZE, sp_nSymmetricBufferSize))
317  return false;
318  if (!GetSetValue(config, OT_KEY_PUBLIC_KEYSIZE, OT_DEFAULT_PUBLIC_KEYSIZE,
319  sp_nPublicKeysize))
320  return false;
321  if (!GetSetValue(config, OT_KEY_PUBLIC_KEYSIZE_MAX,
322  OT_DEFAULT_PUBLIC_KEYSIZE_MAX, sp_nPublicKeysizeMax))
323  return false;
324  if (!GetSetValue(config, OT_KEY_DIGEST_1_SIZE, OT_DEFAULT_DIGEST_1_SIZE,
325  sp_nDigest1Size))
326  return false;
327  if (!GetSetValue(config, OT_KEY_DIGEST_2_SIZE, OT_DEFAULT_DIGEST_2_SIZE,
328  sp_nDigest2Size))
329  return false;
330 
331  if (!config.Save()) return false;
332 
333  config.Reset();
334 
335  return true;
336 }
337 
338 bool OTCryptoConfig::GetSetValue(OTSettings& config, std::string strKeyName,
339  int32_t nDefaultValue,
340  const int32_t*& out_nValue)
341 
342 {
343  if (strKeyName.empty()) return false;
344  if (3 > strKeyName.size()) return false;
345 
346  {
347  bool bIsNew = false;
348  int64_t nValue = 0;
349  config.CheckSet_long("crypto", strKeyName, nDefaultValue, nValue,
350  bIsNew);
351 
352  if (nullptr != out_nValue) {
353  delete out_nValue;
354  out_nValue = nullptr;
355  }
356 
357  out_nValue =
358  new int32_t(bIsNew ? nDefaultValue : static_cast<int32_t>(nValue));
359  }
360 
361  return true;
362 }
363 
364 const int32_t& OTCryptoConfig::GetValue(const int32_t*& pValue)
365 {
366  if (nullptr == pValue) {
367  if (!GetSetAll()) OT_FAIL;
368  }
369  if (nullptr == pValue) {
370  OT_FAIL;
371  }
372  return *pValue;
373 }
374 
376 {
377  return GetValue(sp_nIterationCount);
378 }
380 {
381  return GetValue(sp_nSymmetricSaltSize);
382 }
384 {
385  return GetValue(sp_nSymmetricKeySize);
386 }
388 {
389  return GetValue(sp_nSymmetricKeySizeMax);
390 }
392 {
393  return GetValue(sp_nSymmetricIvSize);
394 }
396 {
397  return GetValue(sp_nSymmetricBufferSize);
398 }
400 {
401  return GetValue(sp_nPublicKeysize);
402 }
404 {
405  return GetValue(sp_nPublicKeysizeMax);
406 }
408 {
409  return GetValue(sp_nDigest1Size);
410 }
412 {
413  return GetValue(sp_nDigest2Size);
414 }
415 
416 // static
417 int32_t OTCrypto::s_nCount =
418  0; // Instance count, should never exceed 1. (At this point, anyway.)
419 
421 {
422 }
424 {
425 }
426 
427 bool OTCrypto::IsBase62(const std::string& str) const
428 {
429  return str.find_first_not_of("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHI"
430  "JKLMNOPQRSTUVWXYZ") == std::string::npos;
431 }
432 
433 /*
434 extern "C"
435 {
436 void SetStdinEcho(int32_t enable)
437 {
438 #ifdef WIN32
439  HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
440  DWORD mode;
441  GetConsoleMode(hStdin, &mode);
442 
443  if( !enable )
444  mode &= ~ENABLE_ECHO_INPUT;
445  else
446  mode |= ENABLE_ECHO_INPUT;
447 
448  SetConsoleMode(hStdin, mode );
449 
450 #else
451  struct termios tty;
452  tcgetattr(STDIN_FILENO, &tty);
453  if( !enable )
454  tty.c_lflag &= ~ECHO;
455  else
456  tty.c_lflag |= ECHO;
457 
458  tcsetattr(STDIN_FILENO, TCSANOW, &tty);
459 #endif
460 }
461 }
462 */
463 
464 /*
465 int32_t _getch( void ); // windows only #include <conio.h>
466 
467 int32_t main()
468 {
469  std::string password;
470  char ch;
471  const char ENTER = 13;
472 
473  std::cout << "enter the password: ";
474 
475  while((ch = _getch()) != ENTER)
476  {
477  bool addChar(char theChar);
478  password += ch;
479  std::cout << '*';
480  }
481 }
482 */
483 
484 #ifndef _PASSWORD_LEN
485 #define _PASSWORD_LEN 128
486 #endif
487 
489  const char* szPrompt) const
490 {
491  OT_ASSERT(nullptr != szPrompt);
492 
493 #ifdef _WIN32
494  {
495  std::cout << szPrompt;
496 
497  {
498  std::string strPassword = "";
499 
500 #ifdef UNICODE
501 
502  const wchar_t enter[] = {L'\x000D', L'\x0000'}; // carrage return
503  const std::wstring wstrENTER = enter;
504 
505  std::wstring wstrPass = L"";
506 
507  for (;;) {
508  const wchar_t ch[] = {_getwch(), L'\x0000'};
509  const std::wstring wstrCH = ch;
510  if (wstrENTER == wstrCH) break;
511  wstrPass.append(wstrCH);
512  }
513  strPassword = OTString::ws2s(wstrPass);
514 
515 #else
516 
517  const char enter[] = {'\x0D', '\x00'}; // carrage return
518  const std::string strENTER = enter;
519 
520  std::string strPass = "";
521 
522  for (;;) {
523  const char ch[] = {_getch(), '\x00'};
524  const std::string strCH = ch;
525  if (strENTER == strCH) break;
526  strPass.append(strCH);
527  }
528  strPassword = strPass;
529 
530 #endif
531  theOutput.setPassword(
532  strPassword.c_str(),
533  static_cast<int32_t>(strPassword.length() - 1));
534  }
535 
536  std::cout << std::endl; // new line.
537  return true;
538  }
539 #elif defined(OT_CRYPTO_USING_OPENSSL)
540  // todo security: might want to allow to set OTPassword's size and copy
541  // directly into it,
542  // so that we aren't using this temp buf in between, which, although we're
543  // zeroing it, could
544  // technically end up getting swapped to disk.
545  //
546  {
547  char buf[_PASSWORD_LEN + 10] = "", buff[_PASSWORD_LEN + 10] = "";
548 
549  if (UI_UTIL_read_pw(buf, buff, _PASSWORD_LEN, szPrompt, 0) == 0) {
550  size_t nPassLength = OTString::safe_strlen(buf, _PASSWORD_LEN);
551  theOutput.setPassword_uint8(reinterpret_cast<uint8_t*>(buf),
552  nPassLength);
553  OTPassword::zeroMemory(buf, nPassLength);
554  OTPassword::zeroMemory(buff, nPassLength);
555  return true;
556  }
557  else
558  return false;
559  }
560 #else
561  {
562  otErr << "__FUNCTION__: Open-Transactions is not compiled to collect "
563  << "the passphrase from the console!\n";
564  return false;
565  }
566 #endif
567 }
568 
569 // get pass phrase, length 'len' into 'tmp'
570 /*
571 int32_t len=0;
572 char *tmp=nullptr;
573 // tmp = "test";
574 len = strlen(tmp);
575 
576 if (len <= 0)
577  return 0;
578 
579 // if too int64_t, truncate
580 if (len > size)
581  len = size;
582 
583 memcpy(buf, tmp, len);
584 return len;
585  */
586 
587 bool OTCrypto::GetPasswordFromConsole(OTPassword& theOutput, bool bRepeat) const
588 {
589  int32_t nAttempts = 0;
590 
591  for (;;) {
592  theOutput.zeroMemory();
593 
594  if (GetPasswordFromConsoleLowLevel(theOutput, "(OT) passphrase: ")) {
595  if (!bRepeat) {
596  std::cout << std::endl;
597  return true;
598  }
599  }
600  else {
601  std::cout << "Sorry." << std::endl;
602  return false;
603  }
604 
605  OTPassword tempPassword;
606 
607  if (!GetPasswordFromConsoleLowLevel(tempPassword,
608  "(Verifying) passphrase again: ")) {
609  std::cout << "Sorry." << std::endl;
610  return false;
611  }
612 
613  if (!tempPassword.Compare(theOutput)) {
614  if (++nAttempts >= 3) break;
615 
616  std::cout << "(Mismatch, try again.)\n" << std::endl;
617  }
618  else {
619  std::cout << std::endl;
620  return true;
621  }
622  }
623 
624  std::cout << "Sorry." << std::endl;
625 
626  return false;
627 }
628 
629 // static
631 {
632  // Todo: someday, swapping the crypto lib should be as easy as changing this
633  // compile flag to OT_CRYPTO_USING_GPG. We'll get there.
634  //
635  static
636 #ifdef OT_CRYPTO_USING_OPENSSL
638 #endif
639  s_theSingleton; // For now we're only allowing a single instance.
640 
641  return &s_theSingleton;
642 }
643 
644 // Currently called by OTLog::OT_Init();
645 
646 void OTCrypto::Init() const
647 {
648  // This is only supposed to happen once per run.
649  //
650  if (0 == OTCrypto::s_nCount) {
651  ++(OTCrypto::s_nCount);
652 
653  otWarn << "OT_Init: Setting up rlimits, and crypto library...\n";
654 
655 // Here is a security measure intended to make it more difficult to capture a
656 // core
657 // dump. (Not used in debug mode, obviously.)
658 //
659 #if !defined(PREDEF_MODE_DEBUG) && defined(PREDEF_PLATFORM_UNIX)
660  struct rlimit rlim;
661  getrlimit(RLIMIT_CORE, &rlim);
662  rlim.rlim_max = rlim.rlim_cur = 0;
663  if (setrlimit(RLIMIT_CORE, &rlim)) {
664  OT_FAIL_MSG("OTCrypto::Init: ASSERT: setrlimit failed. (Used for "
665  "preventing core dumps.)\n");
666  }
667 #endif
668 
669  Init_Override();
670  }
671  else
672  otErr << "OTCrypto::Init: ERROR: Somehow this erroneously got called "
673  "more than once! (Doing nothing.)\n";
674 }
675 
676 // Currently called by OTLog::OT_Cleanup();
677 
678 void OTCrypto::Cleanup() const
679 {
680  // This is only supposed to happen once per run.
681  //
682  if (1 == OTCrypto::s_nCount) {
683  --(OTCrypto::s_nCount);
684 
685  // Any crypto-related cleanup code NOT specific to OpenSSL (which is
686  // handled in OTCrypto_OpenSSL, a subclass) would go here.
687  //
688 
690  }
691  else
692  otErr << "OTCrypto::Cleanup: ERROR: Somehow this erroneously got "
693  "called more than once! (Doing nothing.)\n";
694 }
695 
696 // virtual (Should never get called.)
698 {
699  otErr << "OTCrypto::Init_Override: ERROR: This function should NEVER be "
700  "called (you should be overriding it...)\n";
701 }
702 
703 // virtual (Should never get called.)
705 {
706  otErr << "OTCrypto::Cleanup_Override: ERROR: This function should NEVER be "
707  "called (you should be overriding it...)\n";
708 }
709 
710 bool OTCrypto::Base64Encode(const OTData& theInput, OTString& strOutput,
711  bool bLineBreaks) const
712 {
713 
714  const uint8_t* pDataIn = static_cast<const uint8_t*>(theInput.GetPointer());
715  int32_t nLength = static_cast<int32_t>(theInput.GetSize());
716 
717  OT_ASSERT_MSG(nLength >= 0, "ASSERT!!! nLength is an int32_t, matching the "
718  "openssl interface, and a size was just "
719  "attempted that wouldn't fit into an int32_t, "
720  "after static casting.\n");
721 
722  // Caller is responsible to delete.
723  char* pChar = Base64Encode(pDataIn, nLength, bLineBreaks);
724 
725  if (nullptr == pChar) {
726  otErr << __FUNCTION__
727  << ": Base64Encode returned nullptr. (Failure.)\n";
728  return false;
729  }
730 
731  // pChar not nullptr, and must be cleaned up.
732  //
733  strOutput.Set(pChar);
734  delete pChar;
735  pChar = nullptr;
736 
737  return true; // <=== Success.
738 }
739 
740 bool OTCrypto::Base64Decode(const OTString& strInput, OTData& theOutput,
741  bool bLineBreaks) const
742 {
743 
744  const char* szInput = strInput.Get();
745  size_t theSize = 0;
746 
747  // Caller is responsible to delete.
748  uint8_t* pOutput = Base64Decode(szInput, &theSize, bLineBreaks);
749 
750  if (nullptr == pOutput) {
751  otErr << __FUNCTION__
752  << ": Base64Decode returned nullptr. (Failure.)\n";
753  return false;
754  }
755 
756  // pOutput not nullptr, and must be cleaned up.
757  //
758  const void* pVoid = reinterpret_cast<void*>(pOutput);
759  uint32_t lNewSize = static_cast<uint32_t>(theSize);
760 
761  theOutput.Assign(pVoid, lNewSize);
762  delete pOutput;
763  pOutput = nullptr;
764 
765  return true; // <=== Success.
766 }
767 
768 OTCrypto_Decrypt_Output::OTCrypto_Decrypt_Output()
769  : m_pPassword(nullptr)
770  , m_pPayload(nullptr)
771 {
772 }
773 
775 {
776  // We don't own these objects.
777  // Rather, we own a pointer to ONE of them, since we are a wrapper
778  // for this one or that.
779  //
780  m_pPassword = nullptr;
781  m_pPayload = nullptr;
782 
783  // Since this is merely a wrapper class, we don't actually Release() these
784  // things.
785  // However, we DO have a release function, since the programmatic USER of
786  // this class
787  // MAY wish to Release() whatever it is wrapping.
788  //
789  // Release_Envelope_Decrypt_Output();
790 }
791 
792 OTCrypto_Decrypt_Output::OTCrypto_Decrypt_Output(
793  const OTCrypto_Decrypt_Output& rhs) // passed
794  : m_pPassword(nullptr),
795  m_pPayload(nullptr)
796 {
797  m_pPassword = rhs.m_pPassword;
798  m_pPayload = rhs.m_pPayload;
799 }
800 
801 OTCrypto_Decrypt_Output::OTCrypto_Decrypt_Output(OTPassword& thePassword)
802  : m_pPassword(&thePassword)
803  , m_pPayload(nullptr)
804 {
805 }
806 
807 OTCrypto_Decrypt_Output::OTCrypto_Decrypt_Output(OTPayload& thePayload)
808  : m_pPassword(nullptr)
809  , m_pPayload(&thePayload)
810 {
811 }
812 
814  // member
815  // function
816  // (should
817  // never
818  // fail!)
819 {
820  if (&other != this) {
821  std::swap(m_pPassword, other.m_pPassword);
822  std::swap(m_pPayload, other.m_pPayload);
823  }
824 }
825 
827  OTCrypto_Decrypt_Output other) // note: argument passed by value!
828 {
829  // swap this with other
830  swap(other);
831 
832  // by convention, always return *this
833  return *this;
834 }
835 
836 // This is just a wrapper class.
838 {
839  OT_ASSERT((m_pPassword != nullptr) || (m_pPayload != nullptr));
840 
842 
843  // no need to call ot_super::Release here, since this class has no
844  // superclass.
845 }
846 
847 // This is just a wrapper class.
849 {
850  if (nullptr != m_pPassword) m_pPassword->zeroMemory();
851 
852  if (nullptr != m_pPayload) m_pPayload->Release();
853 }
854 
855 bool OTCrypto_Decrypt_Output::Concatenate(const void* pAppendData,
856  uint32_t lAppendSize) const
857 {
858  OT_ASSERT((m_pPassword != nullptr) || (m_pPayload != nullptr));
859 
860  if (nullptr != m_pPassword) {
861  if (static_cast<int32_t>(lAppendSize) ==
862  static_cast<int32_t>(m_pPassword->addMemory(
863  pAppendData, static_cast<uint32_t>(lAppendSize))))
864  return true;
865  else
866  return false;
867  }
868 
869  if (nullptr != m_pPayload) {
870  m_pPayload->Concatenate(pAppendData, lAppendSize);
871  return true;
872  }
873  return false;
874 }
875 
876 #if defined(OT_CRYPTO_USING_OPENSSL)
877 
878 extern "C" {
879 
880 #include <openssl/crypto.h>
881 #include <openssl/asn1.h>
882 #include <openssl/evp.h>
883 #include <openssl/objects.h>
884 #include <openssl/sha.h>
885 #include <openssl/pem.h>
886 #include <openssl/rsa.h>
887 #include <openssl/err.h>
888 #include <openssl/rand.h>
889 #include <openssl/ssl.h>
890 #include <openssl/conf.h>
891 
892 //#ifndef ANDROID // Android thus far only supports OpenSSL 0.9.8k
893 #include <openssl/whrlpool.h>
894 
895 // // Just trying to get Whirlpool working since they added it to OpenSSL
896 // //
897 // static int32_t init(EVP_MD_CTX* ctx)
898 // { return WHIRLPOOL_Init((WHIRLPOOL_CTX*)ctx->md_data); }
899 //
900 // static int32_t update(EVP_MD_CTX* ctx, const void* data,size_t count)
901 // { return WHIRLPOOL_Update((WHIRLPOOL_CTX*)ctx->md_data,data,count); }
902 //
903 // static int32_t final(EVP_MD_CTX* ctx, uint8_t* md)
904 // { return WHIRLPOOL_Final(md,(WHIRLPOOL_CTX*)ctx->md_data); }
905 //
906 //
907 // static const EVP_MD whirlpool_md =
908 // {
909 // NID_whirlpool,
910 // 0,
911 // WHIRLPOOL_DIGEST_LENGTH,
912 // 0,
913 // init,
914 // update,
915 // final,
916 // nullptr,
917 // nullptr,
918 // EVP_PKEY_nullptr_method,
919 // WHIRLPOOL_BBLOCK/8,
920 // sizeof(EVP_MD *)+sizeof(WHIRLPOOL_CTX),
921 // };
922 //#endif // !ANDROID
923 
924 #ifndef OPENSSL_THREAD_DEFINES
925 #define OPENSSL_THREAD_DEFINES
926 #include <openssl/opensslconf.h>
927 #endif
928 
929 #include <openssl/opensslv.h>
930 }
931 
933  : OTCrypto()
934  , dp(nullptr)
935 {
936 }
937 
939 {
940 }
941 
942 /*
943  #include <openssl/ssl.h>
944  void SSL_load_error_strings(void);
945 
946  #include <openssl/err.h>
947  void ERR_free_strings(void);
948  //void ERR_load_crypto_strings(void);
949 
950 
951  #include <openssl/ssl.h>
952  int32_t SSL_library_init(void);
953  //#define OpenSSL_add_ssl_algorithms() SSL_library_init()
954  //#define SSLeay_add_ssl_algorithms() SSL_library_init()
955 
956 
957  #include <openssl/evp.h>
958  void OpenSSL_add_all_algorithms(void);
959  //void OpenSSL_add_all_ciphers(void);
960  //void OpenSSL_add_all_digests(void);
961  void EVP_cleanup(void);
962 
963 
964  #include <openssl/conf.h>
965  void OPENSSL_config(const char* config_name);
966  //void OPENSSL_no_config(void);
967  //Applications should free up configuration at application closedown by calling
968  CONF_modules_free().
969 
970  #include <openssl/conf.h>
971  void CONF_modules_free(void);
972  //void CONF_modules_finish(void);
973  //void CONF_modules_unload(int32_t all);
974  */
975 
976 /*
977 #include <openssl/crypto.h>
978 
979 / Don't use this structure directly.
980 typedef struct crypto_threadid_st
981  {
982  void *ptr;
983  uint64_t val;
984  } CRYPTO_THREADID;
985 
986 // Only use CRYPTO_THREADID_set_[numeric|pointer]() within callbacks
987 void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID* id, uint64_t val);
988 void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID* id, void* ptr);
989 
990 int32_t CRYPTO_THREADID_set_callback(void (*threadid_func)(CRYPTO_THREADID *));
991 
992 void (*CRYPTO_THREADID_get_callback(void))(CRYPTO_THREADID *);
993 
994 void CRYPTO_THREADID_current(CRYPTO_THREADID* id);
995 
996 int32_t CRYPTO_THREADID_cmp(const CRYPTO_THREADID* a, const CRYPTO_THREADID* b);
997 void CRYPTO_THREADID_cpy(CRYPTO_THREADID* dest, const CRYPTO_THREADID* src);
998 
999  uint64_t CRYPTO_THREADID_hash(const CRYPTO_THREADID* id);
1000 
1001 int32_t CRYPTO_num_locks(void);
1002 
1003  Description
1004 
1005 
1006  OpenSSL can safely be used in multi-threaded applications provided that at
1007 least two callback functions are set,
1008  locking_function and threadid_func.
1009 
1010  locking_function(int32_t mode, int32_t n, const char* file, int32_t line) is
1011 needed to perform locking on shared data structures.
1012  (Note that OpenSSL uses a number of global data structures that will be
1013 implicitly shared whenever multiple threads
1014  use OpenSSL.) Multi-threaded applications will crash at random if it is not
1015 set.
1016 
1017  locking_function() must be able to handle up to CRYPTO_num_locks() different
1018 mutex locks. It sets the n-th lock if
1019  mode & CRYPTO_LOCK , and releases it otherwise.
1020 
1021  file and line are the file number of the function setting the lock. They can be
1022 useful for debugging.
1023 
1024  threadid_func(CRYPTO_THREADID* id) is needed to record the currently-executing
1025 thread's identifier into id. The
1026  implementation of this callback should not fill in id directly, but should use
1027 CRYPTO_THREADID_set_numeric() if
1028  thread IDs are numeric, or CRYPTO_THREADID_set_pointer() if they are
1029 pointer-based. If the application does not
1030  register such a callback using CRYPTO_THREADID_set_callback(), then a default
1031 implementation is used - on Windows
1032  and BeOS this uses the system's default thread identifying APIs, and on all
1033 other platforms it uses the address
1034  of errno. The latter is satisfactory for thread-safety if and only if the
1035 platform has a thread-local error number
1036  facility.
1037  */
1038 
1039 /*
1040 
1041 // struct CRYPTO_dynlock_value needs to be defined by the user
1042 struct CRYPTO_dynlock_value;
1043 
1044 void CRYPTO_set_dynlock_create_callback(struct CRYPTO_dynlock_value *
1045  (*dyn_create_function)(char* file, int32_t line));
1046 void CRYPTO_set_dynlock_lock_callback(void (*dyn_lock_function)
1047  (int32_t mode, struct CRYPTO_dynlock_value *l, const char* file, int32_t
1048 line));
1049 void CRYPTO_set_dynlock_destroy_callback(void (*dyn_destroy_function)
1050  (struct CRYPTO_dynlock_value *l, const char* file, int32_t line));
1051 
1052 int32_t CRYPTO_get_new_dynlockid(void);
1053 
1054 void CRYPTO_destroy_dynlockid(int32_t i);
1055 
1056 void CRYPTO_lock(int32_t mode, int32_t n, const char* file, int32_t line);
1057 
1058 #define CRYPTO_w_lock(type) \
1059  CRYPTO_lock(CRYPTO_LOCK|CRYPTO_WRITE,type,__FILE__,__LINE__)
1060 #define CRYPTO_w_unlock(type) \
1061  CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_WRITE,type,__FILE__,__LINE__)
1062 #define CRYPTO_r_lock(type) \
1063  CRYPTO_lock(CRYPTO_LOCK|CRYPTO_READ,type,__FILE__,__LINE__)
1064 #define CRYPTO_r_unlock(type) \
1065  CRYPTO_lock(CRYPTO_UNLOCK|CRYPTO_READ,type,__FILE__,__LINE__)
1066 #define CRYPTO_add(addr,amount,type) \
1067  CRYPTO_add_lock(addr,amount,type,__FILE__,__LINE__)
1068 
1069  */
1070 
1071 std::mutex* OTCrypto_OpenSSL::s_arrayMutex = nullptr;
1072 
1073 extern "C" {
1074 #if OPENSSL_VERSION_NUMBER - 0 < 0x10000000L
1075 unsigned int64_t ot_openssl_thread_id(void);
1076 #else
1077 void ot_openssl_thread_id(CRYPTO_THREADID*);
1078 #endif
1079 
1080 void ot_openssl_locking_callback(int32_t mode, int32_t type, char* file,
1081  int32_t line);
1082 }
1083 
1084 // done
1085 /*
1086  threadid_func(CRYPTO_THREADID* id) is needed to record the currently-executing
1087  thread's identifier into id.
1088  The implementation of this callback should not fill in id directly, but should
1089  use CRYPTO_THREADID_set_numeric()
1090  if thread IDs are numeric, or CRYPTO_THREADID_set_pointer() if they are
1091  pointer-based. If the application does
1092  not register such a callback using CRYPTO_THREADID_set_callback(), then a
1093  default implementation is used - on
1094  Windows and BeOS this uses the system's default thread identifying APIs, and on
1095  all other platforms it uses the
1096  address of errno. The latter is satisfactory for thread-safety if and only if
1097  the platform has a thread-local
1098  error number facility.
1099 
1100  */
1101 
1102 #if OPENSSL_VERSION_NUMBER - 0 < 0x10000000L
1104 {
1105  uint64_t ret = this_thread::get_raw_id();
1106 
1107  return (ret);
1108 }
1109 
1110 #else
1111 void ot_openssl_thread_id(CRYPTO_THREADID* id)
1112 {
1113  OT_ASSERT(nullptr != id);
1114 
1115  // TODO: Possibly do this by pointer instead of by uint64_t,
1116  // for certain platforms. (OpenSSL provides functions for both.)
1117  //
1118 
1119  unsigned long val =
1120  std::hash<std::thread::id>()(std::this_thread::get_id());
1121 
1122  // void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID* id, uint64_t val);
1123  // void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID* id, void* ptr);
1124 
1125  CRYPTO_THREADID_set_numeric(id, val);
1126 }
1127 #endif
1128 
1129 /*
1130  locking_function(int32_t mode, int32_t n, const char* file, int32_t line) is
1131  needed to perform locking on
1132  shared data structures. (Note that OpenSSL uses a number of global data
1133  structures that will
1134  be implicitly shared whenever multiple threads use OpenSSL.) Multi-threaded
1135  applications will
1136  crash at random if it is not set.
1137 
1138  locking_function() must be able to handle up to CRYPTO_num_locks() different
1139  mutex locks. It
1140  sets the n-th lock if mode & CRYPTO_LOCK , and releases it otherwise.
1141 
1142  file and line are the file number of the function setting the lock. They can be
1143  useful for
1144  debugging.
1145  */
1146 
1147 void ot_openssl_locking_callback(int32_t mode, int32_t type, const char*,
1148  int32_t)
1149 {
1150  if (mode & CRYPTO_LOCK) {
1151  OTCrypto_OpenSSL::s_arrayMutex[type].lock();
1152  }
1153  else {
1154  OTCrypto_OpenSSL::s_arrayMutex[type].unlock();
1155  }
1156 }
1157 
1158 /*
1159  --- More code for Base64 Decoding using OpenSSL:
1160 
1161  void base64Decode(uint8_t* pIn, int32_t inLen, uint8_t* pOut,
1162  int32_t& outLen)
1163 {
1164  // create a memory buffer containing base64 encoded data
1165  OpenSSL_BIO bmem = BIO_new_mem_buf((void*)pIn, inLen);
1166 
1167  // push a Base64 filter so that reading from buffer decodes it
1168  OpenSSL_BIO bioCmd = BIO_new(BIO_f_base64());
1169  // we don't want newlines
1170  BIO_set_flags(bioCmd, BIO_FLAGS_BASE64_NO_NL);
1171  bmem = BIO_push(bioCmd, bmem);
1172 
1173  int32_t finalLen = BIO_read(bmem, (void*)pOut, outLen);
1174  outLen = finalLen;
1175 }
1176 
1177 --- Another example of similar code:
1178 
1179 char *unbase64(uint8_t* input, int32_t length)
1180 {
1181  OpenSSL_BIO b64(nullptr), bmem(nullptr);
1182 
1183  char *buffer = (char *)malloc(length);
1184  memset(buffer, 0, length);
1185 
1186  b64 = BIO_new(BIO_f_base64());
1187  bmem = BIO_new_mem_buf(input, length);
1188  bmem = BIO_push(b64, bmem);
1189 
1190  BIO_read(bmem, buffer, length);
1191 
1192  return buffer;
1193 }
1194 */
1195 
1196 /*
1197 // This function will base64 DECODE the string contents
1198 // and return them as a string in strData
1199 // It does NOT handle Uncompression
1200 
1201 bool OTASCIIArmor::GetString(OTString& strData, bool bLineBreaks) const //=true
1202 {
1203  size_t outSize = 0;
1204  uint8_t * pData = nullptr;
1205 
1206  pData = base64_decode(Get(), &outSize, (bLineBreaks ? 1 : 0));
1207 
1208  if (pData)
1209  {
1210  strData.Set((const char*)pData, outSize);
1211 
1212  delete [] pData; pData=nullptr;
1213  return true;
1214  }
1215  else {
1216  return false;
1217  }
1218 }
1219 
1220 
1221 // This function will base64 ENCODE string stored in strData,
1222 // and then Set() that as the string contents for *this.
1223 // It does NOT handle compression.
1224 
1225 bool OTASCIIArmor::SetString(const OTString& strData, bool bLineBreaks) //
1226 =true
1227 {
1228  char * pString = nullptr;
1229 
1230  // Now let's base-64 encode it... //
1231 +1 for the null terminator.
1232  pString = base64_encode((const uint8_t*)strData.Get(), strData.GetLength(),
1233 (bLineBreaks ? 1 : 0));
1234  // pString = base64_encode((const uint8_t*)strData.Get(),
1235 strData.GetLength()+1, (bLineBreaks ? 1 : 0)); // this was before we used
1236 compression.
1237 
1238  if (pString)
1239  {
1240  Set(pString);
1241  delete [] pString; pString=nullptr; // I'm using free here because I
1242 believe base64_encode is using malloc
1243  return true;
1244  }
1245 
1246  return false;
1247 }
1248 */
1249 
1250 extern "C" {
1251 char* ot_openssl_base64_encode(const uint8_t* input, int32_t in_len,
1252  int32_t bLineBreaks)
1253 {
1254  char* buf = nullptr;
1255  BUF_MEM* bptr = nullptr;
1256 
1257  OT_ASSERT_MSG(in_len >= 0,
1258  "OT_base64_encode: Abort: in_len is a negative number!");
1259 
1260  OpenSSL_BIO b64 = BIO_new(BIO_f_base64());
1261 
1262  if (!b64) return buf;
1263 
1264  if (!bLineBreaks) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1265 
1266  OpenSSL_BIO bmem = BIO_new(BIO_s_mem());
1267 
1268  if (bmem) {
1269  OpenSSL_BIO b64join = BIO_push(b64, bmem);
1270  b64.release();
1271  bmem.release();
1272 
1273  if (BIO_write(b64join, input, in_len) == in_len) {
1274  (void)BIO_flush(b64join);
1275  BIO_get_mem_ptr(b64join, &bptr);
1276  // otLog5 << "DEBUG base64_encode size: %lld, in_len:
1277  // %lld\n", bptr->length+1, in_len);
1278  buf = new char[bptr->length + 1];
1279  OT_ASSERT(nullptr != buf);
1280  memcpy(buf, bptr->data, bptr->length); // Safe.
1281  buf[bptr->length] = '\0'; // Forcing null terminator.
1282  }
1283  }
1284  else {
1285  OT_FAIL_MSG("Failed creating new Bio in base64_encode.\n");
1286  }
1287 
1288  return buf;
1289 }
1290 
1291 uint8_t* ot_openssl_base64_decode(const char* input, size_t* out_len,
1292  int32_t bLineBreaks)
1293 {
1294 
1295  OT_ASSERT(nullptr != input);
1296 
1297  int32_t in_len =
1298  static_cast<int32_t>(strlen(input)); // todo security (strlen)
1299  int32_t out_max_len = (in_len * 6 + 7) / 8;
1300  uint8_t* buf = new uint8_t[out_max_len];
1301  OT_ASSERT(nullptr != buf);
1302  memset(buf, 0, out_max_len); // todo security
1303 
1304  OpenSSL_BIO b64 = BIO_new(BIO_f_base64());
1305 
1306  if (b64) {
1307  if (!bLineBreaks) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
1308 
1309  OpenSSL_BIO bmem =
1310  BIO_new_mem_buf((char*)input, in_len); // todo casting.
1311  OT_ASSERT(nullptr != bmem);
1312 
1313  OpenSSL_BIO b64join = BIO_push(b64, bmem);
1314  b64.release();
1315  bmem.release();
1316  OT_ASSERT(nullptr != b64join);
1317 
1318  *out_len = BIO_read(b64join, buf, out_max_len);
1319 
1320  }
1321  else {
1322  OT_FAIL_MSG("Failed creating new Bio in base64_decode.\n");
1323  }
1324 
1325  return buf;
1326 }
1327 } // extern "C"
1328 
1329 // Caller responsible to delete.
1330 char* OTCrypto_OpenSSL::Base64Encode(const uint8_t* input, int32_t in_len,
1331  bool bLineBreaks) const
1332 {
1333  return ot_openssl_base64_encode(input, in_len, (bLineBreaks ? 1 : 0));
1334 }
1335 
1336 // Caller responsible to delete.
1337 uint8_t* OTCrypto_OpenSSL::Base64Decode(const char* input, size_t* out_len,
1338  bool bLineBreaks) const
1339 {
1340  return ot_openssl_base64_decode(input, out_len, (bLineBreaks ? 1 : 0));
1341 }
1342 
1343 // SET (binary id) FROM BASE62-ENCODED STRING
1344 //
1345 // Using a BigInteger lib I just added.
1346 //
1347 // Hopefully use something like this to replace some of the internals for
1348 // OTIdentifier.
1349 // I need to get the author to add a "back into data again" function though.
1350 //
1352  OTIdentifier& theOutput) const
1353 {
1354  theOutput.Release();
1355 
1356  // If it's short, no validate.
1357  //
1358  if (strInput.GetLength() < 3) return;
1359 
1360  // If it's not base62-encoded, then it doesn't validate.
1361  //
1362  const std::string strINPUT = strInput.Get();
1363  if (!IsBase62(strINPUT)) return;
1364 
1365  // Todo there are try/catches in here, so need to handle those at some
1366  // point.
1367  BigInteger bigIntFromBase62 = stringToBigIntegerBase62(strINPUT);
1368 
1369  // Now theBaseConverter contains a BigInteger that it read in as base62.
1370  //
1371  // Next step is to output it from that to Hex so I can convert to Binary.
1372  //
1373  // Why not convert it DIRECTLY to binary, you might ask? TODO.
1374  // In fact this is what we SHOULD be doing. But the BigInteger lib
1375  // I'm using doesn't have a damned output to binary! I'm emailing the
1376  // author now.
1377  //
1378  // In the meantime, I had old code from before, that converted hex string to
1379  // binary, which still needs to be removed. But for now, I'll just convert
1380  // the
1381  // BigInteger to hex, and then call my old code (below) just to get things
1382  // running.
1383 
1384  // You can convert the other way too.
1385  std::string strHEX_VERSION = bigIntegerToStringBase16(bigIntFromBase62);
1386 
1387  // I would rather use stringToBigUnsigned and then convert that to data.
1388  // But apparently this class has no conversion back to data, I will contact
1389  // the author.
1390  BIGNUM* pBigNum = BN_new();
1391  OT_ASSERT(nullptr != pBigNum);
1392 
1393  // Convert from Hex String to BIGNUM.
1394  const int32_t nToHex = BN_hex2bn(&pBigNum, strHEX_VERSION.c_str());
1395  OT_ASSERT(0 < nToHex);
1396 
1397  // Convert from Hex String to BigInteger (unwieldy, I know. Future versions
1398  // will improve.)
1399  //
1400  uint32_t nBigNumBytes = BN_num_bytes(pBigNum);
1401  theOutput.SetSize(nBigNumBytes);
1402 
1403  const int32_t nConverted =
1404  BN_bn2bin(pBigNum, (uint8_t*)(theOutput.GetPointer())); // Todo casting.
1405  OT_ASSERT(nConverted);
1406 
1407  // BN_bn2bin() converts the absolute value of param 1 into big-endian form
1408  // and stores it at param2.
1409  // param2 must point to BN_num_bytes(pBigNum) bytes of memory.
1410 
1411  BN_free(pBigNum);
1412 }
1413 
1414 // GET (binary id) AS BASE62-ENCODED STRING
1415 //
1416 // This Identifier is stored in binary form.
1417 // But what if you want a pretty hex string version of it?
1418 // Just call this function.
1419 // UPDATE: Now Base62 instead of Hex. (More compact.)
1420 // Easy double-click the ID and the entire thing highlights at once.
1421 //
1423  OTString& strOutput) const
1424 {
1425  strOutput.Release();
1426 
1427  if (theInput.IsEmpty()) return;
1428 
1429  // Convert from internal binary format to BIGNUM format.
1430  //
1431  BIGNUM* pBigNum = BN_new();
1432  OT_ASSERT(nullptr != pBigNum);
1433 
1434  BN_bin2bn((uint8_t*)(theInput.GetPointer()), theInput.GetSize(),
1435  pBigNum); // todo cast
1436 
1437  // Convert from BIGNUM to Hex String.
1438  //
1439  char* szBigNumInHex = BN_bn2hex(pBigNum);
1440  OT_ASSERT(szBigNumInHex != nullptr);
1441 
1442  // Convert from Hex String to BigInteger (unwieldy, I know. Future versions
1443  // will improve.)
1444  //
1445  BigInteger theBigInt = stringToBigIntegerBase16(szBigNumInHex);
1446  OPENSSL_free(szBigNumInHex);
1447  szBigNumInHex = nullptr;
1448  BN_free(pBigNum);
1449 
1450  // Convert from BigInteger to std::string in Base62 format.
1451  //
1452  std::string strBigInt = bigIntegerToStringBase62(theBigInt);
1453 
1454  strOutput.Set(strBigInt.c_str());
1455 }
1456 
1457 bool OTCrypto_OpenSSL::RandomizeMemory(uint8_t* szDestination,
1458  uint32_t nNewSize) const
1459 {
1460  OT_ASSERT(nullptr != szDestination);
1461  OT_ASSERT(nNewSize > 0);
1462 
1463  /*
1464  RAND_bytes() returns 1 on success, 0 otherwise. The error code can be
1465  obtained by ERR_get_error(3).
1466  RAND_pseudo_bytes() returns 1 if the bytes generated are cryptographically
1467  strong, 0 otherwise.
1468  Both functions return -1 if they are not supported by the current RAND
1469  method.
1470  */
1471  const int32_t nRAND_bytes =
1472  RAND_bytes(reinterpret_cast<uint8_t*>(szDestination),
1473  static_cast<int32_t>(nNewSize));
1474 
1475  if ((-1) == nRAND_bytes) {
1476  otErr
1477  << __FUNCTION__
1478  << ": ERROR: RAND_bytes is apparently not supported by the current "
1479  "RAND method. OpenSSL: "
1480  << ERR_error_string(ERR_get_error(), nullptr) << "\n";
1481  return false;
1482  }
1483  else if (0 == nRAND_bytes) {
1484  otErr << __FUNCTION__
1485  << ": Failed: The PRNG is apparently not seeded. OpenSSL error: "
1486  << ERR_error_string(ERR_get_error(), nullptr) << "\n";
1487  return false;
1488  }
1489 
1490  return true;
1491 }
1492 
1493 // DeriveKey derives a 128-bit symmetric key from a passphrase.
1494 //
1495 // The OTPassword* returned is the actual derived key. (The result.)
1496 //
1497 // However, you would not use it directly for symmetric-key crypto, but
1498 // instead you'd use the OTSymmetricKey class. This is because you still
1499 // need an object to manage everything about the symmetric key. It stores
1500 // the salt and the iteration count, as well as ONLY the ENCRYPTED version
1501 // of the symmetric key, which is a completely random number and is only
1502 // decrypted briefly for specific operations. The derived key (below) is
1503 // what we use for briefly decrypting that actual (random) symmetric key.
1504 //
1505 // Therefore this function is mainly used INSIDE OTSymmetricKey as part of
1506 // its internal operations.
1507 //
1508 // userPassword argument contains the user's password which is used to
1509 // derive the key. Presumably you already obtained this passphrase...
1510 // Then the derived key is returned, or nullptr if failure. CALLER
1511 // IS RESPONSIBLE TO DELETE!
1512 // Todo: return a smart pointer here.
1513 //
1515  const OTPassword& userPassword, const OTPayload& dataSalt,
1516  uint32_t uIterations,
1517  const OTPayload& dataCheckHash /*= OTPayload()*/) const
1518 {
1519  OTPayload tempPayload = dataCheckHash;
1520  return OTCrypto_OpenSSL::DeriveNewKey(userPassword, dataSalt, uIterations,
1521  tempPayload);
1522 }
1523 
1525  const OTPayload& dataSalt,
1526  uint32_t uIterations,
1527  OTPayload& dataCheckHash) const
1528 {
1529  // OT_ASSERT(userPassword.isPassword());
1530  OT_ASSERT(!dataSalt.IsEmpty());
1531 
1532  otInfo << __FUNCTION__
1533  << ": Using a text passphrase, salt, and iteration count, "
1534  "to make a derived key...\n";
1535 
1536  OTPassword* pDerivedKey(InstantiateBinarySecret()); // already asserts.
1537 
1538  // pDerivedKey MUST be returned or cleaned-up, below this point.
1539  //
1540  // Key derivation in OpenSSL.
1541  //
1542  // int32_t PKCS5_PBKDF2_HMAC_SHA1(const char*, int32_t, const uint8_t*,
1543  // int32_t, int32_t, int32_t, uint8_t*)
1544  //
1545  PKCS5_PBKDF2_HMAC_SHA1(
1546  reinterpret_cast<const char*> // If is password... supply password,
1547  // otherwise supply memory.
1548  (userPassword.isPassword() ? userPassword.getPassword_uint8()
1549  : userPassword.getMemory_uint8()),
1550  static_cast<const int32_t>(
1551  userPassword.isPassword()
1552  ? userPassword.getPasswordSize()
1553  : userPassword.getMemorySize()), // Password Length
1554  static_cast<const uint8_t*>(dataSalt.GetPayloadPointer()), // Salt Data
1555  static_cast<const int32_t>(dataSalt.GetSize()), // Salt Length
1556  static_cast<const int32_t>(uIterations), // Number Of Iterations
1557  static_cast<const int32_t>(
1558  pDerivedKey->getMemorySize()), // Output Length
1559  static_cast<uint8_t*>(
1560  pDerivedKey->getMemoryWritable()) // Output Key (not const!)
1561  );
1562 
1563  // For The HashCheck
1564  bool bHaveCheckHash = !dataCheckHash.IsEmpty();
1565 
1566  OTPayload tmpHashCheck;
1568 
1569  // We take the DerivedKey, and hash it again, then get a 'hash-check'
1570  // Compare that with the supplied one, (if there is one).
1571  // If there isn't one, we return the
1572 
1573  PKCS5_PBKDF2_HMAC_SHA1(
1574  reinterpret_cast<const char*>(pDerivedKey->getMemory()), // Derived Key
1575  static_cast<const int32_t>(
1576  pDerivedKey->getMemorySize()), // Password Length
1577  static_cast<const uint8_t*>(dataSalt.GetPayloadPointer()), // Salt Data
1578  static_cast<const int32_t>(dataSalt.GetSize()), // Salt Length
1579  static_cast<const int32_t>(uIterations), // Number Of Iterations
1580  static_cast<const int32_t>(tmpHashCheck.GetSize()), // Output Length
1581  const_cast<uint8_t*>(static_cast<const uint8_t*>(
1582  tmpHashCheck.GetPayloadPointer()))) // Output Key (not const!)
1583  ;
1584 
1585  if (bHaveCheckHash) {
1586  OTString strDataCheck, strTestCheck;
1587  strDataCheck.Set(
1588  static_cast<const char*>(dataCheckHash.GetPayloadPointer()),
1589  dataCheckHash.GetSize());
1590  strTestCheck.Set(
1591  static_cast<const char*>(tmpHashCheck.GetPayloadPointer()),
1592  tmpHashCheck.GetSize());
1593 
1594  if (!strDataCheck.Compare(strTestCheck)) {
1595  dataCheckHash.reset();
1596  dataCheckHash = tmpHashCheck;
1597  return nullptr; // failure (but we will return the dataCheckHash we
1598  // got
1599  // anyway)
1600  }
1601  }
1602  else {
1603  dataCheckHash.reset();
1604  dataCheckHash = tmpHashCheck;
1605  }
1606 
1607  return pDerivedKey;
1608 }
1609 
1610 /*
1611  openssl dgst -sha1 \
1612  -sign clientkey.pem \
1613  -out cheesy2.sig \
1614  cheesy2.xml
1615 
1616  openssl dgst -sha1 \
1617  -verify clientcert.pem \
1618  -signature cheesy2.sig \
1619  cheesy2.xml
1620 
1621 
1622 openssl x509 -in clientcert.pem -pubkey -noout > clientpub.pem
1623 
1624  Then verification using the public key works as expected:
1625 
1626 openssl dgst -sha1 -verify clientpub.pem -signature cheesy2.sig cheesy2.xml
1627 
1628  Verified OK
1629 
1630 
1631  openssl enc -base64 -out cheesy2.b64 cheesy2.sig
1632 
1633  */
1634 
1635 // static
1637  const OTString& theName)
1638 {
1639  if (theName.Compare("SHA1"))
1640  return EVP_sha1();
1641  else if (theName.Compare("SHA224"))
1642  return EVP_sha224();
1643  else if (theName.Compare("SHA256"))
1644  return EVP_sha256();
1645  else if (theName.Compare("SHA384"))
1646  return EVP_sha384();
1647  else if (theName.Compare("SHA512"))
1648  return EVP_sha512();
1649  //#ifndef ANDROID
1650  else if (theName.Compare("WHIRLPOOL")) // Todo: follow up on any cleanup
1651  // issues related to this. (Are the
1652  // others dynamically allocated? This
1653  // one isn't.)
1654  return EVP_whirlpool();
1655  //#endif
1656  return nullptr;
1657 }
1658 
1660  const OTString& strHashAlgorithm,
1661  OTIdentifier& theOutput) const
1662 {
1663  theOutput.Release();
1664 
1665  // Some hash algorithms are handled by other methods.
1666  // If those don't handle it, then we'll come back here and use OpenSSL.
1667  if (theOutput.CalculateDigestInternal(strInput, strHashAlgorithm)) {
1668  return true;
1669  }
1670 
1671  EVP_MD_CTX mdctx;
1672  const EVP_MD* md = nullptr;
1673 
1674  uint32_t md_len = 0;
1675  uint8_t md_value[EVP_MAX_MD_SIZE]; // I believe this is safe, having just
1676  // analyzed this function.
1677 
1678  // Okay, it wasn't any internal hash algorithm, so then which one was it?
1679  //
1681  strHashAlgorithm); // todo cleanup?
1682 
1683  if (!md) {
1684  otErr << "OTCrypto_OpenSSL::CalculateDigest"
1685  << ": Unknown message digest algorithm: " << strHashAlgorithm
1686  << "\n";
1687  return false;
1688  }
1689 
1690  EVP_MD_CTX_init(&mdctx);
1691  EVP_DigestInit_ex(&mdctx, md, nullptr);
1692  EVP_DigestUpdate(&mdctx, strInput.Get(), strInput.GetLength());
1693  EVP_DigestFinal_ex(&mdctx, md_value, &md_len);
1694  EVP_MD_CTX_cleanup(&mdctx);
1695 
1696  theOutput.Assign(md_value, md_len);
1697 
1698  return true;
1699 }
1700 
1702  const OTString& strHashAlgorithm,
1703  OTIdentifier& theOutput) const
1704 {
1705  theOutput.Release();
1706 
1707  // Some hash algorithms are handled by other methods.
1708  // If those don't handle it, then we'll come back here and use OpenSSL.
1709  if (theOutput.CalculateDigestInternal(dataInput, strHashAlgorithm)) {
1710  return true;
1711  }
1712 
1713  EVP_MD_CTX mdctx;
1714  const EVP_MD* md = nullptr;
1715 
1716  uint32_t md_len = 0;
1717  uint8_t md_value[EVP_MAX_MD_SIZE]; // I believe this is safe, shouldn't ever
1718  // be larger than MAX SIZE.
1719 
1720  // Okay, it wasn't any internal hash algorithm, so then which one was it?
1721  //
1723  strHashAlgorithm); // todo cleanup ?
1724 
1725  if (!md) {
1726  otErr << "OTCrypto_OpenSSL::CalculateDigest"
1727  << ": Unknown message digest algorithm: " << strHashAlgorithm
1728  << "\n";
1729  return false;
1730  }
1731 
1732  EVP_MD_CTX_init(&mdctx);
1733  EVP_DigestInit_ex(&mdctx, md, nullptr);
1734  EVP_DigestUpdate(&mdctx, dataInput.GetPointer(), dataInput.GetSize());
1735  EVP_DigestFinal_ex(&mdctx, md_value, &md_len);
1736  EVP_MD_CTX_cleanup(&mdctx);
1737 
1738  theOutput.Assign(md_value, md_len);
1739 
1740  return true;
1741 }
1742 
1743 /*
1744  SHA256_CTX context;
1745  uint8_t md[SHA256_DIGEST_LENGTH];
1746 
1747  SHA256_Init(&context);
1748  SHA256_Update(&context, (uint8_t*)input, length);
1749  SHA256_Final(md, &context);
1750  */
1751 
1752 // (To instantiate a text secret, just do this: OTPassword thePassword;)
1753 
1754 // Caller MUST delete!
1755 // todo return a smartpointer here.
1757 {
1758  uint8_t* tmp_data = new uint8_t[OTCryptoConfig::SymmetricKeySize()];
1759  OTPassword* pNewKey = new OTPassword(static_cast<void*>(&tmp_data[0]),
1761  OT_ASSERT_MSG(nullptr != pNewKey, "pNewKey = new OTPassword");
1762 
1763  if (nullptr != tmp_data) {
1764  delete[] tmp_data;
1765  tmp_data = nullptr;
1766  }
1767 
1768  return pNewKey;
1769 }
1770 
1771 // done
1772 
1774 {
1775  OTCrypto_OpenSSL::s_arrayMutex = new std::mutex[CRYPTO_num_locks()];
1776 
1777 // NOTE: OpenSSL supposedly has some default implementation for the thread_id,
1778 // so we're going to NOT set that callback here, and see what happens.
1779 //
1780 // UPDATE: Looks like this works "if and only if the local system provides
1781 // errno"
1782 // and since I already have a supposedly-reliable ID from tinythread++, I'm
1783 // going
1784 // to just use that one for now and see how it works.
1785 //
1786 #if OPENSSL_VERSION_NUMBER - 0 < 0x10000000L
1787  CRYPTO_set_id_callback(ot_openssl_thread_id);
1788 #else
1789  int32_t nResult = CRYPTO_THREADID_set_callback(ot_openssl_thread_id);
1790  ++nResult;
1791  --nResult;
1792 #endif
1793 
1794  // Here we set the locking callback function, which is the same for all
1795  // versions
1796  // of OpenSSL. (Unlike thread_id function above.)
1797  //
1798  CRYPTO_set_locking_callback(ot_openssl_locking_callback);
1799 }
1800 
1801 // done
1802 
1804 {
1805  CRYPTO_set_locking_callback(nullptr);
1806 
1807  if (nullptr != OTCrypto_OpenSSL::s_arrayMutex) {
1809  }
1810 
1812 }
1813 
1815 {
1816  const char* szFunc = "OTCrypto_OpenSSL::Init_Override";
1817 
1818  otWarn << szFunc << ": Setting up OpenSSL: SSL_library_init, error "
1819  "strings and algorithms, and OpenSSL config...\n";
1820 
1821 /*
1822  OPENSSL_VERSION_NUMBER is a numeric release version identifier:
1823 
1824  MMNNFFPPS: major minor fix patch status
1825  The status nibble has one of the values 0 for development, 1 to e for betas 1
1826  to 14, and f for release.
1827 
1828  for example
1829 
1830  0x000906000 == 0.9.6 dev
1831  0x000906023 == 0.9.6b beta 3
1832  0x00090605f == 0.9.6e release
1833  Versions prior to 0.9.3 have identifiers < 0x0930. Versions between 0.9.3 and
1834  0.9.5 had a version identifier with this interpretation:
1835 
1836  MMNNFFRBB major minor fix final beta/patch
1837  for example
1838 
1839  0x000904100 == 0.9.4 release
1840  0x000905000 == 0.9.5 dev
1841  Version 0.9.5a had an interim interpretation that is like the current one,
1842  except the patch level got the highest bit set, to keep continuity. The number
1843  was therefore 0x0090581f.
1844 
1845  For backward compatibility, SSLEAY_VERSION_NUMBER is also defined.
1846 
1847  */
1848 #if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER - 0 < 0x10000000L
1849  OT_FAIL_MSG("ASSERT: Must use OpenSSL version 1.0.0 or higher.\n");
1850 #endif
1851 
1852 /* Todo FYI:
1853  - One final comment about compiling applications linked to the OpenSSL library.
1854  - If you don't use the multithreaded DLL runtime library (/MD option) your
1855  - program will almost certainly crash because malloc gets confused -- the
1856  - OpenSSL DLLs are statically linked to one version, the application must
1857  - not use a different one. You might be able to work around such problems
1858  - by adding CRYPTO_malloc_init() to your program before any calls to the
1859  - OpenSSL libraries: This tells the OpenSSL libraries to use the same
1860  - malloc(), free() and realloc() as the application. However there are many
1861  - standard library functions used by OpenSSL that call malloc() internally
1862  - (e.g. fopen()), and OpenSSL cannot change these; so in general you cannot
1863  - rely on CRYPTO_malloc_init() solving your problem, and you should
1864  - consistently use the multithreaded library.
1865  */
1866 #ifdef _WIN32
1867  CRYPTO_malloc_init(); // # -1
1868 // FYI: this call appeared in the client version, not the server version.
1869 // but now it will obviously appear in both, since they both will just call this
1870 // (OT_Init.)
1871 // Therefore if any weird errors crop in the server, just be aware. This call
1872 // might have been
1873 // specifically for DLLs or something.
1874 #endif
1875  // SSL_library_init() must be called before any other action takes place.
1876  // SSL_library_init() is not reentrant.
1877  //
1878  SSL_library_init(); // #0
1879 
1880  /*
1881  We all owe a debt of gratitude to the OpenSSL team but fuck is their
1882  documentation
1883  difficult!! In this case I am trying to figure out whether I should call
1884  SSL_library_init()
1885  first, or SSL_load_error_strings() first.
1886  Docs say:
1887 
1888  EXAMPLES (http://www.openssl.org/docs/ssl/SSL_library_init.html#)
1889 
1890  A typical TLS/SSL application will start with the library initialization,
1891  and provide readable error messages.
1892 
1893  SSL_load_error_strings(); // readable error messages
1894  SSL_library_init(); // initialize library
1895  -----------
1896  ===> NOTICE it said "START" with library initialization, "AND" provide
1897  readable error messages... But then what order does it PUT them in?
1898 
1899  SSL_load_error_strings(); // readable error messages
1900  SSL_library_init(); // initialize library
1901  -------
1902 
1903  ON THE SAME PAGE, as if things weren't confusing enough, see THIS:
1904 
1905  NOTES
1906  SSL_library_init() must be called before any other action takes place.
1907  SSL_library_init() is not reentrant.
1908  -------------------
1909  Then, on http://www.openssl.org/docs/crypto/ERR_load_crypto_strings.html#,
1910  in
1911  reference to SSL_load_error_strings and ERR_load_crypto_strings, it says:
1912 
1913  One of these functions should be called BEFORE generating textual error
1914  messages.
1915 
1916  ====> ?? Huh?? So which should I call first? Ben Laurie, if you are ever
1917  googling your
1918  own name on the Internet, please drop me a line and lemme know:
1919  fellowtraveler around rayservers cough net
1920  */
1921 
1922  // NOTE: the below sections are numbered #1, #2, #3, etc so that they can be
1923  // UNROLLED
1924  // IN THE OPPOSITE ORDER when we get to OT_Cleanup().
1925 
1926  /*
1927  - ERR_load_crypto_strings() registers the error strings for all libcrypto
1928  functions.
1929  - SSL_load_error_strings() does the same, but also registers the libssl
1930  error strings.
1931  One of these functions should be called before generating textual error
1932  messages.
1933  - ERR_free_strings() frees all previously loaded error strings.
1934  */
1935 
1936  SSL_load_error_strings(); // DONE -- corresponds to ERR_free_strings in
1937  // OT_Cleanup() #1
1938 
1939  // ERR_load_crypto_strings(); // Redundant -- SSL_load_error_strings does
1940  // this already.
1941  //
1942  /*
1943  OpenSSL keeps an internal table of digest algorithms and ciphers.
1944  It uses this table to lookup ciphers via functions such as
1945  EVP_get_cipher_byname().
1946 
1947  OpenSSL_add_all_algorithms() adds all algorithms to the table (digests and
1948  ciphers).
1949 
1950  OpenSSL_add_all_digests() adds all digest algorithms to the table.
1951  OpenSSL_add_all_ciphers() adds all encryption algorithms to the table
1952  including password based encryption algorithms.
1953 
1954  TODO optimization:
1955  Calling OpenSSL_add_all_algorithms() links in all algorithms: as a result a
1956  statically linked executable
1957  can be quite large. If this is important it is possible to just add the
1958  required ciphers and digests.
1959  -- Thought: I will probably have different optimization options. Some
1960  things will be done no matter what, but
1961  other things will be compile-flags for optimizing specifically for speed,
1962  or size, or use of RAM, or CPU cycles,
1963  or security options, etc. This is one example of something where I would
1964  optimize it out, if possible, when trying
1965  to conserve RAM.
1966  Note: However it seems from the docs, that this table needs to be populated
1967  anyway due to problems in
1968  OpenSSL when it's not.
1969  */
1970 
1971  /*
1972  Try to activate OpenSSL debug memory procedure:
1973  OpenSSL_BIO pbio = BIO_new(BIO_s_file());
1974  BIO_set_fp(out,stdout,BIO_NOCLOSE);
1975  CRYPTO_malloc_debug_init();
1976  MemCheck_start();
1977  MemCheck_on();
1978 
1979  .
1980  .
1981  .
1982  MemCheck_off()
1983  MemCheck_stop()
1984  CRYPTO_mem_leaks(pbio);
1985 
1986  This will print out to stdout all memory that has been not deallocated.
1987 
1988  Put starting part before everything ( even before
1989  OpenSSL_add_all_algorithms() call)
1990  this way you will see everything.
1991 
1992  */
1993 
1994  OpenSSL_add_all_algorithms(); // DONE -- corresponds to EVP_cleanup() in
1995  // OT_Cleanup(). #2
1996 
1997 //
1998 //
1999 // RAND
2000 //
2001 /*
2002  RAND_bytes() automatically calls RAND_poll() if it has not already been done at
2003  least once.
2004  So you do not have to call it yourself. RAND_poll() feeds on what the operating
2005  system provides:
2006  on Linux, Solaris, FreeBSD and similar Unix-like systems, it will use
2007  /dev/urandom (or /dev/random
2008  if there is no /dev/urandom) to obtain a cryptographically secure initial seed;
2009  on Windows, it will
2010  call CryptGenRandom() for the same effect.
2011 
2012  RAND_screen() is provided by OpenSSL only for backward compatibility with
2013  (much) older code which
2014  may call it (that was before OpenSSL used proper OS-based seed initialization).
2015 
2016  So the "normal" way of dealing with RAND_poll() and RAND_screen() is to call
2017  neither. Just use RAND_bytes()
2018  and be happy.
2019 
2020  RESPONSE: Thanks for the detailed answer. In regards to your suggestion to call
2021  neither, the problem
2022  under Windows is that RAND_poll can take some time and will block our UI. So we
2023  call it upon initialization,
2024  which works for us.
2025  */
2026 // I guess Windows will seed the PRNG whenever someone tries to get
2027 // some RAND_bytes() the first time...
2028 //
2029 //#ifdef _WIN32
2030 // CORRESPONDS to RAND_cleanup in OT_Cleanup().
2031 // RAND_screen();
2032 //#else
2033 // note: optimization: might want to remove this, since supposedly it happens
2034 // anyway
2035 // when you use RAND_bytes. So the "lazy evaluation" rule would seem to imply,
2036 // not bothering
2037 // to slow things down NOW, since it's not really needed until THEN.
2038 //
2039 
2040 #if defined(USE_RAND_POLL)
2041 
2042  RAND_poll(); // #3
2043 
2044 #endif
2045 
2046  // OPENSSL_config() #4
2047  //
2048  // OPENSSL_config configures OpenSSL using the standard openssl.cnf
2049  // configuration file name
2050  // using config_name. If config_name is nullptr then the default name
2051  // openssl_conf will be used.
2052  // Any errors are ignored. Further calls to OPENSSL_config() will have no
2053  // effect. The configuration
2054  // file format is documented in the conf(5) manual page.
2055  //
2056 
2057  OPENSSL_config(
2058  nullptr); // const char *config_name = nullptr: the default name
2059  // openssl_conf will be used.
2060 
2061  //
2062  // Corresponds to CONF_modules_free() in OT_Cleanup().
2063  //
2064 
2065  //
2066  // Let's see 'em!
2067  //
2068  ERR_print_errors_fp(stderr);
2069 //
2070 
2071 //
2072 //
2073 // THREADS
2074 //
2075 //
2076 
2077 #if defined(OPENSSL_THREADS)
2078  // thread support enabled
2079 
2080  otWarn << szFunc << ": OpenSSL WAS compiled with thread support, FYI. "
2081  "Setting up mutexes...\n";
2082 
2083  thread_setup();
2084 
2085 #else
2086  // no thread support
2087 
2088  otErr << __FUNCTION__
2089  << ": WARNING: OpenSSL was NOT compiled with thread support. "
2090  << "(Also: Master Key will not expire.)\n";
2091 
2092 #endif
2093 }
2094 
2095 // RAND_status() and RAND_event() return 1 if the PRNG has been seeded with
2096 // enough data, 0 otherwise.
2097 
2098 /*
2099  13. I think I've detected a memory leak, is this a bug?
2100 
2101  In most cases the cause of an apparent memory leak is an OpenSSL internal
2102  table that is allocated when an application starts up. Since such tables do
2103  not grow in size over time they are harmless.
2104 
2105  These internal tables can be freed up when an application closes using
2106  various functions. Currently these include following:
2107 
2108  Thread-local cleanup functions:
2109 
2110  ERR_remove_state()
2111 
2112  Application-global cleanup functions that are aware of usage (and therefore
2113  thread-safe):
2114 
2115  ENGINE_cleanup() and CONF_modules_unload()
2116 
2117  "Brutal" (thread-unsafe) Application-global cleanup functions:
2118 
2119  ERR_free_strings(), EVP_cleanup() and CRYPTO_cleanup_all_ex_data().
2120  */
2121 
2123 {
2124  const char* szFunc = "OTCrypto_OpenSSL::Cleanup_Override";
2125 
2126  otLog4 << szFunc << ": Cleaning up OpenSSL...\n";
2127 
2128 // In the future if we start using ENGINEs, then do the cleanup here:
2129 //#ifndef OPENSSL_NO_ENGINE
2130 // void ENGINE_cleanup(void);
2131 //#endif
2132 //
2133 
2134 #if defined(OPENSSL_THREADS)
2135  // thread support enabled
2136 
2137  thread_cleanup();
2138 
2139 #else
2140 // no thread support
2141 
2142 #endif
2143 
2144  /*
2145  CONF_modules_free()
2146 
2147  OpenSSL configuration cleanup function. CONF_modules_free() closes down and
2148  frees
2149  up all memory allocated by all configuration modules.
2150  Normally applications will only call CONF_modules_free() at application
2151  [shutdown]
2152  to tidy up any configuration performed.
2153  */
2154  CONF_modules_free(); // CORRESPONDS to: OPENSSL_config() in OT_Init(). #4
2155 
2156  RAND_cleanup(); // Corresponds to RAND_screen / RAND_poll in OT_Init() #3
2157 
2158  EVP_cleanup(); // DONE (brutal) -- corresponds to OpenSSL_add_all_algorithms
2159  // in OT_Init(). #2
2160 
2161  CRYPTO_cleanup_all_ex_data(); // (brutal)
2162  // CRYPTO_mem_leaks(bio_err);
2163 
2164  ERR_free_strings(); // DONE (brutal) -- corresponds to
2165  // SSL_load_error_strings in OT_Init(). #1
2166 
2167  // ERR_remove_state - free a thread's error queue "prevents memory leaks..."
2168  //
2169  // ERR_remove_state() frees the error queue associated with thread pid. If
2170  // pid == 0,
2171  // the current thread will have its error queue removed.
2172  //
2173  // Since error queue data structures are allocated automatically for new
2174  // threads,
2175  // they must be freed when threads are terminated in order to avoid memory
2176  // leaks.
2177  //
2178  // ERR_remove_state(0);
2179  ERR_remove_thread_state(nullptr);
2180 
2181  /*
2182  + Note that ERR_remove_state() is now deprecated, because it is tied
2183  + to the assumption that thread IDs are numeric. ERR_remove_state(0)
2184  + to free the current thread's error state should be replaced by
2185  + ERR_remove_thread_state(nullptr).
2186  */
2187 
2188  // NOTE: You must call SSL_shutdown() before you call SSL_free().
2189  // Update: these are for SSL sockets, they must be called per socket.
2190  // (IOW: Not needed here for app cleanup.)
2191 }
2192 
2193 // #define OTCryptoConfig::SymmetricBufferSize() default: 4096
2194 
2196  const OTPassword& theRawSymmetricKey, // The symmetric key, in clear form.
2197  const char* szInput, // This is the Plaintext.
2198  const uint32_t lInputLength, const OTPayload& theIV, // (We assume this IV
2199  // is already generated
2200  // and passed in.)
2201  OTPayload& theEncryptedOutput) const // OUTPUT. (Ciphertext.)
2202 {
2203  const char* szFunc = "OTCrypto_OpenSSL::Encrypt";
2204 
2205  OT_ASSERT(OTCryptoConfig::SymmetricIvSize() == theIV.GetSize());
2207  theRawSymmetricKey.getMemorySize());
2208  OT_ASSERT(nullptr != szInput);
2209  OT_ASSERT(lInputLength > 0);
2210 
2211  EVP_CIPHER_CTX ctx;
2212 
2213  std::vector<uint8_t> vBuffer(OTCryptoConfig::SymmetricBufferSize()); // 4096
2214  std::vector<uint8_t> vBuffer_out(OTCryptoConfig::SymmetricBufferSize() +
2215  EVP_MAX_IV_LENGTH);
2216  int32_t len_out = 0;
2217 
2218  memset(&vBuffer.at(0), 0, OTCryptoConfig::SymmetricBufferSize());
2219  memset(&vBuffer_out.at(0), 0,
2220  OTCryptoConfig::SymmetricBufferSize() + EVP_MAX_IV_LENGTH);
2221 
2222  //
2223  // This is where the envelope final contents will be placed.
2224  // including the size of the IV, the IV itself, and the ciphertext.
2225  //
2226  theEncryptedOutput.Release();
2227 
2228  class _OTEnv_Enc_stat
2229  {
2230  private:
2231  const char* m_szFunc;
2232  EVP_CIPHER_CTX& m_ctx;
2233 
2234  public:
2235  _OTEnv_Enc_stat(const char* param_szFunc, EVP_CIPHER_CTX& param_ctx)
2236  : m_szFunc(param_szFunc)
2237  , m_ctx(param_ctx)
2238  {
2239  OT_ASSERT(nullptr != param_szFunc);
2240 
2241  EVP_CIPHER_CTX_init(&m_ctx);
2242  }
2243  ~_OTEnv_Enc_stat()
2244  {
2245  // EVP_CIPHER_CTX_cleanup returns 1 for success and 0 for failure.
2246  //
2247  if (0 == EVP_CIPHER_CTX_cleanup(&m_ctx))
2248  otErr << m_szFunc << ": Failure in EVP_CIPHER_CTX_cleanup. (It "
2249  "returned 0.)\n";
2250 
2251  m_szFunc = nullptr; // keep the static analyzer happy
2252  }
2253  };
2254  _OTEnv_Enc_stat theInstance(szFunc, ctx);
2255 
2256  const EVP_CIPHER* cipher_type = EVP_aes_128_cbc(); // todo hardcoding.
2257 
2258  if (!EVP_EncryptInit(
2259  &ctx, cipher_type,
2260  const_cast<uint8_t*>(theRawSymmetricKey.getMemory_uint8()),
2261  static_cast<uint8_t*>(
2262  const_cast<void*>(theIV.GetPayloadPointer())))) {
2263  otErr << szFunc << ": EVP_EncryptInit: failed.\n";
2264  return false;
2265  }
2266 
2267  // Now we process the input and write the encrypted data to
2268  // the output.
2269  //
2270  uint32_t lRemainingLength = lInputLength;
2271  uint32_t lCurrentIndex = 0;
2272 
2273  while (lRemainingLength > 0) {
2274  // If the remaining length is less than the default buffer size, then
2275  // set len to remaining length.
2276  // else if remaining length is larger than or equal to default buffer
2277  // size, then use the default buffer size.
2278  // Resulting value stored in len.
2279  //
2280 
2281  uint32_t len = static_cast<uint32_t>(
2282  (lRemainingLength < OTCryptoConfig::SymmetricBufferSize())
2283  ? lRemainingLength
2285 
2286  if (!EVP_EncryptUpdate(
2287  &ctx, &vBuffer_out.at(0), &len_out,
2288  const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(
2289  &(szInput[lCurrentIndex]))),
2290  len)) {
2291  otErr << szFunc << ": EVP_EncryptUpdate: failed.\n";
2292  return false;
2293  }
2294  lRemainingLength -= len;
2295  lCurrentIndex += len;
2296 
2297  if (len_out > 0)
2298  theEncryptedOutput.Concatenate(
2299  reinterpret_cast<void*>(&vBuffer_out.at(0)),
2300  static_cast<uint32_t>(len_out));
2301  }
2302 
2303  if (!EVP_EncryptFinal(&ctx, &vBuffer_out.at(0), &len_out)) {
2304  otErr << szFunc << ": EVP_EncryptFinal: failed.\n";
2305  return false;
2306  }
2307 
2308  // This is the "final" piece that is added from EncryptFinal just above.
2309  //
2310  if (len_out > 0)
2311  theEncryptedOutput.Concatenate(
2312  reinterpret_cast<void*>(&vBuffer_out.at(0)),
2313  static_cast<uint32_t>(len_out));
2314 
2315  return true;
2316 }
2317 
2319  const OTPassword& theRawSymmetricKey, // The symmetric key, in clear form.
2320  const char* szInput, // This is the Ciphertext.
2321  const uint32_t lInputLength, const OTPayload& theIV, // (We assume this IV
2322  // is already generated
2323  // and passed in.)
2324  OTCrypto_Decrypt_Output theDecryptedOutput) const // OUTPUT. (Recovered
2325  // plaintext.) You can
2326  // pass OTPassword& OR
2327 // OTPayload& here (either
2328 // will work.)
2329 {
2330  const char* szFunc = "OTCrypto_OpenSSL::Decrypt";
2331 
2332  OT_ASSERT(OTCryptoConfig::SymmetricIvSize() == theIV.GetSize());
2334  theRawSymmetricKey.getMemorySize());
2335  OT_ASSERT(nullptr != szInput);
2336  OT_ASSERT(lInputLength > 0);
2337 
2338  EVP_CIPHER_CTX ctx;
2339 
2340  std::vector<uint8_t> vBuffer(OTCryptoConfig::SymmetricBufferSize()); // 4096
2341  std::vector<uint8_t> vBuffer_out(OTCryptoConfig::SymmetricBufferSize() +
2342  EVP_MAX_IV_LENGTH);
2343  int32_t len_out = 0;
2344 
2345  memset(&vBuffer.at(0), 0, OTCryptoConfig::SymmetricBufferSize());
2346  memset(&vBuffer_out.at(0), 0,
2347  OTCryptoConfig::SymmetricBufferSize() + EVP_MAX_IV_LENGTH);
2348 
2349  //
2350  // This is where the plaintext results will be placed.
2351  //
2352  theDecryptedOutput.Release();
2353 
2354  class _OTEnv_Dec_stat
2355  {
2356  private:
2357  const char* m_szFunc;
2358  EVP_CIPHER_CTX& m_ctx;
2359 
2360  public:
2361  _OTEnv_Dec_stat(const char* param_szFunc, EVP_CIPHER_CTX& param_ctx)
2362  : m_szFunc(param_szFunc)
2363  , m_ctx(param_ctx)
2364  {
2365  OT_ASSERT(nullptr != param_szFunc);
2366 
2367  EVP_CIPHER_CTX_init(&m_ctx);
2368  }
2369  ~_OTEnv_Dec_stat()
2370  {
2371  // EVP_CIPHER_CTX_cleanup returns 1 for success and 0 for failure.
2372  //
2373  if (0 == EVP_CIPHER_CTX_cleanup(&m_ctx))
2374  otErr << m_szFunc << ": Failure in EVP_CIPHER_CTX_cleanup. (It "
2375  "returned 0.)\n";
2376  m_szFunc = nullptr; // to keep the static analyzer happy.
2377  }
2378  };
2379  _OTEnv_Dec_stat theInstance(szFunc, ctx);
2380 
2381  const EVP_CIPHER* cipher_type = EVP_aes_128_cbc();
2382 
2383  if (!EVP_DecryptInit(
2384  &ctx, cipher_type,
2385  const_cast<uint8_t*>(theRawSymmetricKey.getMemory_uint8()),
2386  static_cast<uint8_t*>(
2387  const_cast<void*>(theIV.GetPayloadPointer())))) {
2388  otErr << szFunc << ": EVP_DecryptInit: failed.\n";
2389  return false;
2390  }
2391 
2392  // Now we process the input and write the decrypted data to
2393  // the output.
2394  //
2395  uint32_t lRemainingLength = lInputLength;
2396  uint32_t lCurrentIndex = 0;
2397 
2398  while (lRemainingLength > 0) {
2399  // If the remaining length is less than the default buffer size, then
2400  // set len to remaining length.
2401  // else if remaining length is larger than or equal to default buffer
2402  // size, then use the default buffer size.
2403  // Resulting value stored in len.
2404  //
2405  uint32_t len =
2406  (lRemainingLength < OTCryptoConfig::SymmetricBufferSize())
2407  ? lRemainingLength
2409  lRemainingLength -= len;
2410 
2411  if (!EVP_DecryptUpdate(
2412  &ctx, &vBuffer_out.at(0), &len_out,
2413  const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(
2414  &(szInput[lCurrentIndex]))),
2415  len)) {
2416  otErr << szFunc << ": EVP_DecryptUpdate: failed.\n";
2417  return false;
2418  }
2419  lCurrentIndex += len;
2420 
2421  if (len_out > 0)
2422  if (false ==
2423  theDecryptedOutput.Concatenate(
2424  reinterpret_cast<void*>(&vBuffer_out.at(0)),
2425  static_cast<uint32_t>(len_out))) {
2426  otErr << szFunc << ": Failure: theDecryptedOutput isn't large "
2427  "enough for the decrypted output (1).\n";
2428  return false;
2429  }
2430  }
2431 
2432  if (!EVP_DecryptFinal(&ctx, &vBuffer_out.at(0), &len_out)) {
2433  otErr << szFunc << ": EVP_DecryptFinal: failed.\n";
2434  return false;
2435  }
2436 
2437  // This is the "final" piece that is added from DecryptFinal just above.
2438  //
2439  if (len_out > 0)
2440  if (false ==
2441  theDecryptedOutput.Concatenate(
2442  reinterpret_cast<void*>(&vBuffer_out.at(0)),
2443  static_cast<uint32_t>(len_out))) {
2444  otErr << szFunc << ": Failure: theDecryptedOutput isn't large "
2445  "enough for the decrypted output (2).\n";
2446  return false;
2447  }
2448 
2449  return true;
2450 }
2451 
2452 // Seal up as envelope (Asymmetric, using public key and then AES key.)
2453 
2455  const OTString& theInput, OTData& dataOutput) const
2456 {
2457  OT_ASSERT_MSG(!RecipPubKeys.empty(),
2458  "OTCrypto_OpenSSL::Seal: ASSERT: RecipPubKeys.size() > 0");
2459 
2460  const char* szFunc = "OTCrypto_OpenSSL::Seal";
2461 
2462  EVP_CIPHER_CTX ctx;
2463 
2464  uint8_t buffer[4096];
2465  uint8_t buffer_out[4096 + EVP_MAX_IV_LENGTH];
2466  uint8_t iv[EVP_MAX_IV_LENGTH];
2467 
2468  uint32_t len = 0;
2469  int32_t len_out = 0;
2470 
2471  memset(buffer, 0, 4096);
2472  memset(buffer_out, 0, 4096 + EVP_MAX_IV_LENGTH);
2473  memset(iv, 0, EVP_MAX_IV_LENGTH);
2474 
2475  // The below three arrays are ALL allocated and then cleaned-up inside this
2476  // fuction
2477  // (Using the below nested class, _OTEnv_Seal.) The first array will contain
2478  // useful pointers, but we do NOT delete those.
2479  // The next array contains pointers that we DO need to cleanup.
2480  // The final array contains integers (sizes.)
2481  //
2482  EVP_PKEY** array_pubkey =
2483  nullptr; // These will be pointers we use, but do NOT need to clean-up.
2484  uint8_t** ek = nullptr; // These we DO need to cleanup...
2485  int32_t* eklen = nullptr; // This will just be an array of integers.
2486 
2487  bool bFinalized = false; // If this is set true, then we don't bother to
2488  // cleanup the ctx. (See the destructor below.)
2489 
2490  // This class is used as a nested function, for easier cleanup. (C++ doesn't
2491  // directly support nested functions.)
2492  // Basically it translates the incoming RecipPubKeys into the low-level
2493  // arrays
2494  // ek and eklen (that OpenSSL needs.) This also cleans up those same arrays,
2495  // once
2496  // this object destructs (when we leave scope of this function.)
2497  //
2498  class _OTEnv_Seal
2499  {
2500  private:
2501  _OTEnv_Seal(const _OTEnv_Seal&);
2502  _OTEnv_Seal& operator=(const _OTEnv_Seal&);
2503  const char* m_szFunc;
2504  EVP_CIPHER_CTX& m_ctx; // reference to openssl cipher context.
2505  EVP_PKEY*** m_array_pubkey; // pointer to array of public key pointers.
2506  uint8_t*** m_ek; // pointer to array of encrypted symmetric keys.
2507  int32_t** m_eklen; // pointer to array of lengths for each encrypted
2508  // symmetric key
2509  mapOfAsymmetricKeys& m_RecipPubKeys; // array of public keys (to
2510  // initialize the above members
2511  // with.)
2512  int32_t m_nLastPopulatedIndex; // We store the highest-populated index
2513  // (so we can free() up 'til the same
2514  // index, in destructor.)
2515  bool& m_bFinalized;
2516 
2517  public:
2518  _OTEnv_Seal(const char* param_szFunc, EVP_CIPHER_CTX& theCTX,
2519  EVP_PKEY*** param_array_pubkey, uint8_t*** param_ek,
2520  int32_t** param_eklen,
2521  mapOfAsymmetricKeys& param_RecipPubKeys,
2522  bool& param_Finalized)
2523  : m_szFunc(param_szFunc)
2524  , m_ctx(theCTX)
2525  , m_array_pubkey(nullptr)
2526  , m_ek(nullptr)
2527  , m_eklen(nullptr)
2528  , m_RecipPubKeys(param_RecipPubKeys)
2529  , m_nLastPopulatedIndex(-1)
2530  , m_bFinalized(param_Finalized)
2531  {
2532  if (nullptr == param_szFunc) OT_FAIL;
2533  if (nullptr == param_array_pubkey) OT_FAIL;
2534  if (nullptr == param_ek) OT_FAIL;
2535  if (nullptr == param_eklen) OT_FAIL;
2536  OT_ASSERT(!m_RecipPubKeys.empty());
2537 
2538  // Notice that each variable is a "pointer to" the actual array that
2539  // was passed in.
2540  // (So use them that way, inside this class,
2541  // like this: *m_ek and *m_eklen )
2542  //
2543  m_array_pubkey = param_array_pubkey;
2544  m_ek = param_ek;
2545  m_eklen = param_eklen;
2546 
2547  // EVP_CIPHER_CTX_init() corresponds to: EVP_CIPHER_CTX_cleanup()
2548  // EVP_CIPHER_CTX_cleanup clears all information from a cipher
2549  // context and free up any allocated
2550  // memory associate with it. It should be called after all
2551  // operations using a cipher are complete
2552  // so sensitive information does not remain in memory.
2553  //
2554  EVP_CIPHER_CTX_init(&m_ctx);
2555 
2556  // (*m_array_pubkey)[] array must have m_RecipPubKeys.size() no. of
2557  // elements (each containing a pointer
2558  // to an EVP_PKEY that we must NOT clean up.)
2559  //
2560  *m_array_pubkey =
2561  (EVP_PKEY**)malloc(m_RecipPubKeys.size() * sizeof(EVP_PKEY*));
2562  OT_ASSERT(nullptr != *m_array_pubkey);
2563  memset(*m_array_pubkey, 0,
2564  m_RecipPubKeys.size() *
2565  sizeof(EVP_PKEY*)); // size of array length *
2566  // sizeof(pointer)
2567 
2568  // (*m_ek)[] array must have m_RecipPubKeys.size() no. of elements
2569  // (each will contain a pointer from OpenSSL that we must clean up.)
2570  //
2571  *m_ek = (uint8_t**)malloc(m_RecipPubKeys.size() * sizeof(uint8_t*));
2572  if (nullptr == *m_ek) OT_FAIL;
2573  memset(*m_ek, 0, m_RecipPubKeys.size() *
2574  sizeof(uint8_t*)); // size of array length *
2575  // sizeof(pointer)
2576 
2577  // (*m_eklen)[] array must also have m_RecipPubKeys.size() no. of
2578  // elements (each containing a size as integer.)
2579  //
2580  *m_eklen = static_cast<int32_t*>(
2581  malloc(m_RecipPubKeys.size() * sizeof(int32_t)));
2582  OT_ASSERT(nullptr != *m_eklen);
2583  memset(*m_eklen, 0, m_RecipPubKeys.size() *
2584  sizeof(int32_t)); // size of array length *
2585  // sizeof(int32_t)
2586 
2587  //
2588  // ABOVE is all just above allocating the memory and setting it to 0
2589  // / nullptr.
2590  //
2591  // Whereas BELOW is about populating that memory, so the actual
2592  // OTEnvelope::Seal() function can use it.
2593  //
2594 
2595  int32_t nKeyIndex = -1; // it will be 0 upon first iteration.
2596 
2597  for (auto& it : m_RecipPubKeys) {
2598  ++nKeyIndex; // 0 on first iteration.
2599  m_nLastPopulatedIndex = nKeyIndex;
2600 
2601  OTAsymmetricKey* pTempPublicKey =
2602  it.second; // first is the NymID
2603  OT_ASSERT(nullptr != pTempPublicKey);
2604 
2605  OTAsymmetricKey_OpenSSL* pPublicKey =
2606  dynamic_cast<OTAsymmetricKey_OpenSSL*>(pTempPublicKey);
2607  OT_ASSERT(nullptr != pPublicKey);
2608 
2609  EVP_PKEY* public_key =
2610  const_cast<EVP_PKEY*>(pPublicKey->dp->GetKey());
2611  OT_ASSERT(nullptr != public_key);
2612 
2613  // Copy the public key pointer to an array of public key
2614  // pointers...
2615  //
2616  (*m_array_pubkey)[nKeyIndex] =
2617  public_key; // For OpenSSL, it needs an array of ALL the
2618  // public keys.
2619 
2620  // We allocate enough space for the encrypted symmetric key to
2621  // be placed
2622  // at this index (the space determined based on size of the
2623  // public key that
2624  // the symmetric key will be encrypted to.) The space is left
2625  // empty, for OpenSSL
2626  // to populate.
2627  //
2628  (*m_ek)[nKeyIndex] = (uint8_t*)malloc(
2629  EVP_PKEY_size(public_key)); // (*m_ek)[i] must have room for
2630  // EVP_PKEY_size(pubk[i]) bytes.
2631  OT_ASSERT(nullptr != (*m_ek)[nKeyIndex]);
2632  memset((*m_ek)[nKeyIndex], 0, EVP_PKEY_size(public_key));
2633  }
2634  }
2635 
2636  ~_OTEnv_Seal()
2637  {
2638  OT_ASSERT(nullptr != m_array_pubkey); // 1. pointer to an array of
2639  // pointers to EVP_PKEY,
2640  OT_ASSERT(nullptr != m_ek); // 2. pointer to an array of pointers to
2641  // encrypted symmetric keys
2642  OT_ASSERT(nullptr != m_eklen); // 3. pointer to an array storing the
2643  // lengths of those keys.
2644 
2645  // Iterate the array of encrypted symmetric keys, and free the key
2646  // at each index...
2647  //
2648  // We know how many there are, because each pointer will otherwise
2649  // be nullptr.
2650  // Plus we have m_nLastPopulatedIndex, which is obviously as far as
2651  // we will go.
2652  //
2653 
2654  int32_t nKeyIndex = -1; // it will be 0 upon first iteration.
2655  while (nKeyIndex < m_nLastPopulatedIndex) // if
2656  // m_nLastPopulatedIndex
2657  // is 0, then this loop
2658  // will iterate ONCE, with
2659  // nKeyIndex incrementing
2660  // to 0 on the first line.
2661  {
2662  ++nKeyIndex; // 0 on first iteration.
2663 
2664  OT_ASSERT(nullptr != (*m_ek)[nKeyIndex]);
2665 
2666  free((*m_ek)[nKeyIndex]);
2667  (*m_ek)[nKeyIndex] = nullptr;
2668  }
2669 
2670  //
2671  // Now free all of the arrays:
2672  // 1. an array of pointers to EVP_PKEY,
2673  // 2. an array of pointers to encrypted symmetric keys
2674  // (those all being nullptr pointers due to the above
2675  // while-loop),
2676  // and
2677  // 3. an array storing the lengths of those keys.
2678  //
2679 
2680  if (nullptr !=
2681  *m_array_pubkey) // NOTE: The individual pubkeys are NOT
2682  // to be cleaned up, but this array,
2683  // containing pointers to those
2684  // pubkeys, IS cleaned up.
2685  free(*m_array_pubkey);
2686  *m_array_pubkey = nullptr;
2687  m_array_pubkey = nullptr;
2688  if (nullptr != *m_ek) free(*m_ek);
2689  *m_ek = nullptr;
2690  m_ek = nullptr;
2691  if (nullptr != *m_eklen) free(*m_eklen);
2692  *m_eklen = nullptr;
2693  m_eklen = nullptr;
2694 
2695  // EVP_CIPHER_CTX_cleanup returns 1 for success and 0 for failure.
2696  // EVP_EncryptFinal(), EVP_DecryptFinal() and EVP_CipherFinal()
2697  // behave in a similar way to EVP_EncryptFinal_ex(),
2698  // EVP_DecryptFinal_ex() and EVP_CipherFinal_ex() except ctx is
2699  // automatically cleaned up after the call.
2700  //
2701  if (!m_bFinalized) {
2702  // We only clean this up here, if the "Final" Seal function
2703  // didn't get called. (It normally
2704  // would have done this for us.)
2705 
2706  if (0 == EVP_CIPHER_CTX_cleanup(&m_ctx))
2707  otErr << m_szFunc << ": Failure in EVP_CIPHER_CTX_cleanup. "
2708  "(It returned 0.)\n";
2709  }
2710  }
2711  }; // class _OTEnv_Seal
2712 
2713  // INSTANTIATE IT (This does all our setup on construction here, AND cleanup
2714  // on destruction, whenever exiting this function.)
2715 
2716  _OTEnv_Seal local_RAII(szFunc, ctx, &array_pubkey, &ek, &eklen,
2717  RecipPubKeys, bFinalized);
2718 
2719  // This is where the envelope final contents will be placed.
2720  // including the size of the encrypted symmetric key, the symmetric key
2721  // itself, the initialization vector, and the ciphertext.
2722  //
2723  dataOutput.Release();
2724 
2725  const EVP_CIPHER* cipher_type = EVP_aes_128_cbc(); // todo hardcoding.
2726 
2727  /*
2728  int32_t EVP_SealInit(EVP_CIPHER_CTX* ctx, const EVP_CIPHER* type,
2729  uint8_t **ek, int32_t* ekl, uint8_t* iv,
2730  EVP_PKEY **pubk, int32_t npubk);
2731 
2732  -- ek is an array of buffers where the public-key-encrypted secret key will
2733  be written (for each recipient.)
2734  -- Each buffer must contain enough room for the corresponding encrypted
2735  key: that is,
2736  ek[i] must have room for EVP_PKEY_size(pubk[i]) bytes.
2737  -- The actual size of each encrypted secret key is written to the array
2738  ekl.
2739  -- pubk is an array of npubk public keys.
2740  */
2741 
2742  // EVP_PKEY ** array_pubkey = nullptr; // These will be pointers we
2743  // use, but do NOT need to clean-up.
2744  // uint8_t ** ek = nullptr; // These we DO need to cleanup...
2745  // int32_t * eklen = nullptr; // This will just be an
2746  // array of integers.
2747 
2748  if (!EVP_SealInit(
2749  &ctx, cipher_type, ek,
2750  eklen, // array of buffers for output of encrypted copies of the
2751  // symmetric "session key". (Plus array of ints, to receive
2752  // the size of each key.)
2753  iv, // A buffer where the generated IV is written. Must contain
2754  // room for the corresponding cipher's IV, as determined by
2755  // (for example) EVP_CIPHER_iv_length(type).
2756  array_pubkey,
2757  static_cast<int32_t>(RecipPubKeys.size()))) // array of public keys
2758  // we are addressing
2759  // this envelope to.
2760  {
2761  otErr << szFunc << ": EVP_SealInit: failed.\n";
2762  return false;
2763  }
2764 
2765  // Write the ENVELOPE TYPE (network order version.)
2766  //
2767  // 0 == Error
2768  // 1 == Asymmetric Key (this function -- Seal / Open)
2769  // 2 == Symmetric Key (other functions -- Encrypt / Decrypt use this.)
2770  // Anything else: error.
2771 
2772  uint16_t temp_env_type = 1; // todo hardcoding.
2773  uint16_t env_type_n = static_cast<uint16_t>(
2774  htons(static_cast<uint16_t>(temp_env_type))); // Calculate
2775  // "network-order" version
2776  // of envelope type 1.
2777 
2778  dataOutput.Concatenate(reinterpret_cast<void*>(&env_type_n),
2779  static_cast<uint32_t>(sizeof(env_type_n)));
2780 
2781  // Write the ARRAY SIZE (network order version.)
2782 
2783  uint32_t array_size_n = static_cast<uint32_t>(
2784  htonl(static_cast<uint32_t>(RecipPubKeys.size()))); // Calculate
2785  // "network-order"
2786  // version of array
2787  // size.
2788 
2789  dataOutput.Concatenate(reinterpret_cast<void*>(&array_size_n),
2790  static_cast<uint32_t>(sizeof(array_size_n)));
2791 
2792  otLog5 << __FUNCTION__
2793  << ": Envelope type: " << static_cast<int32_t>(ntohs(env_type_n))
2794  << " Array size: " << static_cast<int64_t>(ntohl(array_size_n))
2795  << "\n";
2796 
2797  OT_ASSERT(nullptr != ek);
2798  OT_ASSERT(nullptr != eklen);
2799 
2800  // Loop through the encrypted symmetric keys, and for each, write its
2801  // network-order NymID size, and its NymID, and its network-order content
2802  // size,
2803  // and its content, to the envelope data contents
2804  // (that we are currently building...)
2805  //
2806  int32_t ii = -1; // it will be 0 upon first iteration.
2807 
2808  for (auto& it : RecipPubKeys) {
2809  ++ii; // 0 on first iteration.
2810 
2811  std::string str_nym_id = it.first;
2812  // OTAsymmetricKey * pTempPublicKey = it->second;
2813  // OT_ASSERT(nullptr != pTempPublicKey);
2814 
2815  // OTAsymmetricKey_OpenSSL * pPublicKey =
2816  // dynamic_cast<OTAsymmetricKey_OpenSSL*>(pTempPublicKey);
2817  // OT_ASSERT(nullptr != pPublicKey);
2818 
2819  // OTIdentifier theNymID;
2820  // bool bCalculatedID = pPublicKey->CalculateID(theNymID); //
2821  // Only works for public keys.
2822  //
2823  // if (!bCalculatedID)
2824  // {
2825  // otErr << "%s: Error trying to calculate ID of
2826  // recipient.\n", szFunc);
2827  // return false;
2828  // }
2829 
2830  const OTString strNymID(str_nym_id.c_str());
2831 
2832  uint32_t nymid_len = static_cast<uint32_t>(
2833  strNymID.GetLength() + 1); // +1 for null terminator.
2834  uint32_t nymid_len_n = static_cast<uint32_t>(
2835  htonl(nymid_len)); // Calculate "network-order" version of length
2836  // (+1 for null terminator)
2837 
2838  // Write nymid_len_n and strNymID for EACH encrypted symmetric key.
2839  //
2840  dataOutput.Concatenate(reinterpret_cast<void*>(&nymid_len_n),
2841  static_cast<uint32_t>(sizeof(nymid_len_n)));
2842 
2843  dataOutput.Concatenate(
2844  reinterpret_cast<const void*>(strNymID.Get()),
2845  static_cast<uint32_t>(nymid_len)); // (+1 for null terminator is
2846  // included here already, from
2847  // above.)
2848 
2849  otLog5 << __FUNCTION__ << ": INDEX: " << static_cast<int64_t>(ii)
2850  << " NymID length: "
2851  << static_cast<int64_t>(ntohl(nymid_len_n))
2852  << " Nym ID: " << strNymID
2853  << " Strlen (should be a byte shorter): "
2854  << static_cast<int64_t>(strNymID.GetLength()) << "\n";
2855 
2856  // Write eklen_n and ek for EACH encrypted symmetric key,
2857  //
2858  // EVP_PKEY ** array_pubkey = nullptr; // These will be
2859  // pointers we use, but do NOT need to clean-up.
2860  // uint8_t ** ek = nullptr; // These we DO need to
2861  // cleanup...
2862  // int32_t * eklen = nullptr; // This will
2863  // just
2864  // be an array of integers.
2865 
2866  OT_ASSERT(nullptr != ek[ii]); // assert key pointer not null.
2867  OT_ASSERT(eklen[ii] > 0); // assert key length larger than 0.
2868 
2869  uint32_t eklen_n = static_cast<uint32_t>(htonl(static_cast<uint32_t>(
2870  eklen[ii]))); // Calculate "network-order" version of length.
2871 
2872  dataOutput.Concatenate(reinterpret_cast<void*>(&eklen_n),
2873  static_cast<uint32_t>(sizeof(eklen_n)));
2874 
2875  dataOutput.Concatenate(reinterpret_cast<void*>(ek[ii]),
2876  static_cast<uint32_t>(eklen[ii]));
2877 
2878  otLog5 << __FUNCTION__
2879  << ": EK length: " << static_cast<int64_t>(ntohl(eklen_n))
2880  << " First byte: " << static_cast<int32_t>((ek[ii])[0])
2881  << " Last byte: "
2882  << static_cast<int32_t>((ek[ii])[eklen[ii] - 1]) << "\n";
2883  }
2884 
2885  // Write IV size before then writing IV itself.
2886  //
2887  uint32_t ivlen = static_cast<uint32_t>(
2888  EVP_CIPHER_iv_length(cipher_type)); // Length of IV for this cipher...
2889  // (TODO: add cipher name to output,
2890  // and use it for looking up cipher
2891  // upon Open.)
2892  // OT_ASSERT(ivlen > 0);
2893  uint32_t ivlen_n = static_cast<uint32_t>(htonl(static_cast<uint32_t>(
2894  ivlen))); // Calculate "network-order" version of iv length.
2895 
2896  dataOutput.Concatenate(reinterpret_cast<void*>(&ivlen_n),
2897  static_cast<uint32_t>(sizeof(ivlen_n)));
2898 
2899  dataOutput.Concatenate(reinterpret_cast<void*>(iv),
2900  static_cast<uint32_t>(ivlen));
2901 
2902  otLog5 << __FUNCTION__
2903  << ": iv_size: " << static_cast<int64_t>(ntohl(ivlen_n))
2904  << " IV first byte: " << static_cast<int32_t>(iv[0])
2905  << " IV last byte: " << static_cast<int32_t>(iv[ivlen - 1])
2906  << " \n";
2907 
2908  // Next we put the plaintext into a data object so we can process it via
2909  // EVP_SealUpdate,
2910  // in blocks, into encrypted form in dataOutput. Each iteration of the loop
2911  // processes
2912  // one block.
2913  //
2914  OTData plaintext(static_cast<const void*>(theInput.Get()),
2915  theInput.GetLength() + 1); // +1 for null terminator
2916 
2917  // Now we process the input and write the encrypted data to the
2918  // output.
2919  //
2920  while (0 <
2921  (len = plaintext.OTfread(reinterpret_cast<uint8_t*>(buffer),
2922  static_cast<uint32_t>(sizeof(buffer))))) {
2923  if (!EVP_SealUpdate(&ctx, buffer_out, &len_out, buffer,
2924  static_cast<int32_t>(len))) {
2925  otErr << szFunc << ": EVP_SealUpdate failed.\n";
2926  return false;
2927  }
2928  else if (len_out > 0)
2929  dataOutput.Concatenate(reinterpret_cast<void*>(buffer_out),
2930  static_cast<uint32_t>(len_out));
2931  else
2932  break;
2933  }
2934 
2935  if (!EVP_SealFinal(&ctx, buffer_out, &len_out)) {
2936  otErr << szFunc << ": EVP_SealFinal failed.\n";
2937  return false;
2938  }
2939  // This is the "final" piece that is added from SealFinal just above.
2940  //
2941  else if (len_out > 0) {
2942  bFinalized = true;
2943  dataOutput.Concatenate(reinterpret_cast<void*>(buffer_out),
2944  static_cast<uint32_t>(len_out));
2945  }
2946  else {
2947  // cppcheck-suppress unreadVariable
2948  bFinalized = true;
2949  }
2950 
2951  return true;
2952 }
2953 
2954 /*
2955 #include <openssl/evp.h>
2956 int32_t EVP_OpenInit(EVP_CIPHER_CTX* ctx, EVP_CIPHER* type, uint8_t* ek,
2957  int32_t ekl, uint8_t* iv, EVP_PKEY* priv);
2958 int32_t EVP_OpenUpdate(EVP_CIPHER_CTX* ctx, uint8_t* out, int32_t* outl,
2959 uint8_t* in, int32_t inl);
2960 int32_t EVP_OpenFinal(EVP_CIPHER_CTX* ctx, uint8_t* out, int32_t* outl);
2961 DESCRIPTION
2962 
2963 The EVP envelope routines are a high level interface to envelope decryption.
2964 They decrypt a public key
2965  encrypted symmetric key and then decrypt data using it.
2966 
2967  int32_t EVP_OpenInit(EVP_CIPHER_CTX* ctx, EVP_CIPHER* type, uint8_t* ek,
2968 int32_t
2969 ekl, uint8_t* iv, EVP_PKEY* priv);
2970 EVP_OpenInit() initializes a cipher context ctx for decryption with cipher type.
2971 It decrypts the encrypted
2972  symmetric key of length ekl bytes passed in the ek parameter using the private
2973 key priv. The IV is supplied
2974  in the iv parameter.
2975 
2976 EVP_OpenUpdate() and EVP_OpenFinal() have exactly the same properties as the
2977 EVP_DecryptUpdate() and
2978  EVP_DecryptFinal() routines, as documented on the EVP_EncryptInit(3) manual
2979 page.
2980 
2981 NOTES
2982 
2983 It is possible to call EVP_OpenInit() twice in the same way as
2984 EVP_DecryptInit(). The first call should have
2985  priv set to nullptr and (after setting any cipher parameters) it should be
2986 called
2987 again with type set to nullptr.
2988 
2989 If the cipher passed in the type parameter is a variable length cipher then the
2990 key length will be set to the
2991 value of the recovered key length. If the cipher is a fixed length cipher then
2992 the recovered key length must
2993 match the fixed cipher length.
2994 
2995 RETURN VALUES
2996 
2997 EVP_OpenInit() returns 0 on error or a non zero integer (actually the recovered
2998 secret key size) if successful.
2999 
3000 EVP_OpenUpdate() returns 1 for success or 0 for failure.
3001 
3002 EVP_OpenFinal() returns 0 if the decrypt failed or 1 for success.
3003 */
3004 
3005 // RSA / AES
3006 
3007 bool OTCrypto_OpenSSL::Open(OTData& dataInput, const OTPseudonym& theRecipient,
3008  OTString& theOutput,
3009  const OTPasswordData* pPWData) const
3010 {
3011  const char* szFunc = "OTCrypto_OpenSSL::Open";
3012 
3013  uint8_t buffer[4096];
3014  uint8_t buffer_out[4096 + EVP_MAX_IV_LENGTH];
3015  uint8_t iv[EVP_MAX_IV_LENGTH];
3016 
3017  uint32_t len = 0;
3018  int32_t len_out = 0;
3019  bool bFinalized = false; // We only clean up the ctx if the Open "Final"
3020  // function hasn't been called, since it does that
3021  // automatically already.
3022 
3023  memset(buffer, 0, 4096);
3024  memset(buffer_out, 0, 4096 + EVP_MAX_IV_LENGTH);
3025  memset(iv, 0, EVP_MAX_IV_LENGTH);
3026 
3027  // theOutput is where we'll put the decrypted result.
3028  //
3029  theOutput.Release();
3030 
3031  // Grab the NymID of the recipient, so we can find his session
3032  // key (there might be symmetric keys for several Nyms, not just this
3033  // one, and we need to find the right one in order to perform this Open.)
3034  //
3035  OTString strNymID;
3036  theRecipient.GetIdentifier(strNymID);
3037 
3038  OTAsymmetricKey& theTempPrivateKey =
3039  const_cast<OTAsymmetricKey&>(theRecipient.GetPrivateEncrKey());
3040 
3041  OTAsymmetricKey_OpenSSL* pPrivateKey =
3042  dynamic_cast<OTAsymmetricKey_OpenSSL*>(&theTempPrivateKey);
3043  OT_ASSERT(nullptr != pPrivateKey);
3044 
3045  EVP_PKEY* private_key =
3046  const_cast<EVP_PKEY*>(pPrivateKey->dp->GetKey(pPWData));
3047 
3048  if (nullptr == private_key) {
3049  otErr << szFunc
3050  << ": Null private key on recipient. (Returning false.)\n";
3051  return false;
3052  }
3053  else
3054  otLog5 << __FUNCTION__
3055  << ": Private key is available for NymID: " << strNymID << " \n";
3056 
3057  EVP_CIPHER_CTX ctx;
3058 
3059  class _OTEnv_Open
3060  {
3061  private:
3062  const char* m_szFunc;
3063  EVP_CIPHER_CTX& m_ctx; // reference to openssl cipher context.
3064  OTAsymmetricKey& m_privateKey; // reference to OTAsymmetricKey object.
3065  bool& m_bFinalized;
3066 
3067  public:
3068  _OTEnv_Open(const char* param_szFunc, EVP_CIPHER_CTX& theCTX,
3069  OTAsymmetricKey& param_privateKey, bool& param_Finalized)
3070  : m_szFunc(param_szFunc)
3071  , m_ctx(theCTX)
3072  , m_privateKey(param_privateKey)
3073  , m_bFinalized(param_Finalized)
3074  {
3075  OT_ASSERT(nullptr != param_szFunc);
3076 
3077  EVP_CIPHER_CTX_init(&m_ctx);
3078  }
3079 
3080  ~_OTEnv_Open() // DESTRUCTOR
3081  {
3082  m_privateKey.ReleaseKey();
3083  //
3084  // BELOW this point, private_key (which is a member of m_privateKey
3085  // is either
3086  // cleaned up, or kept based on a timer value. (It MAY not be
3087  // cleaned up,
3088  // depending on its state.)
3089 
3090  // EVP_CIPHER_CTX_cleanup returns 1 for success and 0 for failure.
3091  //
3092  if (!m_bFinalized) {
3093  if (0 == EVP_CIPHER_CTX_cleanup(&m_ctx))
3094  otErr << m_szFunc << ": Failure in EVP_CIPHER_CTX_cleanup. "
3095  "(It returned 0.)\n";
3096  }
3097 
3098  m_szFunc = nullptr;
3099  }
3100  };
3101 
3102  // INSTANTIATE the clean-up object.
3103  //
3104  _OTEnv_Open theNestedInstance(szFunc, ctx, *pPrivateKey, bFinalized);
3105 
3106  dataInput.reset(); // Reset the fread position on this object to 0.
3107 
3108  uint32_t nRunningTotal =
3109  0; // Everytime we read something, we add the length to this variable.
3110 
3111  uint32_t nReadEnvType = 0;
3112  uint32_t nReadArraySize = 0;
3113  uint32_t nReadIV = 0;
3114 
3115  // Read the ARRAY SIZE (network order version -- convert to host version.)
3116 
3117  // Loop through the array of encrypted symmetric keys, and for each:
3118  // read its network-order NymID size (convert to host version), and
3119  // then read its NymID,
3120  // read its network-order key content size (convert to host), and then
3121  // read its key content,
3122 
3123  //
3124  // Read network-order IV size (convert to host version) before then reading
3125  // IV itself.
3126  // (Then update encrypted blocks until evp open final...)
3127  //
3128 
3129  // So here we go...
3130 
3131  //
3132  // Read the ENVELOPE TYPE (as network order version -- and convert to host
3133  // version.)
3134  //
3135  // 0 == Error
3136  // 1 == Asymmetric Key (this function -- Seal / Open)
3137  // 2 == Symmetric Key (other functions -- Encrypt / Decrypt use this.)
3138  // Anything else: error.
3139  //
3140  uint16_t env_type_n = 0;
3141 
3142  if (0 == (nReadEnvType = dataInput.OTfread(
3143  reinterpret_cast<uint8_t*>(&env_type_n),
3144  static_cast<uint32_t>(sizeof(env_type_n))))) {
3145  otErr << szFunc << ": Error reading Envelope Type. Expected "
3146  "asymmetric(1) or symmetric (2).\n";
3147  return false;
3148  }
3149  nRunningTotal += nReadEnvType;
3150  OT_ASSERT(nReadEnvType == static_cast<uint32_t>(sizeof(env_type_n)));
3151 
3152  // convert that envelope type from network to HOST endian.
3153  //
3154  const uint16_t env_type =
3155  static_cast<uint16_t>(ntohs(static_cast<uint16_t>(env_type_n)));
3156  // nRunningTotal += env_type; // NOPE! Just because envelope type is 1
3157  // or 2, doesn't mean we add 1 or 2 extra bytes to the length here. Nope!
3158 
3159  if (1 != env_type) {
3160  otErr << szFunc << ": Error : Expected Envelope for Asymmetric "
3161  "key(type 1) but instead found type "
3162  << static_cast<int32_t>(env_type) << ".\n";
3163  print_stacktrace();
3164  return false;
3165  }
3166  else
3167  otLog5 << __FUNCTION__
3168  << ": Envelope type: " << static_cast<int32_t>(env_type) << "\n";
3169 
3170  // Read the ARRAY SIZE (network order version -- convert to host version.)
3171  //
3172  uint32_t array_size_n = 0;
3173 
3174  if (0 == (nReadArraySize = dataInput.OTfread(
3175  reinterpret_cast<uint8_t*>(&array_size_n),
3176  static_cast<uint32_t>(sizeof(array_size_n))))) {
3177  otErr << szFunc
3178  << ": Error reading Array Size for encrypted symmetric keys.\n";
3179  return false;
3180  }
3181  nRunningTotal += nReadArraySize;
3182  OT_ASSERT(nReadArraySize == static_cast<uint32_t>(sizeof(array_size_n)));
3183 
3184  // convert that array size from network to HOST endian.
3185  //
3186  const uint32_t array_size = ntohl(array_size_n);
3187 
3188  otLog5 << __FUNCTION__
3189  << ": Array size: " << static_cast<int64_t>(array_size) << "\n";
3190 
3191  // nRunningTotal += array_size; // NOPE! Just because there are 10 array
3192  // elements doesn't mean I want to add "10" here to the running total!! Not
3193  // logical.
3194 
3195  // We are going to loop through all the keys and load each up (then delete.)
3196  // Each one is proceeded by its length.
3197  // IF we find the one we are looking for, then we set it onto this variable,
3198  // theRawEncryptedKey, so we have it available below this loop.
3199  //
3200  OTPayload theRawEncryptedKey;
3201  bool bFoundKeyAlready =
3202  false; // If we find it during the loop below, we'll set this to true.
3203 
3204  // Loop through as we read the encrypted symmetric keys, and for each:
3205  // read its network-order NymID size (convert to host version), and
3206  // then read its NymID,
3207  // read its network-order key content size (convert to host), and then
3208  // read its key content,
3209  //
3210  for (uint32_t ii = 0; ii < array_size; ++ii) {
3211 
3212  // Loop through the encrypted symmetric keys, and for each:
3213  // read its network-order NymID size (convert to host version), and
3214  // then read its NymID,
3215  // read its network-order key content size (convert to host), and
3216  // then read its key content.
3217 
3218  uint32_t nymid_len_n = 0;
3219  uint32_t nReadNymIDSize = 0;
3220 
3221  if (0 == (nReadNymIDSize = dataInput.OTfread(
3222  reinterpret_cast<uint8_t*>(&nymid_len_n),
3223  static_cast<uint32_t>(sizeof(nymid_len_n))))) {
3224  otErr << szFunc << ": Error reading NymID length for an encrypted "
3225  "symmetric key.\n";
3226  return false;
3227  }
3228  nRunningTotal += nReadNymIDSize;
3229  OT_ASSERT(nReadNymIDSize == static_cast<uint32_t>(sizeof(nymid_len_n)));
3230 
3231  // convert that array size from network to HOST endian.
3232  //
3233  uint32_t nymid_len = static_cast<uint32_t>(ntohl(static_cast<uint32_t>(
3234  nymid_len_n))); // FYI: ntohl returns uint32_t !!!!!
3235 
3236  otLog5 << __FUNCTION__
3237  << ": NymID length: " << static_cast<int64_t>(nymid_len) << "\n";
3238 
3239  // nRunningTotal += nymid_len; // Nope!
3240 
3241  uint8_t* nymid =
3242  static_cast<uint8_t*>(malloc(sizeof(uint8_t) * nymid_len));
3243  OT_ASSERT(nullptr != nymid);
3244  nymid[0] = '\0'; // null terminator.
3245 
3246  uint32_t nReadNymID = 0;
3247 
3248  if (0 == (nReadNymID = dataInput.OTfread(
3249  reinterpret_cast<uint8_t*>(nymid),
3250  static_cast<uint32_t>(sizeof(uint8_t) *
3251  nymid_len)))) // this length
3252  // includes the null
3253  // terminator (it was
3254  // written that way.)
3255  {
3256  otErr << szFunc
3257  << ": Error reading NymID for an encrypted symmetric key.\n";
3258  free(nymid);
3259  nymid = nullptr;
3260  return false;
3261  }
3262  nRunningTotal += nReadNymID;
3263  OT_ASSERT(nReadNymID ==
3264  static_cast<uint32_t>(sizeof(uint8_t) * nymid_len));
3265  // OT_ASSERT(nymid_len == nReadNymID);
3266 
3267  nymid[nymid_len - 1] = '\0'; // for null terminator. If string is 10
3268  // bytes int64_t, it's from 0-9, and the
3269  // null terminator is at index 9.
3270  const OTString loopStrNymID(reinterpret_cast<char*>(nymid));
3271  free(nymid);
3272  nymid = nullptr;
3273 
3274  otLog5 << __FUNCTION__ << ": (LOOP) Current NymID: " << loopStrNymID
3275  << " Strlen: "
3276  << static_cast<int64_t>(loopStrNymID.GetLength()) << "\n";
3277 
3278  // loopStrNymID ... if this matches strNymID then it's the one we're
3279  // looking for.
3280  // But we have to load it all either way, just to iterate through them,
3281  // so might
3282  // as well load it all first, then check. If it matches, we use it and
3283  // break.
3284  // Otherwise we keep iterating until we find it.
3285  //
3286  // Read its network-order key content size (convert to host-order), and
3287  // then
3288  // read its key content.
3289  uint8_t* ek = nullptr;
3290  uint32_t eklen = 0;
3291  uint32_t eklen_n = 0;
3292  uint32_t nReadLength = 0;
3293  uint32_t nReadKey = 0;
3294 
3295  // First we read the encrypted key size.
3296  //
3297  if (0 == (nReadLength = dataInput.OTfread(
3298  reinterpret_cast<uint8_t*>(&eklen_n),
3299  static_cast<uint32_t>(sizeof(eklen_n))))) {
3300  otErr << szFunc << ": Error reading encrypted key size.\n";
3301  return false;
3302  }
3303  nRunningTotal += nReadLength;
3304  OT_ASSERT(nReadLength == static_cast<uint32_t>(sizeof(eklen_n)));
3305 
3306  // convert that key size from network to host endian.
3307  //
3308  eklen = static_cast<uint32_t>(ntohl(static_cast<uint32_t>(eklen_n)));
3309  // eklen = EVP_PKEY_size(private_key); // We read this size from
3310  // file now...
3311 
3312  otLog5 << __FUNCTION__
3313  << ": EK length: " << static_cast<int64_t>(eklen) << " \n";
3314 
3315  // nRunningTotal += eklen; // Nope!
3316 
3317  ek = static_cast<uint8_t*>(
3318  malloc(static_cast<int32_t>(eklen) *
3319  sizeof(uint8_t))); // I assume this is for the AES key
3320  OT_ASSERT(nullptr != ek);
3321  memset(static_cast<void*>(ek), 0, static_cast<int32_t>(eklen));
3322 
3323  // Next we read the encrypted key itself...
3324  //
3325  if (0 == (nReadKey = dataInput.OTfread(reinterpret_cast<uint8_t*>(ek),
3326  static_cast<uint32_t>(eklen)))) {
3327  otErr << szFunc << ": Error reading encrypted key.\n";
3328  free(ek);
3329  ek = nullptr;
3330  return false;
3331  }
3332  nRunningTotal += nReadKey;
3333 
3334  otLog5 << __FUNCTION__
3335  << ": EK First byte: " << static_cast<int32_t>(ek[0])
3336  << " EK Last byte: " << static_cast<int32_t>(ek[eklen - 1])
3337  << "\n";
3338 
3339  OT_ASSERT(nReadKey == static_cast<uint32_t>(eklen));
3340 
3341  // If we "found the key already" that means we already found the right
3342  // key on
3343  // a previous iteration, so therefore we're *definitely* just going to
3344  // throw
3345  // THIS one away. We just continue on to the next iteration and keep
3346  // counting
3347  // the bytes.
3348  //
3349  if (!bFoundKeyAlready) {
3350  // We have NOT found the right key yet, so let's see if this is the
3351  // one we're looking for.
3352 
3353  const bool bNymIDMatches =
3354  strNymID.Compare(loopStrNymID); // FOUND IT! <==========
3355 
3356  if ((ii == (array_size - 1)) || // If we're on the LAST INDEX in the
3357  // array (often the only index), OR
3358  // if the
3359  bNymIDMatches) // NymID is a guaranteed match, then we'll try to
3360  // decrypt using this session key.
3361  { // (Of course also we know that we haven't found the Key yet, or
3362  // we wouldn't even be here.)
3363  // NOTE: What if we're on the last index, but the NymID DOES
3364  // exist, and it DEFINITELY doesn't match?
3365  // In other words, if loopStrNymID EXISTS, and it DEFINITELY
3366  // doesn't match (bNymIDMatches is false) then we
3367  // DEFINITELY want to skip it. But if bNymIDMatches is false
3368  // simply because loopStrNymID is EMPTY, then we
3369  // can't rule that key out, in that case.
3370  //
3371  if (!(loopStrNymID.Exists() &&
3372  !bNymIDMatches)) // Skip if ID was definitely found and
3373  // definitely doesn't match.
3374  {
3375  bFoundKeyAlready = true;
3376 
3377  theRawEncryptedKey.Assign(static_cast<void*>(ek),
3378  static_cast<uint32_t>(eklen));
3379  // theRawEncryptedKey.Assign(const_cast<const
3380  // void *>(static_cast<void *>(ek)), eklen);
3381  }
3382  }
3383  }
3384 
3385  free(ek);
3386  ek = nullptr;
3387 
3388  } // for
3389 
3390  if (!bFoundKeyAlready) // Todo: AND if list of POTENTIAL matches is
3391  // also empty...
3392  {
3393  otOut << __FUNCTION__
3394  << ": Sorry: Unable to find a session key for the Nym attempting "
3395  "to open this envelope: " << strNymID << "\n";
3396  return false;
3397  }
3398 
3399  // Read network-order IV size (convert to host version) before then reading
3400  // IV itself.
3401  // (Then update encrypted blocks until evp open final...)
3402  //
3403  const uint32_t max_iv_length =
3404  OTCryptoConfig::SymmetricIvSize(); // I believe this is a max length, so
3405  // it may not match the actual
3406  // length.
3407 
3408  // Read the IV SIZE (network order version -- convert to host version.)
3409  //
3410  uint32_t iv_size_n = 0;
3411  uint32_t nReadIVSize = 0;
3412 
3413  if (0 == (nReadIVSize = dataInput.OTfread(
3414  reinterpret_cast<uint8_t*>(&iv_size_n),
3415  static_cast<uint32_t>(sizeof(iv_size_n))))) {
3416  otErr << szFunc
3417  << ": Error reading IV Size for encrypted symmetric keys.\n";
3418  return false;
3419  }
3420  nRunningTotal += nReadIVSize;
3421  OT_ASSERT(nReadIVSize == static_cast<uint32_t>(sizeof(iv_size_n)));
3422 
3423  // convert that iv size from network to HOST endian.
3424  //
3425  const uint32_t iv_size_host_order = ntohl(static_cast<uint32_t>(iv_size_n));
3426 
3427  if (iv_size_host_order > max_iv_length) {
3428  const int64_t l1 = iv_size_host_order, l2 = max_iv_length;
3429  otErr << __FUNCTION__ << ": Error: iv_size (" << l1
3430  << ") is larger than max_iv_length (" << l2 << ").\n";
3431  return false;
3432  }
3433  else
3434  otLog5 << __FUNCTION__
3435  << ": IV size: " << static_cast<int64_t>(iv_size_host_order)
3436  << "\n";
3437 
3438  // Then read the IV (initialization vector) itself.
3439  //
3440  if (0 == (nReadIV = dataInput.OTfread(
3441  reinterpret_cast<uint8_t*>(iv),
3442  static_cast<uint32_t>(iv_size_host_order)))) {
3443  otErr << szFunc << ": Error reading initialization vector.\n";
3444  return false;
3445  }
3446 
3447  nRunningTotal += nReadIV;
3448  OT_ASSERT(nReadIV == static_cast<uint32_t>(iv_size_host_order));
3449 
3450  otLog5 << __FUNCTION__
3451  << ": IV First byte: " << static_cast<int32_t>(iv[0])
3452  << " IV Last byte: "
3453  << static_cast<int32_t>(iv[iv_size_host_order - 1]) << "\n";
3454 
3455  // We read the encrypted key size, then we read the encrypted key itself,
3456  // with nReadKey containing
3457  // the number of bytes actually read. The IF statement says "if 0 ==" but it
3458  // should probably say
3459  // "if eklen !=" (right?) Wrong: because I think it's a max length.
3460  //
3461  // We create an OTData object to store the ciphertext itself, which begins
3462  // AFTER the end of the IV.
3463  // So we see pointer + nRunningTotal as the starting point for the
3464  // ciphertext.
3465  // the size of the ciphertext, meanwhile, is the size of the entire thing,
3466  // MINUS nRunningTotal.
3467  //
3468  OTData ciphertext(static_cast<const void*>(
3469  static_cast<const uint8_t*>(dataInput.GetPointer()) +
3470  nRunningTotal),
3471  dataInput.GetSize() - nRunningTotal);
3472 
3473  //
3474  const EVP_CIPHER* cipher_type = EVP_aes_128_cbc(); // todo hardcoding.
3475  //
3476  // OTPayload
3477  // void SetPayloadSize (uint32_t lNewSize);
3478  // const
3479  // void * GetPayloadPointer() const;
3480 
3481  // OTData
3482  // inline
3483  // uint32_t GetSize () const { return m_lSize; }
3484  // bool IsEmpty () const;
3485  // virtual void Release ();
3486  // void Assign (const void* pNewData, uint32_t lNewSize);
3487  // void Concatenate(const void* pNewData, uint32_t lNewSize);
3488 
3489  // int32_t EVP_OpenInit(
3490  // EVP_CIPHER_CTX *ctx,
3491  // EVP_CIPHER *type,
3492  // uint8_t *ek,
3493  // int32_t ekl,
3494  // uint8_t *iv,
3495  // EVP_PKEY *priv);
3496 
3497  // if (!EVP_OpenInit(&ctx, cipher_type, ek, eklen, iv, private_key))
3498  if (!EVP_OpenInit(
3499  &ctx, cipher_type,
3500  static_cast<const uint8_t*>(theRawEncryptedKey.GetPayloadPointer()),
3501  static_cast<int32_t>(theRawEncryptedKey.GetSize()),
3502  static_cast<const uint8_t*>(iv), private_key)) {
3503 
3504  // EVP_OpenInit() initializes a cipher context ctx for decryption with
3505  // cipher type. It decrypts the encrypted
3506  // symmetric key of length ekl bytes passed in the ek parameter using
3507  // the private key priv. The IV is supplied
3508  // in the iv parameter.
3509 
3510  otErr << szFunc << ": EVP_OpenInit: failed.\n";
3511  return false;
3512  }
3513 
3514  // Now we process ciphertext and write the decrypted data to plaintext.
3515  //
3516  OTData plaintext;
3517 
3518  // We loop through the ciphertext and process it in blocks...
3519  //
3520  while (0 <
3521  (len = ciphertext.OTfread(reinterpret_cast<uint8_t*>(buffer),
3522  static_cast<uint32_t>(sizeof(buffer))))) {
3523  if (!EVP_OpenUpdate(&ctx, buffer_out, &len_out, buffer,
3524  static_cast<int32_t>(len))) {
3525  otErr << szFunc << ": EVP_OpenUpdate: failed.\n";
3526  return false;
3527  }
3528  else if (len_out > 0)
3529  plaintext.Concatenate(reinterpret_cast<void*>(buffer_out),
3530  static_cast<uint32_t>(len_out));
3531  else
3532  break;
3533  }
3534 
3535  if (!EVP_OpenFinal(&ctx, buffer_out, &len_out)) {
3536  otErr << szFunc << ": EVP_OpenFinal: failed.\n";
3537  return false;
3538  }
3539  else if (len_out > 0) {
3540  bFinalized = true;
3541  plaintext.Concatenate(reinterpret_cast<void*>(buffer_out),
3542  static_cast<uint32_t>(len_out));
3543 
3544  }
3545  else {
3546  // cppcheck-suppress unreadVariable
3547  bFinalized = true;
3548  }
3549 
3550  // Make sure it's null-terminated...
3551  //
3552  uint32_t nIndex =
3553  plaintext.GetSize() - 1; // null terminator is already part of length
3554  // here (it was, or at least should have been,
3555  // sealed that way in the first place.)
3556  (static_cast<uint8_t*>(const_cast<void*>(plaintext.GetPointer())))[nIndex] =
3557  '\0';
3558 
3559  // Set it into theOutput (to return the plaintext to the caller)
3560  //
3561  // if size is 10, then indices are 0..9 and we pass '10' as the size here.
3562  // Since it's an OTData, then the 10th byte (at index 9) is expected to
3563  // contain
3564  // the null terminator.
3565  // Thus the ACTUAL string is only 9 bytes int64_t, and is contained in
3566  // indices 0..8.
3567  //
3568  const bool bSetMem = theOutput.MemSet(
3569  static_cast<const char*>(plaintext.GetPointer()), plaintext.GetSize());
3570 
3571  if (bSetMem)
3572  otLog5 << __FUNCTION__ << ": Output:\n" << theOutput << "\n\n";
3573  else
3574  otErr << __FUNCTION__ << ": Error: Failed while trying to memset from "
3575  "plaintext OTData to output OTString.\n";
3576 
3577  return bSetMem;
3578 }
3579 
3580 // If length is 10,
3581 // Then indices are 0..9
3582 // Therefore '9' is the 10th byte, starting from 0.
3583 // Therefore "GetSize()" would be 10,
3584 // and "GetSize()-1" would be 9, which is the 10th byte starting from 0.
3585 // Therefore if the string is 9 bytes int64_t, it will have data from 0 through
3586 // 8, with 9 being \0.
3587 // Normally you wouldn't expect a string to include the null terminator as part
3588 // of its length.
3589 // But for OTData, you WOULD expect the null 0 to be at the end.
3590 //
3591 
3592 /*
3593  * An implementation of RSA PSS digital signature using OpenSSL
3594  *
3595  * Copyright (c) 2009 Mounir IDRASSI <[email protected]>. All rights
3596  *reserved.
3597  *
3598  * This program is distributed in the hope that it will be useful,
3599  * but WITHOUT ANY WARRANTY; without even the implied warranty of
3600  *MERCHANTABILITY
3601  * or FITNESS FOR A PARTICULAR PURPOSE.
3602  *
3603  */
3604 /*
3605 // inside a comment here #include <cstdio>
3606 // inside a comment here #include <string.h>
3607 #include <openssl/err.h>
3608 #include <openssl/evp.h>
3609 #include <openssl/rsa.h>
3610 #include <openssl/rand.h>
3611 
3612 
3613 int32_t main(int32_t argc, char** argv)
3614 {
3615  RSA* pRsaKey = nullptr;
3616  uint8_t pDigest[32];
3617  size_t uDigestLen = 32;
3618  const char* szMessage = "This is the string to be signed";
3619  EVP_MD_CTX md_ctx;
3620  uint8_t EM[128];
3621  uint8_t pSignature[128];
3622  uint8_t pDecrypted[128];
3623  int32_t status = 0;
3624 
3625  // openssl initialization
3626  ERR_load_crypto_strings();
3627  OpenSSL_add_all_algorithms();
3628 
3629 #ifdef _WIN32
3630  RAND_screen();
3631 #else
3632  RAND_poll();
3633 #endif
3634 
3635  // Generate an RSA key pair
3636  pRsaKey = RSA_generate_key(1024, 0x010001, nullptr, nullptr);
3637  if (!pRsaKey)
3638  {
3639  printf("RSA_generate_key failed with error %s\n",
3640 ERR_error_string(ERR_get_error(), nullptr));
3641  goto prog_end;
3642  }
3643 
3644  // hash the message
3645  EVP_MD_CTX_init(&md_ctx);
3646  EVP_DigestInit(&md_ctx, EVP_sha256());
3647  EVP_DigestUpdate(&md_ctx, (const void*) szMessage, strlen(szMessage));
3648  EVP_DigestFinal(&md_ctx, pDigest, &uDigestLen);
3649  EVP_MD_CTX_cleanup(&md_ctx);
3650 
3651  // compute the PSS padded data
3652  status = RSA_padding_add_PKCS1_PSS(pRsaKey, EM, pDigest, EVP_sha256(), -2);
3653 //maximum salt length
3654  if (!status)
3655  {
3656  printf("RSA_padding_add_PKCS1_PSS failed with error %s\n",
3657 ERR_error_string(ERR_get_error(), nullptr));
3658  goto prog_end;
3659  }
3660 
3661  // perform digital signature
3662  status = RSA_private_encrypt(128, EM, pSignature, pRsaKey, RSA_NO_PADDING);
3663  if (status == -1)
3664  {
3665  printf("RSA_private_encrypt failed with error %s\n",
3666 ERR_error_string(ERR_get_error(), nullptr));
3667  goto prog_end;
3668  }
3669 
3670  // now we will verify the signature
3671  // Start by a RAW decrypt of the signature
3672  status = RSA_public_decrypt(128, pSignature, pDecrypted, pRsaKey,
3673 RSA_NO_PADDING);
3674  if (status == -1)
3675  {
3676  printf("RSA_public_decrypt failed with error %s\n",
3677 ERR_error_string(ERR_get_error(), nullptr));
3678  goto prog_end;
3679  }
3680 
3681  // verify the data
3682  status = RSA_verify_PKCS1_PSS(pRsaKey, pDigest, EVP_sha256(), pDecrypted,
3683 -2); // salt length recovered from signature
3684  if (status == 1)
3685  {
3686  printf("Signature verification successfull!\n");
3687  }
3688  else
3689  {
3690  printf("RSA_verify_PKCS1_PSS failed with error %s\n",
3691 ERR_error_string(ERR_get_error(), nullptr));
3692  goto prog_end;
3693  }
3694 
3695 prog_end:
3696  if (pRsaKey)
3697  RSA_free(pRsaKey);
3698 
3699  // openssl cleanup
3700  CRYPTO_cleanup_all_ex_data();
3701  RAND_cleanup();
3702  EVP_cleanup();
3703  ERR_free_strings();
3704  ERR_remove_state(0);
3705 
3706  return 0;
3707 }
3708 */
3709 
3710 // The default hashing algorithm in this software should be one that XOR
3711 // combines two other,
3712 // established and respected algorithms. In this case, we use the "SAMY" hash
3713 // which is actually
3714 // SHA512 XOR'd with WHIRLPOOL (also 512 in output). Credit to SAMY for the
3715 // idea.
3716 //
3717 // This way if one is ever cracked, our system is still strong, and we can swap
3718 // it out.
3719 // Thus, I had to write this special function so that if the Default hash
3720 // algorithm is the one
3721 // chosen, ("SAMY") then we have to hash it twice using Hash1 (SHA512) and Hash2
3722 // (Whirlpool)
3723 // before we encrypt it with the private key.
3724 //
3725 // Since the envelope (EVP) interface did not allow this, I had to Google
3726 // everywhere to find
3727 // lower-level code I could model.
3728 
3729 /*
3730  128 bytes * 8 bits == 1024 bits key. (RSA)
3731 
3732  64 bytes * 8 bits == 512 bits key (for WHIRLPOOL and SHA-512 message digests.)
3733 
3734  BUT--now I want to allow various key sizes (above 1024...)
3735  and I also have a smaller message digest now: 256 bits.
3736 
3737  */
3739  const OTString& strContractUnsigned, const EVP_PKEY* pkey,
3740  OTSignature& theSignature, const OTPasswordData*) const
3741 {
3742  const char* szFunc = "OTCrypto_OpenSSL::SignContractDefaultHash";
3743 
3744  bool bReturnValue = false;
3745 
3746  // These two contain the output of the two message digest
3747  // functions that we're using (SHA-256 and WHIRLPOOL.)
3748  // the two output hashes are then merged together into this one.
3749  std::vector<uint8_t> vOutputHash1(OTCryptoConfig::SymmetricKeySizeMax());
3750  std::vector<uint8_t> vOutputHash2(OTCryptoConfig::SymmetricKeySizeMax());
3751  std::vector<uint8_t> vDigest(OTCryptoConfig::SymmetricKeySizeMax());
3752 
3753  // This stores the message digest, pre-encrypted, but with the padding
3754  // added.
3755  // This stores the final signature, when the EM value has been signed by RSA
3756  // private key.
3757  std::vector<uint8_t> vEM(OTCryptoConfig::PublicKeysizeMax());
3758  std::vector<uint8_t> vpSignature(OTCryptoConfig::PublicKeysizeMax());
3759 
3760  uint32_t uDigest1Len =
3761  OTCryptoConfig::Digest1Size(); // 32 bytes == 256 bits. (These are used
3762  // for function output below, not input.)
3763  uint32_t uDigest2Len =
3764  OTCryptoConfig::Digest2Size(); // 64 bytes == 512 bits. (These are used
3765  // for function output below, not input.)
3766 
3767  EVP_MD_CTX mdHash1_ctx, mdHash2_ctx;
3768 
3769  // OTPassword::zeroMemory(uint8_t* szMemory, uint32_t theSize);
3770  // OTPassword::zeroMemory(void* vMemory, uint32_t theSize);
3771  OTPassword::zeroMemory(&vOutputHash1.at(0),
3773  OTPassword::zeroMemory(&vOutputHash2.at(0),
3775  OTPassword::zeroMemory(&vDigest.at(0),
3778  OTPassword::zeroMemory(&vpSignature.at(0),
3780 
3781  // Here, we convert the EVP_PKEY that was passed in, to an RSA key for
3782  // signing.
3783  //
3784  RSA* pRsaKey = EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pkey));
3785 
3786  if (!pRsaKey) {
3787  otErr << szFunc << ": EVP_PKEY_get1_RSA failed with error "
3788  << ERR_error_string(ERR_get_error(), nullptr) << "\n";
3789  return false;
3790  }
3791 
3792  // Since the idea of this special code is that we're using 2 hash
3793  // algorithms,
3794  // let's look them up and see what they are.
3795  // addendum: unless we're on Android... then there's only 1 hash algorithm.
3796  //
3797  const EVP_MD* digest1 =
3799  OTIdentifier::HashAlgorithm1); // SHA-256
3800 
3801  if (nullptr == digest1) {
3802  otErr << szFunc << ": Failure to load message digest algorithm.\n";
3803  RSA_free(pRsaKey);
3804  pRsaKey = nullptr;
3805  return false;
3806  }
3807 
3808  // hash the contents of the contract with HashAlgorithm1 (SHA-256)
3809  EVP_MD_CTX_init(&mdHash1_ctx);
3810  EVP_DigestInit(&mdHash1_ctx, digest1); // digest1 is the actual algorithm
3811  EVP_DigestUpdate(&mdHash1_ctx, strContractUnsigned.Get(),
3812  strContractUnsigned.GetLength()); // input
3813  EVP_DigestFinal(&mdHash1_ctx, &vOutputHash1.at(0),
3814  &uDigest1Len); // output and length
3815  EVP_MD_CTX_cleanup(&mdHash1_ctx); // cleanup
3816 
3817  /*
3818  TODO:
3819  The functions EVP_DigestInit(), EVP_DigestFinal() and EVP_MD_CTX_copy() are
3820  obsolete but are retained to maintain compatibility
3821  with existing code. New applications should use EVP_DigestInit_ex(),
3822  EVP_DigestFinal_ex() and EVP_MD_CTX_copy_ex() because they
3823  can efficiently reuse a digest context instead of initializing and cleaning
3824  it up on each call and allow non default implementations
3825  of digests to be specified.
3826  */
3827  //#ifndef ANDROID
3828  const EVP_MD* digest2 =
3830  OTIdentifier::HashAlgorithm2); // WHIRLPOOL (512)
3831 
3832  if (nullptr == digest2) {
3833  otErr << szFunc << ": Failure to load message digest algorithm.\n";
3834  RSA_free(pRsaKey);
3835  pRsaKey = nullptr;
3836  return false;
3837  }
3838 
3839  // hash the same contents with HashAlgorithm2 (WHIRLPOOL)
3840  EVP_MD_CTX_init(&mdHash2_ctx);
3841  EVP_DigestInit(&mdHash2_ctx, digest2); // digest2 is the algorithm
3842  EVP_DigestUpdate(&mdHash2_ctx, strContractUnsigned.Get(),
3843  strContractUnsigned.GetLength()); // Input
3844  EVP_DigestFinal(&mdHash2_ctx, &vOutputHash2.at(0),
3845  &uDigest2Len); // output and length
3846  EVP_MD_CTX_cleanup(&mdHash2_ctx); // cleanup
3847 
3848  // (Goes with the smaller size.)
3849  const uint32_t uDigestMergedLength =
3850  (uDigest1Len > uDigest2Len ? uDigest2Len : uDigest1Len);
3851 
3852  // XOR the two together
3853  //
3854  for (uint32_t i = 0; i < uDigestMergedLength; i++) {
3855  vDigest.at(i) = ((vOutputHash1.at(i)) ^ (vOutputHash2.at(i)));
3856  }
3857  //#else // ANDROID
3858  // const uint32_t uDigestMergedLength = uDigest1Len;
3859  //
3860  // for (int32_t i = 0; i < uDigestMergedLength; i++)
3861  // {
3862  // pDigest[i] = (vOutputHash1.at(i));
3863  // }
3864  //#endif // ANDROID
3865 
3866  // pDigest is now set up.
3867  // uDigestMergedLength contains its length in bytes.
3868 
3869  /*
3870  NOTE:
3871  RSA_sign only supports PKCS# 1 v1.5 padding which always gives the same
3872  output for the same input data.
3873  If you want to perfom a digital signature with PSS padding, you have to
3874  pad the data yourself by calling RSA_padding_add_PKCS1_PSS and then call
3875  RSA_private_encrypt on the padded output after setting its last
3876  parameter to RSA_NO_PADDING.
3877 
3878  I have written a small sample code that shows how to perform PSS
3879  signature and verification. You can get the code from the following link:
3880  http://www.idrix.fr/Root/Samples/openssl_pss_signature.c
3881 
3882  I hope this answers your questions.
3883  Cheers,
3884  --
3885  Mounir IDRASSI
3886  */
3887  // compute the PSS padded data
3888  // the result goes into EM.
3889 
3890  /*
3891  int32_t RSA_padding_add_PKCS1_PSS(RSA* rsa, uint8_t* EM, const uint8_t*
3892  mHash, const EVP_MD* Hash, int32_t sLen);
3893  */
3894  // int32_t RSA_padding_add_xxx(uint8_t* to, int32_t tlen,
3895  // uint8_t *f, int32_t fl);
3896  // RSA_padding_add_xxx() encodes *fl* bytes from *f* so as to fit into
3897  // *tlen*
3898  // bytes and stores the result at *to*.
3899  // An error occurs if fl does not meet the size requirements of the encoding
3900  // method.
3901  // The RSA_padding_add_xxx() functions return 1 on success, 0 on error.
3902  // The RSA_padding_check_xxx() functions return the length of the recovered
3903  // data, -1 on error.
3904 
3905  // rsa EM mHash Hash sLen
3906  // in OUT IN in in
3907  int32_t status =
3908  RSA_padding_add_PKCS1_PSS(pRsaKey, &vEM.at(0), &vDigest.at(0), digest1,
3909  -2); // maximum salt length
3910 
3911  // Above, pDigest is the input, but its length is not needed, since it is
3912  // determined
3913  // by the digest algorithm (digest1.) In this case, that size is 32 bytes ==
3914  // 256 bits.
3915 
3916  // Also notice that digest1 and digest2 are both processed, and then digest1
3917  // is used here
3918  // again, since RSA_padding_add_PKCS1_PSS requires a digest. Might be
3919  // optimization opportunities there.
3920  //
3921  // More clearly: pDigest is 256 bits int64_t, aka 32 bytes. The call to
3922  // RSA_padding_add_PKCS1_PSS above
3923  // is transforming its contents based on digest1, into EM. Once this is
3924  // done, the new digest stored in
3925  // EM will be RSA_size(pRsaKey)-11 bytes in size, with the rest padded.
3926  // Therefore if this is sucessful, then we can call RSA_private_encrypt
3927  // without any further padding,
3928  // since it's already accomplished here. EM itself will be RSA_size(pRsaKey)
3929  // in size total (exactly.)
3930 
3931  if (!status) // 1 or 0.
3932  {
3933  otErr << __FILE__ << ": RSA_padding_add_PKCS1_PSS failure: "
3934  << ERR_error_string(ERR_get_error(), nullptr) << "\n";
3935  RSA_free(pRsaKey);
3936  pRsaKey = nullptr;
3937  return false;
3938  }
3939 
3940  // EM is now set up.
3941  // But how big is it? Answer: RSA_size(pRsaKey)
3942  // No size is returned because the whole point of RSA_padding_add_PKCS1_PSS
3943  // is to safely pad
3944  // pDigest into EM within a specific size based on the keysize.
3945 
3946  // RSA_padding_check_xxx() verifies that the fl bytes at f contain a valid
3947  // encoding for a rsa_len byte RSA key in the respective
3948  // encoding method and stores the recovered data of at most tlen bytes (for
3949  // RSA_NO_PADDING: of size tlen) at to.
3950 
3951  // RSA_private_encrypt
3952  // int32_t RSA_private_encrypt(int32_t flen, uint8_t* from,
3953  // uint8_t *to, RSA* rsa, int32_t padding);
3954  // RSA_private_encrypt() signs the *flen* bytes at *from* (usually a message
3955  // digest with
3956  // an algorithm identifier) using the private key rsa and stores the
3957  // signature in *to*.
3958  // to must point to RSA_size(rsa) bytes of memory.
3959  // RSA_private_encrypt() returns the size of the signature (i.e.,
3960  // RSA_size(rsa)).
3961  //
3962  status = RSA_private_encrypt(
3963  RSA_size(pRsaKey), // input
3964  &vEM.at(0), // padded message digest (input)
3965  &vpSignature.at(0), // encrypted padded message digest (output)
3966  pRsaKey, // private key (input )
3967  RSA_NO_PADDING); // why not RSA_PKCS1_PADDING ? (Custom padding above in
3968  // PSS mode with two hashes.)
3969 
3970  if (status == -1) {
3971  otErr << szFunc << ": RSA_private_encrypt failure: "
3972  << ERR_error_string(ERR_get_error(), nullptr) << "\n";
3973  RSA_free(pRsaKey);
3974  pRsaKey = nullptr;
3975  return false;
3976  }
3977  // status contains size
3978 
3979  OTData binSignature(&vpSignature.at(0), status); // RSA_private_encrypt
3980  // actually returns the
3981  // right size.
3982  // OTData binSignature(pSignature, 128); // stop hardcoding this block
3983  // size.
3984 
3985  // theSignature that was passed in, now contains the final signature.
3986  // The contents were hashed twice, and the resulting hashes were
3987  // XOR'd together, and then padding was added, and then it was signed
3988  // with the private key.
3989  theSignature.SetData(binSignature, true); // true means, "yes, with newlines
3990  // in the b64-encoded output,
3991  // please."
3992  bReturnValue = true;
3993 
3994  if (pRsaKey) RSA_free(pRsaKey);
3995  pRsaKey = nullptr;
3996 
3997  return bReturnValue;
3998 }
3999 
4000 // Verify a contract that has been signed with our own default algorithm (aka
4001 // SAMY hash)
4002 // Basically we had to customize for that algorithm since, by default, it XORs
4003 // two different
4004 // algorithms together (SHA256 and WHIRLPOOL) in anticipation of the day that
4005 // one of them is
4006 // broken.
4007 
4009  const OTString& strContractToVerify, const EVP_PKEY* pkey,
4010  const OTSignature& theSignature, const OTPasswordData*) const
4011 {
4012  const char* szFunc = "OTCrypto_OpenSSL::VerifyContractDefaultHash";
4013 
4014  bool bReturnValue = false;
4015 
4016  std::vector<uint8_t> vOutputHash1(
4017  OTCryptoConfig::SymmetricKeySizeMax()); // These two contain the output
4018  // of the two message digest
4019  std::vector<uint8_t> vOutputHash2(
4020  OTCryptoConfig::SymmetricKeySizeMax()); // functions that we're using
4021  // (SHA-256 and WHIRLPOOL.)
4022  std::vector<uint8_t> vDigest(
4023  OTCryptoConfig::SymmetricKeySizeMax()); // the two output hashes are
4024  // then merged together into
4025  // this one.
4026 
4027  std::vector<uint8_t> vDecrypted(
4028  OTCryptoConfig::PublicKeysizeMax()); // Contains the decrypted
4029  // signature.
4030 
4031  uint32_t uDigest1Len =
4032  OTCryptoConfig::Digest1Size(); // 32 bytes == 256 bits. (These are used
4033  // for function output below, not input.)
4034  uint32_t uDigest2Len =
4035  OTCryptoConfig::Digest2Size(); // 64 bytes == 512 bits. (These are used
4036  // for function output below, not input.)
4037 
4038  EVP_MD_CTX mdHash1_ctx, mdHash2_ctx;
4039 
4040  OTPassword::zeroMemory(&vOutputHash1.at(0),
4042  OTPassword::zeroMemory(&vOutputHash2.at(0),
4044  OTPassword::zeroMemory(&vDigest.at(0),
4046  OTPassword::zeroMemory(&vDecrypted.at(0),
4048 
4049  // Here, we convert the EVP_PKEY that was passed in, to an RSA key for
4050  // signing.
4051  RSA* pRsaKey = EVP_PKEY_get1_RSA(const_cast<EVP_PKEY*>(pkey));
4052 
4053  if (!pRsaKey) {
4054  otErr << szFunc << ": EVP_PKEY_get1_RSA failed with error "
4055  << ERR_error_string(ERR_get_error(), nullptr) << "\n";
4056  return false;
4057  }
4058 
4059  // Since the idea of this special code is that we're using 2 hash
4060  // algorithms,
4061  // let's look them up and see what they are.
4062  const EVP_MD* digest1 =
4064  OTIdentifier::HashAlgorithm1); // SHA-256
4065  if (nullptr == digest1) {
4066  otErr << szFunc << ": Failure to load message digest algorithm.\n";
4067  RSA_free(pRsaKey);
4068  pRsaKey = nullptr;
4069  return false;
4070  }
4071 
4072  // hash the contents of the contract with HashAlgorithm1 (SHA-256)
4073  EVP_MD_CTX_init(&mdHash1_ctx);
4074  EVP_DigestInit(&mdHash1_ctx, digest1); // digest1 is the algorithm itself
4075  EVP_DigestUpdate(&mdHash1_ctx, strContractToVerify.Get(),
4076  strContractToVerify.GetLength()); // input
4077  EVP_DigestFinal(&mdHash1_ctx, &vOutputHash1.at(0),
4078  &uDigest1Len); // output and size
4079  EVP_MD_CTX_cleanup(&mdHash1_ctx); // cleanup
4080 
4081  //#ifndef ANDROID // NOT Android.
4082  const EVP_MD* digest2 =
4084  OTIdentifier::HashAlgorithm2); // WHIRLPOOL
4085  if (nullptr == digest2) {
4086  otErr << szFunc << ": Failure to load message digest algorithm.\n";
4087  RSA_free(pRsaKey);
4088  pRsaKey = nullptr;
4089  return false;
4090  }
4091 
4092  // hash the same contents with HashAlgorithm2 (WHIRLPOOL)
4093  EVP_MD_CTX_init(&mdHash2_ctx);
4094  EVP_DigestInit(&mdHash2_ctx, digest2); // digest2 is the algorithm itself
4095  EVP_DigestUpdate(&mdHash2_ctx, strContractToVerify.Get(),
4096  strContractToVerify.GetLength()); // Input
4097  EVP_DigestFinal(&mdHash2_ctx, &vOutputHash2.at(0),
4098  &uDigest2Len); // output and size
4099  EVP_MD_CTX_cleanup(&mdHash2_ctx); // cleanup
4100 
4101  // (Goes with the smaller size.)
4102  const uint32_t uDigestMergedLength =
4103  (uDigest1Len > uDigest2Len ? uDigest2Len : uDigest1Len);
4104 
4105  // XOR the two together
4106  for (uint32_t i = 0; i < uDigestMergedLength; i++) {
4107  vDigest.at(i) = ((vOutputHash1.at(i)) ^ (vOutputHash2.at(i)));
4108  }
4109  //#else // ** is ** ANDROID
4110  //
4111  // // (Goes with the smaller size.)
4112  // const uint32_t uDigestMergedLength = uDigest1Len;
4113  //
4114  // for (int32_t i = 0; i < uDigest1Len; i++)
4115  // {
4116  // pDigest[i] = (pOutputHash1[i]);
4117  // }
4118  //#endif // ANDROID
4119 
4120  // Now we have the exact content in pDigest that we should also see if we
4121  // decrypt
4122  // the signature that was passed in.
4123  //
4124 
4125  OTPayload binSignature;
4126 
4127  // This will cause binSignature to contain the base64 decoded binary of the
4128  // signature that we're verifying. Unless the call fails of course...
4129  //
4130  if ((theSignature.GetLength() < 10) ||
4131  (false == theSignature.GetData(binSignature))) {
4132  otErr << szFunc << ": Error decoding base64 data for Signature.\n";
4133  RSA_free(pRsaKey);
4134  pRsaKey = nullptr;
4135  return false;
4136  }
4137 
4138  const int32_t nSignatureSize = static_cast<int32_t>(
4139  binSignature.GetSize()); // converting from unsigned to signed (since
4140  // openssl wants it that way.)
4141 
4142  if ((binSignature.GetSize() < static_cast<uint32_t>(RSA_size(pRsaKey))) ||
4143  (nSignatureSize < RSA_size(pRsaKey))) // this one probably unnecessary.
4144  {
4145  otErr << szFunc << ": Decoded base64-encoded data for signature, but "
4146  "resulting size was < RSA_size(pRsaKey): "
4147  "Signed: " << nSignatureSize
4148  << ". Unsigned: " << binSignature.GetSize() << ".\n";
4149  RSA_free(pRsaKey);
4150  pRsaKey = nullptr;
4151  return false;
4152  }
4153 
4154  // now we will verify the signature
4155  // Start by a RAW decrypt of the signature
4156  // output goes to pDecrypted
4157  // FYI: const void * binSignature.GetPointer()
4158 
4159  // RSA_PKCS1_OAEP_PADDING
4160  // RSA_PKCS1_PADDING
4161 
4162  // the 128 in the below call was a BUG. The SIZE of the ciphertext
4163  // (signature) being decrypted is NOT 128 (modulus / cleartext size).
4164  // Rather, the size of the signature is RSA_size(pRsaKey). Will have to
4165  // revisit this likely, elsewhere in the code.
4166  // status = RSA_public_decrypt(128, static_cast<const
4167  // uint8_t*>(binSignature.GetPointer()), pDecrypted, pRsaKey,
4168  // RSA_NO_PADDING);
4169  int32_t status = RSA_public_decrypt(
4170  nSignatureSize, // length of signature, aka RSA_size(rsa)
4171  static_cast<const uint8_t*>(
4172  binSignature.GetPayloadPointer()), // location of signature
4173  &vDecrypted.at(0), // Output--must be large enough to hold the md (which
4174  // is smaller than RSA_size(rsa) - 11)
4175  pRsaKey, // signer's public key
4176  RSA_NO_PADDING);
4177 
4178  // int32_t RSA_public_decrypt(int32_t flen, uint8_t* from,
4179  // uint8_t *to, RSA* rsa, int32_t padding);
4180 
4181  // RSA_public_decrypt() recovers the message digest from the *flen* bytes
4182  // int64_t signature at *from*,
4183  // using the signer's public key *rsa*.
4184  // padding is the padding mode that was used to sign the data.
4185  // *to* must point to a memory section large enough to hold the message
4186  // digest
4187  // (which is smaller than RSA_size(rsa) - 11).
4188  // RSA_public_decrypt() returns the size of the recovered message digest.
4189  /*
4190  message to be encrypted, an octet string of length at
4191  most k-2-2hLen, where k is the length in octets of the
4192  modulus n and hLen is the length in octets of the hash
4193  function output for EME-OAEP
4194  */
4195 
4196  if (status == -1) // Error
4197  {
4198  otErr << szFunc << ": RSA_public_decrypt failed with error "
4199  << ERR_error_string(ERR_get_error(), nullptr) << "\n";
4200  RSA_free(pRsaKey);
4201  pRsaKey = nullptr;
4202  return false;
4203  }
4204  // status contains size of recovered message digest after signature
4205  // decryption.
4206 
4207  // verify the data
4208  // Now it compares pDecrypted (the decrypted message digest from the
4209  // signature) with pDigest
4210  // (supposedly the same message digest, which we calculated above based on
4211  // the message itself.)
4212  // They SHOULD be the same.
4213  /*
4214  int32_t RSA_verify_PKCS1_PSS(RSA* rsa, const uint8_t* mHash, const EVP_MD* Hash, const uint8_t* EM, int32_t sLen)
4215  */ // rsa mHash Hash alg. EM sLen
4216  status = RSA_verify_PKCS1_PSS(pRsaKey, &vDigest.at(0), digest1,
4217  &vDecrypted.at(0),
4218  -2); // salt length recovered from signature
4219 
4220  if (status == 1) {
4221  otLog5 << " *Signature verified*\n";
4222  bReturnValue = true;
4223  }
4224  else {
4225  otLog5 << szFunc << ": RSA_verify_PKCS1_PSS failed with error: "
4226  << ERR_error_string(ERR_get_error(), nullptr) << "\n";
4227  RSA_free(pRsaKey);
4228  pRsaKey = nullptr;
4229  return false;
4230  }
4231 
4232  /*
4233 
4234  NOTE:
4235  RSA_private_encrypt() signs the flen bytes at from (usually a message
4236  digest with an algorithm identifier)
4237  using the private key rsa and stores the signature in to. to must point to
4238  RSA_size(rsa) bytes of memory.
4239 
4240  From: http://linux.die.net/man/3/rsa_public_decrypt
4241 
4242  RSA_NO_PADDING
4243  Raw RSA signature. This mode should only be used to implement
4244  cryptographically sound padding modes in the application code.
4245  Signing user data directly with RSA is insecure.
4246 
4247  RSA_PKCS1_PADDING
4248  PKCS #1 v1.5 padding. This function does not handle the algorithmIdentifier
4249  specified in PKCS #1. When generating or verifying
4250  PKCS #1 signatures, rsa_sign(3) and rsa_verify(3) should be used.
4251 
4252  Need to research this and make sure it's being done right.
4253 
4254  Perhaps my use of the lower-level call here is related to my use of two
4255  message-digest algorithms.
4256  -------------------------------
4257 
4258  On Sun, Feb 25, 2001 at 08:04:55PM -0500, Greg Stark wrote:
4259 
4260  > It is not a bug, it is a known fact. As Joseph Ashwood notes, you end up
4261  > trying to encrypt values that are larger than the modulus. The
4262  documentation
4263  > and most literature do tend to refer to moduli as having a certain
4264  "length"
4265  > in bits or bytes. This is fine for most discussions, but if you are
4266  planning
4267  > to use RSA to directly encrypt/decrypt AND you are not willing or able to
4268  > use one of the padding schemes, then you'll have to understand *all* the
4269  > details. One of these details is that it is possible to supply
4270  > RSA_public_encrypt() with plaintext values that are greater than the
4271  modulus
4272  > N. It returns values that are always between 0 and N-1, which is the only
4273  > reasonable behavior. Similarly, RSA_public_decrypt() returns values
4274  between
4275  > 0 and N-1.
4276 
4277  I have to confess I totally overlooked that and just assumed that if
4278  RSA_size(key) would be 1024, then I would be able to encrypt messages of
4279  1024
4280  bits.
4281 
4282  > There are multiple solutions to this problem. A generally useful one
4283  > is to use the RSA PKCS#1 ver 1.5 padding
4284  > (http://www.rsalabs.com/pkcs/pkcs-1/index.html). If you don't like that
4285  > padding scheme, then you might want to read the PKCS#1 document for the
4286  > reasons behind that padding scheme and decide for yourself where you can
4287  > modify it. It sounds like it be easiest if you just follow Mr. Ashwood's
4288  > advice. Is there some problem with that?
4289 
4290  Yes well, upon reading the PKCS#1 v1.5 document I noticed that Mr. Ashwood
4291  solves this problem by not only making the most significant bit zero, but
4292  in
4293  fact the 6 most significant bits.
4294 
4295  I don't want to use one of the padding schemes because I already know the
4296  message size in advance, and so does a possible attacker. Using a padding
4297  scheme would therefore add known plaintext, which does not improve
4298  security.
4299 
4300  But thank you for the link! I think this solves my problem now :).
4301  */
4302 
4303  /*
4304  #include <openssl/rsa.h>
4305 
4306  int32_t RSA_sign(int32_t type, const uint8_t* m, uint32_t m_len, uint8_t*
4307  sigret, uint32_t* siglen, RSA* rsa);
4308  int32_t RSA_verify(int32_t type, const uint8_t* m, uint32_t m_len, uint8_t*
4309  sigbuf, uint32_t siglen, RSA* rsa);
4310 
4311  DESCRIPTION
4312 
4313  RSA_sign() signs the message digest m of size m_len using the private key
4314  rsa as specified in PKCS #1 v2.0.
4315  It stores the signature in sigret and the signature size in siglen. sigret
4316  must point to RSA_size(rsa) bytes of memory.
4317 
4318  type denotes the message digest algorithm that was used to generate m. It
4319  usually is one of NID_sha1, NID_ripemd160
4320  and NID_md5; see objects(3) for details. If type is NID_md5_sha1, an SSL
4321  signature (MD5 and SHA1 message digests with
4322  PKCS #1 padding and no algorithm identifier) is created.
4323 
4324  RSA_verify() verifies that the signature sigbuf of size siglen matches a
4325  given message digest m of size m_len. type
4326  denotes the message digest algorithm that was used to generate the
4327  signature. rsa is the signer's public key.
4328 
4329  RETURN VALUES
4330 
4331  RSA_sign() returns 1 on success, 0 otherwise. RSA_verify() returns 1 on
4332  successful verification, 0 otherwise.
4333 
4334  The error codes can be obtained by ERR_get_error(3).
4335  */
4336 
4337  /*
4338  Hello,
4339  > I am getting the following error in calling OCSP_basic_verify():
4340  >
4341  > error:04067084:rsa routines:RSA_EAY_PUBLIC_DECRYPT:data too large for
4342  modulus
4343  >
4344  > Could somebody advice what is going wrong?
4345 
4346  In RSA you can encrypt/decrypt only as much data as RSA key size
4347  (size of RSA key is the size of modulus n = p*q).
4348  In this situation, RSA routine checks size of data to decrypt
4349  (probably signature) and this size of bigger than RSA key size,
4350  this if of course error.
4351  I think that in this situation this is possible when OCSP was signed
4352  with (for example) 2048 bit key (private key) and you have some
4353  certificate with (maybe old) 1024 bit public key.
4354  In this case this error may happen.
4355  My suggestion is to check signer certificate.
4356 
4357  Best regards,
4358  --
4359  Marek Marcola <[EMAIL PROTECTED]>
4360 
4361 
4362 
4363  Daniel Stenberg | 16 Jul 19:57
4364 
4365  Re: SSL cert error with CURLOPT_SSL_VERIFYPEER
4366 
4367  On Thu, 16 Jul 2009, Stephen Collyer wrote:
4368 
4369  > error:04067084:rsa routines:RSA_EAY_PUBLIC_DECRYPT:data too large for
4370  > modulus
4371 
4372  This sounds like an OpenSSL problem to me.
4373 
4374 
4375 
4376  http://www.mail-archive.com/[email protected]/msg38183.html
4377  On Tue, Dec 07, 2004, Jesse Hammons wrote:
4378 
4379  >
4380  > > Jesse Hammons wrote:
4381  > >
4382  > >> So to clarify: If I generate a 65-bit key, will I be able to use that
4383  > >> 65-bit key to sign any 64-bit value?
4384  > >
4385  > > Yes, but
4386  >
4387  > Actually, I have found the answer to be "no" :-)
4388  >
4389  > > a 65 bit key won't be very secure AT ALL, it will be
4390  > > very easy to factor a modulus that small.
4391  >
4392  > Security is not my goal. This is more of a theoretical exercise that
4393  > happens to have a practical application for me.
4394  >
4395  > > Bottom line: asymmetrical
4396  > > (public-key) encryption has a fairly large "minimum block size" that
4397  > > actually increases as key size increases.
4398  >
4399  > Indeed. I have found experimentally that:
4400  > * The minimum signable data quantity in OpenSSL is 1 byte
4401  > * The minimum size RSA key that can be used to sign 1 byte is 89 bits
4402  > * A signature created using a 64-bit RSA key would create a number 64
4403  > bits int64_t, BUT:
4404  > - This is not possible to do in OpenSSL because the maximum signable
4405  > quantity for a 64
4406  > bit RSA key is only a few bits, and OpenSSL input/output is done on
4407  > byte boundaries
4408  >
4409  > Do those number sound right?
4410 
4411  It depends on the padding mode. These insert/delete padding bytes depending
4412  on
4413  the mode used. If you use the no padding mode you can "sign" data equal to
4414  the
4415  modulus length but less than its magnitude.
4416 
4417  Check the manual pages (e.g. RSA_private_encrypt()) for more info.
4418 
4419 
4420 
4421 
4422 
4423  http://www.mail-archive.com/[email protected]/msg29731.html
4424  Hmm, the error message "RSA_R_DATA_TOO_LARGE_FOR_MODULUS"
4425  is triggered by:
4426 
4427  ... (from RSA_eay_private_encrypt() in rsa_eay.c)
4428  if (BN_ucmp(&f, rsa->n) >= 0)
4429  {
4430  // usually the padding functions would catch this
4431  RSAerr(...,RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
4432  goto err;
4433  }
4434  ...
4435  => the error message has nothing to do with PKCS#1. It should tell you
4436  that your plaintext (as a BIGNUM) is greater (or equal) than the modulus.
4437  The typical error message in case of PKCS#1 error (in your case) would
4438  be "RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE".
4439 
4440  > I can arrange for the plaintext to be a little smaller: 14 octets is
4441  > definitely doable. (The 15 octet length for the ciphertext I can't
4442  exceed.)
4443  > If I arrange for the plaintext to be a zero followed by 14 octets of
4444  data,
4445  > can I make this work?
4446 
4447  it should work (, but what about a longer (== more secure) key ?)
4448 
4449  Regards,
4450  Nils
4451 
4452 
4453 
4454 
4455  For reasons that would be tedious to rehearse, the size of the encrypted
4456  block has to be not more than 15 octets.
4457  I was hoping for something a little more definitive than "should work."
4458 
4459 
4460  >
4461  > Would a good approach be perhaps to generate keys until I found one for
4462  > which n is greater than the bignum representation of the largest
4463  plaintext?
4464  > (Yeah, I know, this would restrict the key space, which might be a
4465  security
4466  > concern.)
4467 
4468  It would be sufficient is the highest bit of the plaintext is zero
4469  , because the highest bit of the modulus is certainly set
4470  (at least if the key is generated with OpenSSL).
4471 
4472  ...
4473  > > it should work (, but what about a longer (== more secure) key ?)
4474  >
4475  > For reasons that would be tedious to rehearse, the size of the encrypted
4476  > block has to be not more than 15 octets.
4477  >
4478  > I was hoping for something a little more definitive than "should work."
4479 
4480  Ok , unless something really strange happens: it will work :-)
4481 
4482  Regards,
4483  Nils
4484 
4485 
4486  Re: RSA_private_encrypt does not work with RSA_NO_PADDING option
4487  by Dr. Stephen Henson Jul 19, 2010; 10:31am :: Rate this Message: - Use
4488  ratings to moderate (?)
4489  Reply | Print | View Threaded | Show Only this Message
4490  On Mon, Jul 19, 2010, anhpham wrote:
4491 
4492  >
4493  > Hi all :x
4494  > I encountered an error when using function RSA_private_encrypt with
4495  > RSA_NO_PADDING option.
4496  > I had an uint8_t array a with length = 20, RSA* r,
4497  > uint8_t* sig = (uint8_t*) malloc(RSA_size(r)) and then I invoked
4498  > function int32_t i = RSA_private_encrypt(20,a ,sign,r,RSA_NO_PADDING );
4499  The
4500  > returned value i = -1 means that this function failed. However, when I
4501  > invoked int32_t i = RSA_private_encrypt(20,a,sig,r,RSA_PKCS1_PADDING ),
4502  it did
4503  > run smoothly. I'm confused whether it is an error of the library or not
4504  but
4505  > I don't know how to solve this problem.
4506  > Please help me :-<
4507  ... [show rest of quote]
4508 
4509  If you use RSA_NO_PADDING you have to supply a buffer of RSA_size(r) bytes
4510  and
4511  whose value is less than the modulus.
4512 
4513  With RSA_PKCS1_PADDING you can pass up to RSA_size(r) - 11.
4514 
4515  Steve.
4516  --
4517  Dr Stephen N. Henson. OpenSSL project core developer.
4518  Commercial tech support now available see: http://www.openssl.org
4519 
4520 
4521 
4522  Hello,
4523 
4524  I have a problem, I cannot really cover.
4525 
4526  I'm using public key encryption together with RSA_NO_PADDING. The
4527  Key-/Modulus-Size is 128Byte and the message to be encrypted are also
4528  128Byte sized.
4529 
4530  Now my problem:
4531  Using the same (!) binary code (running in a debugging environment or not)
4532  it sometimes work properly, sometimes it failes with the following
4533  message:
4534 
4535  "error:04068084:rsa routines:RSA_EAY_PUBLIC_ENCRYPT:data too large for
4536  modulus"
4537 
4538  Reply:
4539  It is *not* enough that the modulus and message are both 128 bytes. You
4540  need
4541  a stronger condition.
4542 
4543  Suppose your RSA modulus, as a BigNum, is n. Suppose the data you are
4544  trying
4545  to encrypt, as a BigNum, is x. You must ensure that x < n, or you get that
4546  error message. That is one of the reasons to use a padding scheme such as
4547  RSA_PKCS1 padding.
4548 
4549 
4550  knotwork
4551  is this a reason to use larger keys or something? 4096 instead of2048 or
4552  1024?
4553 
4554  4:41
4555  FellowTraveler
4556  larger keys is one solution, and that is why I've been looking at mkcert.c
4557  which, BTW *you* need to look at mkcert.c since there are default values
4558  hardcoded, and I need you to give me a better idea of what you would want
4559  in those places, as a server operator.
4560  First argument of encrypt should have been key.size() and first argument of
4561  decrypt should have been RSA_size(myKey).
4562  Padding scheme should have been used
4563  furthermore, RSA_Sign and RSA_Verify should have been used instead of
4564  RSA_Public_Decrypt and RSA_Private_Encrypt
4565  What you are seeing, your error, is a perfectly normal result of the fact
4566  that the message data being passed in is too large for the modulus of your
4567  key.
4568  .
4569  All of the above fixes need to be investigated and implemented at some
4570  point, and that will almost certainly change the data format inside the key
4571  enough to invalidate all existing signatures
4572  This is a real bug you found, in the crypto.
4573 
4574  4:43
4575  knotwork
4576  zmq got you thinking you could have large messages so you forgot the crypto
4577  had its own limits on message size?
4578 
4579  4:43
4580  FellowTraveler
4581  it's not message size per se
4582  it's message DIGEST size in relation to key modulus
4583  which must be smaller based on a bignum comparison of the two
4584  RSA_Size is supposed to be used in decrypt
4585 
4586  4:44
4587  knotwork
4588  a form of the resync should fix everything, it just needs to run throguh
4589  everything resigning it with new type of signature?
4590 
4591  4:44
4592  FellowTraveler
4593  not that simple
4594  I would have to code some kind of special "convert legacy data" thing into
4595  OT itself
4596  though there might be a stopgap measure now, good enough to keep data until
4597  all the above fixes are made
4598  ok see if this fixes it for you......
4599  knotwork, go into OTLib/OTContract.cpp
4600  Find the first line that begins with status = RSA_public_decrypt
4601 
4602  4:46
4603  knotwork
4604  vanalces would be enough maybe. jsut a way to set balances of all accoutns
4605  to whatever they actually are at the time
4606 
4607  4:46
4608  FellowTraveler
4609  the only other one is commented out, so it's not hard
4610  you will see a hardcoded size: status = RSA_public_decrypt(128,
4611  CHANGE the 128 to this value:
4612  RSA_size(pRsaKey)
4613  for now you can change the entire line to this:
4614  status = RSA_public_decrypt(RSA_size(pRsaKey), static_cast<const
4615  uint8_t*>(binSignature.GetPointer()), pDecrypted, pRsaKey, RSA_NO_PADDING);
4616  Then see if your bug goes away
4617  I will still need to make fixes someday though, even if this works, and
4618  will have to lose or convert data.
4619  4:48
4620  otherwise there could be security issues down the road.
4621 
4622 
4623  TODO SECURITY ^ sign/verify needs revamping!
4624 
4625  UPDATE: Okay I may have it fixed now, though need to test still.
4626 
4627  http://www.bmt-online.org/geekisms/RSA_verify
4628 
4629  Also see: ~/Projects/openssl/demos/sign
4630  */
4631 
4632  if (pRsaKey) RSA_free(pRsaKey);
4633  pRsaKey = nullptr;
4634 
4635  return bReturnValue;
4636 }
4637 
4638 // All the other various versions eventually call this one, where the actual
4639 // work is done.
4641  const OTString& strContractUnsigned, const EVP_PKEY* pkey,
4642  OTSignature& theSignature, const OTString& strHashType,
4643  const OTPasswordData* pPWData) const
4644 {
4645  OT_ASSERT_MSG(nullptr != pkey,
4646  "Null private key sent to OTCrypto_OpenSSL::SignContract.\n");
4647 
4648  const char* szFunc = "OTCrypto_OpenSSL::SignContract";
4649 
4650  class _OTCont_SignCont1
4651  {
4652  private:
4653  const char* m_szFunc;
4654  EVP_MD_CTX& m_ctx;
4655 
4656  public:
4657  _OTCont_SignCont1(const char* param_szFunc, EVP_MD_CTX& param_ctx)
4658  : m_szFunc(param_szFunc)
4659  , m_ctx(param_ctx)
4660  {
4661  OT_ASSERT(nullptr != m_szFunc);
4662 
4663  EVP_MD_CTX_init(&m_ctx);
4664  }
4665  ~_OTCont_SignCont1()
4666  {
4667  if (0 == EVP_MD_CTX_cleanup(&m_ctx))
4668  otErr << m_szFunc << ": Failure in cleanup. (It returned 0.)\n";
4669  }
4670  };
4671 
4672  // Moving this lower...
4673 
4674  // _OTCont_SignCont1 theInstance(szFunc, md_ctx);
4675 
4676  // OTString strDoubleHash;
4677 
4678  // Are we using the special SAMY hash? In which case, we have to actually
4679  // combine two signatures.
4680  const bool bUsesDefaultHashAlgorithm =
4682  EVP_MD* md = nullptr;
4683 
4684  // SAMY hash. (The "default" hash.)
4685  if (bUsesDefaultHashAlgorithm) {
4686  // OTIdentifier hash1, hash2;
4687  //
4688  // hash1.CalculateDigest(strContractUnsigned,
4689  // OTIdentifier::HashAlgorithm1);
4690  // hash2.CalculateDigest(strContractUnsigned,
4691  // OTIdentifier::HashAlgorithm2);
4692  //
4693  // hash1.XOR(hash2);
4694  // hash1.GetString(strDoubleHash);
4695  //
4696  // md = (EVP_MD
4697  // *)OTCrypto_OpenSSL::GetOpenSSLDigestByName(OTIdentifier::HashAlgorithm1);
4698 
4699  return SignContractDefaultHash(strContractUnsigned, pkey, theSignature,
4700  pPWData);
4701  }
4702 
4703  // else
4704  {
4705  md = (EVP_MD*)
4707  strHashType); // todo cast
4708  }
4709 
4710  // If it's not the default hash, then it's just a normal hash.
4711  // Either way then we process it, first by getting the message digest
4712  // pointer for signing.
4713 
4714  if (nullptr == md) {
4715  otErr << szFunc
4716  << ": Unable to decipher Hash algorithm: " << strHashType << "\n";
4717  return false;
4718  }
4719 
4720  // RE: EVP_SignInit() or EVP_MD_CTX_init()...
4721  //
4722  // Since only a copy of the digest context is ever finalized the
4723  // context MUST be cleaned up after use by calling EVP_MD_CTX_cleanup()
4724  // or a memory leak will occur.
4725  //
4726  EVP_MD_CTX md_ctx;
4727 
4728  _OTCont_SignCont1 theInstance(szFunc, md_ctx);
4729 
4730  // Do the signature
4731  // Note: I just changed this to the _ex version (in case I'm debugging later
4732  // and find a problem here.)
4733  //
4734  EVP_SignInit_ex(&md_ctx, md, nullptr);
4735 
4736  // if (bUsesDefaultHashAlgorithm)
4737  // {
4738  // EVP_SignUpdate (&md_ctx, strDoubleHash.Get(),
4739  // strDoubleHash.GetLength());
4740  // }
4741  // else
4742  {
4743  EVP_SignUpdate(&md_ctx, strContractUnsigned.Get(),
4744  strContractUnsigned.GetLength());
4745  }
4746 
4747  uint8_t sig_buf[4096]; // Safe since we pass the size when we use it.
4748 
4749  int32_t sig_len = sizeof(sig_buf);
4750  int32_t err = EVP_SignFinal(&md_ctx, sig_buf, (uint32_t*)&sig_len,
4751  (EVP_PKEY*)pkey); // todo cast
4752 
4753  if (err != 1) {
4754  otErr << szFunc << ": Error signing xml contents.\n";
4755  return false;
4756  }
4757  else {
4758  otLog3 << szFunc << ": Successfully signed xml contents.\n";
4759 
4760  // We put the signature data into the signature object that
4761  // was passed in for that purpose.
4762  OTData tempData;
4763  tempData.Assign(sig_buf, sig_len);
4764  theSignature.SetData(tempData);
4765 
4766  return true;
4767  }
4768 }
4769 
4770 bool OTCrypto_OpenSSL::SignContract(const OTString& strContractUnsigned,
4771  const OTAsymmetricKey& theKey,
4772  OTSignature& theSignature, // output
4773  const OTString& strHashType,
4774  const OTPasswordData* pPWData)
4775 {
4776 
4777  OTAsymmetricKey& theTempKey = const_cast<OTAsymmetricKey&>(theKey);
4778  OTAsymmetricKey_OpenSSL* pTempOpenSSLKey =
4779  dynamic_cast<OTAsymmetricKey_OpenSSL*>(&theTempKey);
4780  OT_ASSERT(nullptr != pTempOpenSSLKey);
4781 
4782  const EVP_PKEY* pkey = pTempOpenSSLKey->dp->GetKey(pPWData);
4783  OT_ASSERT(nullptr != pkey);
4784 
4785  if (false ==
4786  dp->SignContract(strContractUnsigned, pkey, theSignature, strHashType,
4787  pPWData)) {
4788  otErr << "OTCrypto_OpenSSL::SignContract: "
4789  << "SignContract returned false.\n";
4790  return false;
4791  }
4792 
4793  return true;
4794 }
4795 
4796 bool OTCrypto_OpenSSL::VerifySignature(const OTString& strContractToVerify,
4797  const OTAsymmetricKey& theKey,
4798  const OTSignature& theSignature,
4799  const OTString& strHashType,
4800  const OTPasswordData* pPWData) const
4801 {
4802  OTAsymmetricKey& theTempKey = const_cast<OTAsymmetricKey&>(theKey);
4803  OTAsymmetricKey_OpenSSL* pTempOpenSSLKey =
4804  dynamic_cast<OTAsymmetricKey_OpenSSL*>(&theTempKey);
4805  OT_ASSERT(nullptr != pTempOpenSSLKey);
4806 
4807  const EVP_PKEY* pkey = pTempOpenSSLKey->dp->GetKey(pPWData);
4808  OT_ASSERT(nullptr != pkey);
4809 
4810  if (false ==
4811  dp->VerifySignature(strContractToVerify, pkey, theSignature,
4812  strHashType, pPWData)) {
4813  otLog3 << "OTCrypto_OpenSSL::VerifySignature: "
4814  << "VerifySignature returned false.\n";
4815  return false;
4816  }
4817 
4818  return true;
4819 }
4820 
4821 // All the other various versions eventually call this one, where the actual
4822 // work is done.
4824  const OTString& strContractToVerify, const EVP_PKEY* pkey,
4825  const OTSignature& theSignature, const OTString& strHashType,
4826  const OTPasswordData* pPWData) const
4827 {
4828  OT_ASSERT_MSG(strContractToVerify.Exists(),
4829  "OTCrypto_OpenSSL::VerifySignature: ASSERT FAILURE: "
4830  "strContractToVerify.Exists()");
4831  OT_ASSERT_MSG(nullptr != pkey,
4832  "Null pkey in OTCrypto_OpenSSL::VerifySignature.\n");
4833 
4834  const char* szFunc = "OTCrypto_OpenSSL::VerifySignature";
4835 
4836  // Are we using the special SAMY hash? In which case, we have to actually
4837  // combine two hashes.
4838  const bool bUsesDefaultHashAlgorithm =
4840  EVP_MD* md = nullptr;
4841 
4842  if (bUsesDefaultHashAlgorithm) {
4843  // OTIdentifier hash1, hash2;
4844  //
4845  // hash1.CalculateDigest(strContractToVerify,
4846  // OTIdentifier::HashAlgorithm1);
4847  // hash2.CalculateDigest(strContractToVerify,
4848  // OTIdentifier::HashAlgorithm2);
4849  //
4850  // hash1.XOR(hash2);
4851  // hash1.GetString(strDoubleHash);
4852  //
4853  // md = (EVP_MD
4854  // *)OTCrypto_OpenSSL::GetOpenSSLDigestByName(OTIdentifier::HashAlgorithm1);
4855 
4856  return VerifyContractDefaultHash(strContractToVerify, pkey,
4857  theSignature, pPWData);
4858  }
4859 
4860  // else
4861  {
4862  md = (EVP_MD*)
4864  strHashType); // todo cast
4865  }
4866 
4867  if (!md) {
4868  otWarn << szFunc
4869  << ": Unknown message digest algorithm: " << strHashType << "\n";
4870  return false;
4871  }
4872 
4873  OTPayload binSignature;
4874 
4875  // now binSignature contains the base64 decoded binary of the signature.
4876  // Unless the call failed of course...
4877  if (!theSignature.GetData(binSignature)) {
4878  otErr << szFunc << ": Error decoding base64 data for Signature.\n";
4879  return false;
4880  }
4881 
4882  EVP_MD_CTX ctx;
4883  EVP_MD_CTX_init(&ctx);
4884 
4885  EVP_VerifyInit(&ctx, md);
4886 
4887  // Here I'm adding the actual XML portion of the contract (the portion that
4888  // gets signed.)
4889  // Basically we are repeating similarly to the signing process in order to
4890  // verify.
4891 
4892  // if (bUsesDefaultHashAlgorithm)
4893  // {
4894  // EVP_VerifyUpdate(&ctx, strDoubleHash.Get(),
4895  // strDoubleHash.GetLength());
4896  // }
4897  // else
4898  {
4899  EVP_VerifyUpdate(&ctx, strContractToVerify.Get(),
4900  strContractToVerify.GetLength());
4901  }
4902 
4903  // Now we pass in the Signature
4904  // EVP_VerifyFinal() returns 1 for a correct signature,
4905  // 0 for failure and -1 if some other error occurred.
4906  //
4907  int32_t nErr = EVP_VerifyFinal(
4908  &ctx, (const uint8_t*)binSignature.GetPayloadPointer(), // todo cast
4909  (uint32_t)binSignature.GetSize(), (EVP_PKEY*)pkey); // todo cast
4910 
4911  EVP_MD_CTX_cleanup(&ctx);
4912 
4913  // the moment of true. 1 means the signature verified.
4914  if (1 == nErr)
4915  return true;
4916  else
4917  return false;
4918 }
4919 
4920 // Sign the Contract using a private key from a file.
4921 // theSignature will contain the output.
4922 bool OTCrypto_OpenSSL::SignContract(const OTString& strContractUnsigned,
4923  const OTString& strSigHashType,
4924  const std::string& strCertFileContents,
4925  OTSignature& theSignature,
4926  const OTPasswordData* pPWData)
4927 {
4928  OT_ASSERT_MSG(strContractUnsigned.Exists(), "OTCrypto_OpenSSL::"
4929  "SignContract: ASSERT FAILURE: "
4930  "strContractUnsigned.Exists()");
4931  OT_ASSERT_MSG(
4932  strCertFileContents.size() > 2,
4933  "Empty strCertFileContents passed to OTCrypto_OpenSSL::SignContract");
4934 
4935  // Create a new memory buffer on the OpenSSL side
4936  //
4937  OpenSSL_BIO bio =
4938  BIO_new_mem_buf((void*)strCertFileContents.c_str(), -1); // todo cast.
4939  OT_ASSERT(nullptr != bio);
4940 
4941  // TODO security:
4942  /* The old PrivateKey write routines are retained for compatibility.
4943  New applications should write private keys using the
4944  PEM_write_bio_PKCS8PrivateKey() or PEM_write_PKCS8PrivateKey()
4945  routines because they are more secure (they use an iteration count of 2048
4946  whereas the traditional routines use a
4947  count of 1) unless compatibility with older versions of OpenSSL is
4948  important.
4949  NOTE: The PrivateKey read routines can be used in all applications because
4950  they handle all formats transparently.
4951  */
4952  OTPasswordData thePWData("(OTCrypto_OpenSSL::SignContract is trying to "
4953  "read the private key...)");
4954 
4955  if (nullptr == pPWData) pPWData = &thePWData;
4956 
4957  bool bSigned = false;
4958  EVP_PKEY* pkey = PEM_read_bio_PrivateKey(
4959  bio, nullptr, OTAsymmetricKey::GetPasswordCallback(),
4960  const_cast<OTPasswordData*>(pPWData));
4961 
4962  if (nullptr == pkey) {
4963  otErr << "OTCrypto_OpenSSL::SignContract: "
4964  << "Error reading private key from BIO.\n";
4965  }
4966  else {
4967  bSigned = dp->SignContract(strContractUnsigned, pkey, theSignature,
4968  strSigHashType, pPWData);
4969 
4970  EVP_PKEY_free(pkey);
4971  pkey = nullptr;
4972  }
4973 
4974  return bSigned;
4975 }
4976 
4977 // Presumably the Signature passed in here was just loaded as part of this
4978 // contract and is
4979 // somewhere in m_listSignatures. Now it is being verified.
4980 //
4981 bool OTCrypto_OpenSSL::VerifySignature(const OTString& strContractToVerify,
4982  const OTString& strSigHashType,
4983  const std::string& strCertFileContents,
4984  const OTSignature& theSignature,
4985  const OTPasswordData* pPWData) const
4986 {
4987  OT_ASSERT_MSG(strContractToVerify.Exists(),
4988  "OTCrypto_OpenSSL::VerifySignature: ASSERT FAILURE: "
4989  "strContractToVerify.Exists()");
4990  OT_ASSERT_MSG(strCertFileContents.size() > 2,
4991  "Empty strCertFileContents passed to "
4992  "OTCrypto_OpenSSL::VerifySignature");
4993 
4994  const char* szFunc = "OTCrypto_OpenSSL::VerifySignature";
4995 
4996  // Create a new memory buffer on the OpenSSL side
4997  //
4998  OpenSSL_BIO bio =
4999  BIO_new_mem_buf((void*)strCertFileContents.c_str(), -1); // todo cast
5000  OT_ASSERT(nullptr != bio);
5001 
5002  OTPasswordData thePWData("(OTCrypto_OpenSSL::VerifySignature is trying to "
5003  "read the public key...)");
5004 
5005  if (nullptr == pPWData) pPWData = &thePWData;
5006 
5007  X509* x509 =
5008  PEM_read_bio_X509(bio, nullptr, OTAsymmetricKey::GetPasswordCallback(),
5009  const_cast<OTPasswordData*>(pPWData));
5010 
5011  if (nullptr == x509) {
5012  otErr << szFunc << ": Failed reading x509 out of cert file...\n";
5013  return false;
5014  }
5015 
5016  bool bVerifySig = false;
5017  EVP_PKEY* pkey = X509_get_pubkey(x509);
5018 
5019  if (nullptr == pkey) {
5020  otErr << szFunc
5021  << ": Failed reading public key from x509 from certfile...\n";
5022  }
5023  else {
5024  bVerifySig = dp->VerifySignature(strContractToVerify, pkey,
5025  theSignature, strSigHashType, pPWData);
5026 
5027  EVP_PKEY_free(pkey);
5028  pkey = nullptr;
5029  }
5030 
5031  // At some point have to call this.
5032  //
5033  X509_free(x509);
5034  x509 = nullptr;
5035 
5036  return bVerifySig;
5037 }
5038 
5039 // OpenSSL_BIO
5040 
5041 // static
5042 BIO* OpenSSL_BIO::assertBioNotNull(BIO* pBIO)
5043 {
5044  if (nullptr == pBIO) OT_FAIL;
5045  return pBIO;
5046 }
5047 
5049  : m_refBIO(*assertBioNotNull(pBIO))
5050  , bCleanup(true)
5051  , bFreeOnly(false)
5052 {
5053 }
5054 
5056 {
5057  if (bCleanup) {
5058  if (bFreeOnly) {
5059  BIO_free(&m_refBIO);
5060  }
5061  else {
5062  BIO_free_all(&m_refBIO);
5063  }
5064  }
5065 }
5066 
5067 OpenSSL_BIO::operator BIO*() const
5068 {
5069  return (&m_refBIO);
5070 }
5071 
5073 {
5074  bCleanup = false;
5075 }
5076 
5078 {
5079  bFreeOnly = true;
5080 }
5081 
5082 #elif defined(OT_CRYPTO_USING_GPG)
5083 
5084 // Someday }:-)
5085 
5086 #else // Apparently NO crypto engine is defined!
5087 
5088 // Perhaps error out here...
5089 
5090 #endif // if defined (OT_CRYPTO_USING_OPENSSL), elif defined
5091  // (OT_CRYPTO_USING_GPG), else, endif.
5092 
5093 /*
5094 
5095  DERIVING KEYS FROM A PASSWORD
5096 
5097  #include <evp.h>
5098  #include <openssl/rand.h>
5099 
5100  char * passwd = "secret password";
5101 
5102  uint8_t salt[8];
5103 
5104  int32_t iter = 65535;
5105 
5106  uint8_t key[16];
5107 
5108  RAND_bytes(salt, sizeof(salt));
5109 
5110  // From OTPassword.h:
5111  // size_t strnlen(const char* s, size_t max)
5112 
5113  PKCS5_PBKDF2_HMAC_SHA1(passwd, strnlen(passwd, BIGGEST_POSSIBLE_PWD), salt,
5114 sizeof(salt), iter, sizeof(key), key);
5115 
5116  AES_KEY aes_key;
5117  AES_set_encrypt_key(key, 128, aes_key);
5118 
5119 
5120  // perform aes encryption here...
5121 
5122  uint8_t iv[16];
5123  RAND_bytes(iv, sizeof(iv));
5124 
5125 
5126  -----------------------------------------------------------
5127 
5128  DEALING WITH SALT:
5129 
5130  // Note: Salt is generated randomly when the symmetric key is created from the
5131 passphrase.
5132  // Then the salt must be STORED with the symmetric key, so that the passphrase
5133 / salt / encrypted symmetric key
5134  // can later be used to produce a decrypted symmetric key (which should not
5135 stay in memory for int64_t...)
5136  //
5137 
5138 int32_t main()
5139 {
5140  char *pass = "password";
5141  char *salt = "12340000";
5142  int32_t ic = 1;
5143  uint8_t buf[1024];
5144 
5145  ic = 1;
5146  PKCS5_PBKDF2_HMAC_SHA1(pass, strlen(pass), (uint8_t*)salt, strlen(salt), ic,
5147 32+16, buf);
5148  printf("PKCS5_PBKDF2_HMAC_SHA1(\"%s\", \"%s\", %d)=\n", pass, salt, ic);
5149  print_hex(buf, 32+16);
5150 
5151  // NOTE: The above function is used INSTEAD of the one below!
5152 
5153  ic = 1;
5154  EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha1(), (uint8_t*)salt,
5155 (uint8_t*)pass, strlen(pass), ic, buf, buf+32);
5156  printf("EVP_BytesToKey(\"%s\", \"%s\", %d)=\n", pass, salt, ic);
5157  print_hex(buf, 32+16);
5158 
5159  return(0);
5160 }
5161 
5162 
5163 
5164 
5165 
5166  int32_t EVP_BytesToKey(const EVP_CIPHER* type, const EVP_MD* md, const uint8_t*
5167 salt, const uint8_t* data, int32_t datal,
5168  int32_t count, uint8_t* key, uint8_t* iv);
5169 
5170  EVP_BytesToKey() derives a key and IV from various parameters.
5171  type is the cipher to derive the key and IV for.
5172  md is the message digest to use.
5173  The salt paramter is used as a salt in the derivation: it should point to an
5174 8 byte buffer or nullptr if no salt is used.
5175  data is a buffer containing datal bytes which is used to derive the keying
5176 data.
5177  count is the iteration count to use.
5178  The derived key and IV will be written to key and iv respectively.
5179  -----------------------------------------------------------
5180 
5181 
5182 
5183  The initialization vector needs to be known to Alice AND Bob.
5184  And it needs to be transmitted at the time the session key is negotiated.
5185 
5186  So there should probably be a "OTEnvelope" class which stores the IV
5187  as well as the session key, and which can be encrypted with a public key
5188  and decrypted with a private key. The keys can just be passed in or whatever.
5189 
5190 
5191 int32_t PKCS5_PBKDF2_HMAC_SHA1 (const void* password,
5192  size_t password_len, const void* salt,
5193  size_t salt_len,
5194  uint64_t iter,
5195  size_t keylen, void* key)
5196 
5197 
5198  OPENSSL's version:
5199 
5200  int32_t PKCS5_PBKDF2_HMAC_SHA1(const char* pass, int32_t passlen, const
5201 uint8_t* salt, int32_t saltlen,
5202  int32_t iter,
5203  int32_t keylen, uint8_t* out);
5204 
5205  */
5206 
5207 /*
5208 int32_t do_evp_seal(FILE* rsa_pkey_file, FILE* in_file, FILE* out_file)
5209 {
5210  int32_t retval = 0;
5211  RSA *rsa_pkey = nullptr;
5212  EVP_PKEY *pkey = EVP_PKEY_new();
5213  EVP_CIPHER_CTX ctx;
5214  uint8_t buffer[4096];
5215  uint8_t buffer_out[4096 + EVP_MAX_IV_LENGTH];
5216  size_t len;
5217  int32_t len_out;
5218  uint8_t *ek;
5219  int32_t eklen;
5220  uint32_t eklen_n;
5221  uint8_t iv[EVP_MAX_IV_LENGTH];
5222 
5223  if (!PEM_read_RSA_PUBKEY(rsa_pkey_file, &rsa_pkey,
5224 OTAsymmetricKey::GetPasswordCallback(), nullptr))
5225  {
5226  otErr << "Error loading RSA Public Key File.\n";
5227  ERR_print_errors_fp(stderr);
5228  retval = 2;
5229  goto out;
5230  }
5231 
5232  if (!EVP_PKEY_assign_RSA(pkey, rsa_pkey))
5233  {
5234  otErr << "EVP_PKEY_assign_RSA: failed.\n";
5235  retval = 3;
5236  goto out;
5237  }
5238 
5239  EVP_CIPHER_CTX_init(&ctx);
5240  ek = malloc(EVP_PKEY_size(pkey));
5241 
5242  if (!EVP_SealInit(&ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &pkey, 1))
5243  {
5244  otErr << "EVP_SealInit: failed.\n";
5245  retval = 3;
5246  goto out_free;
5247  }
5248 
5249  // First we write out the encrypted key length, then the encrypted key,
5250  / then the iv (the IV length is fixed by the cipher we have chosen).
5251 
5252 
5253  eklen_n = htonl(eklen);
5254  if (fwrite(&eklen_n, sizeof eklen_n, 1, out_file) != 1)
5255  {
5256  perror("output file");
5257  retval = 5;
5258  goto out_free;
5259  }
5260  if (fwrite(ek, eklen, 1, out_file) != 1)
5261  {
5262  perror("output file");
5263  retval = 5;
5264  goto out_free;
5265  }
5266  if (fwrite(iv, EVP_CIPHER_iv_length(EVP_aes_128_cbc()), 1, out_file) != 1)
5267  {
5268  perror("output file");
5269  retval = 5;
5270  goto out_free;
5271  }
5272 
5273  // Now we process the input file and write the encrypted data to the
5274  //output file.
5275 
5276  while ((len = fread(buffer, 1, sizeof buffer, in_file)) > 0)
5277  {
5278  if (!EVP_SealUpdate(&ctx, buffer_out, &len_out, buffer, len))
5279  {
5280  otErr << "EVP_SealUpdate: failed.\n";
5281  retval = 3;
5282  goto out_free;
5283  }
5284 
5285  if (fwrite(buffer_out, len_out, 1, out_file) != 1)
5286  {
5287  perror("output file");
5288  retval = 5;
5289  goto out_free;
5290  }
5291  }
5292 
5293  if (ferror(in_file))
5294  {
5295  perror("input file");
5296  retval = 4;
5297  goto out_free;
5298  }
5299 
5300  if (!EVP_SealFinal(&ctx, buffer_out, &len_out))
5301  {
5302  otErr << "EVP_SealFinal: failed.\n";
5303  retval = 3;
5304  goto out_free;
5305  }
5306 
5307  if (fwrite(buffer_out, len_out, 1, out_file) != 1)
5308  {
5309  perror("output file");
5310  retval = 5;
5311  goto out_free;
5312  }
5313 
5314 out_free:
5315  EVP_PKEY_free(pkey);
5316  free(ek);
5317 
5318 out:
5319  return retval;
5320 }
5321 
5322 int32_t main(int32_t argc, char *argv[])
5323 {
5324  FILE *rsa_pkey_file;
5325  int32_t rv;
5326 
5327  if (argc < 2)
5328  {
5329  otOut << "Usage: %s <PEM RSA Public Key File>\n", argv[0]);
5330  exit(1);
5331  }
5332 
5333  rsa_pkey_file = fopen(argv[1], "rb");
5334  if (!rsa_pkey_file)
5335  {
5336  perror(argv[1]);
5337  otErr << "Error loading PEM RSA Public Key File.\n";
5338  exit(2);
5339  }
5340 
5341  rv = do_evp_seal(rsa_pkey_file, stdin, stdout);
5342 
5343  fclose(rsa_pkey_file);
5344  return rv;
5345 }
5346 */
5347 
5348 } // namespace opentxs
EXPORT const uint8_t * getMemory_uint8() const
Definition: OTPassword.cpp:582
static EXPORT OTCrypto * It()
Definition: OTCrypto.cpp:630
virtual void Cleanup_Override() const
Definition: OTCrypto.cpp:704
OTLOG_IMPORT OTLogStream otLog4
virtual bool CalculateDigest(const OTString &strInput, const OTString &strHashAlgorithm, OTIdentifier &theOutput) const
Definition: OTCrypto.cpp:1659
static EXPORT uint32_t SymmetricIvSize()
Definition: OTCrypto.cpp:391
char * ot_openssl_base64_encode(const uint8_t *input, int32_t in_len, int32_t bLineBreaks)
Definition: OTCrypto.cpp:1251
#define OT_DEFAULT_DIGEST_1_SIZE
Definition: OTCrypto.cpp:266
#define OT_KEY_SYMMETRIC_IV_SIZE
Definition: OTCrypto.cpp:273
EXPORT uint32_t getMemorySize() const
Definition: OTPassword.cpp:619
#define OT_KEY_DIGEST_2_SIZE
Definition: OTCrypto.cpp:278
EXPORT void GetIdentifier(OTIdentifier &theIdentifier) const
static EXPORT uint32_t IterationCount()
Definition: OTCrypto.cpp:375
#define OT_DEFAULT_SYMMETRIC_KEY_SIZE_MAX
Definition: OTCrypto.cpp:261
#define OT_DEFAULT_SYMMETRIC_BUFFER_SIZE
Definition: OTCrypto.cpp:263
EXPORT bool GetPasswordFromConsole(OTPassword &theOutput, bool bRepeat=false) const
Definition: OTCrypto.cpp:587
virtual void SetIDFromBase62String(const OTString &strInput, OTIdentifier &theOutput) const
Definition: OTCrypto.cpp:1351
virtual bool Decrypt(const OTPassword &theRawSymmetricKey, const char *szInput, uint32_t lInputLength, const OTPayload &theIV, OTCrypto_Decrypt_Output theDecryptedOutput) const
Definition: OTCrypto.cpp:2318
virtual bool SignContract(const OTString &strContractUnsigned, const OTAsymmetricKey &theKey, OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr)
Definition: OTCrypto.cpp:4770
static EXPORT const OTString HashAlgorithm2
#define OT_KEY_SYMMETRIC_SALT_SIZE
Definition: OTCrypto.cpp:270
#define OT_KEY_SYMMETRIC_KEY_SIZE_MAX
Definition: OTCrypto.cpp:272
virtual void Init_Override() const
Definition: OTCrypto.cpp:1814
virtual OTPassword * DeriveNewKey(const OTPassword &userPassword, const OTPayload &dataSalt, uint32_t uIterations, OTPayload &dataCheckHash) const
Definition: OTCrypto.cpp:1524
#define OT_DEFAULT_PUBLIC_KEYSIZE_MAX
Definition: OTCrypto.cpp:265
EXPORT void zeroMemory()
Definition: OTPassword.cpp:281
EXPORT bool Concatenate(const void *pAppendData, uint32_t lAppendSize) const
Definition: OTCrypto.cpp:855
EXPORT int32_t addMemory(const void *append, uint32_t size)
Definition: OTPassword.cpp:944
OTLOG_IMPORT OTLogStream otOut
virtual OTPassword * InstantiateBinarySecret() const
Definition: OTCrypto.cpp:1756
EXPORT bool isPassword() const
Definition: OTPassword.cpp:537
#define OT_DEFAULT_SYMMETRIC_SALT_SIZE
Definition: OTCrypto.cpp:259
OTLOG_IMPORT OTLogStream otLog3
virtual bool RandomizeMemory(uint8_t *szDestination, uint32_t nNewSize) const
Definition: OTCrypto.cpp:1457
EXPORT const void * getMemory() const
Definition: OTPassword.cpp:577
EXPORT uint32_t GetLength() const
Definition: OTString.cpp:1040
#define OT_DEFAULT_SYMMETRIC_KEY_SIZE
Definition: OTCrypto.cpp:260
EXPORT int32_t setPassword(const char *input, int32_t size)
Definition: OTPassword.cpp:665
bool SignContractDefaultHash(const OTString &strContractUnsigned, const EVP_PKEY *pkey, OTSignature &theSignature, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:3738
static EXPORT uint32_t SymmetricSaltSize()
Definition: OTCrypto.cpp:379
void thread_setup() const
Definition: OTCrypto.cpp:1773
static EXPORT uint32_t SymmetricKeySizeMax()
Definition: OTCrypto.cpp:387
#define OT_DEFAULT_DIGEST_2_SIZE
Definition: OTCrypto.cpp:267
EXPORT bool GetPasswordFromConsoleLowLevel(OTPassword &theOutput, const char *szPrompt) const
Definition: OTCrypto.cpp:488
EXPORT bool Exists() const
Definition: OTString.cpp:1035
static EXPORT uint32_t Digest1Size()
Definition: OTCrypto.cpp:407
EXPORT bool CalculateDigestInternal(const OTString &strInput, const OTString &strHashAlgorithm)
virtual uint8_t * Base64Decode(const char *input, size_t *out_len, bool bLineBreaks) const
Definition: OTCrypto.cpp:1337
#define OT_DEFAULT_PUBLIC_KEYSIZE
Definition: OTCrypto.cpp:264
EXPORT bool Compare(const char *compare) const
Definition: OTString.cpp:1102
virtual bool Encrypt(const OTPassword &theRawSymmetricKey, const char *szInput, uint32_t lInputLength, const OTPayload &theIV, OTPayload &theEncryptedOutput) const
Definition: OTCrypto.cpp:2195
virtual void Cleanup_Override() const
Definition: OTCrypto.cpp:2122
static size_t safe_strlen(const char *s, size_t max)
Definition: OTString.cpp:388
static std::mutex * s_arrayMutex
Definition: OTCrypto.hpp:419
EXPORT void Set(const char *data, uint32_t enforcedMaxLength=0)
Definition: OTString.cpp:1055
static EXPORT uint32_t SymmetricBufferSize()
Definition: OTCrypto.cpp:395
EXPORT void Assign(const OTData &source)
Definition: OTData.cpp:275
bool IsBase62(const std::string &str) const
Definition: OTCrypto.cpp:427
#define OT_KEY_PUBLIC_KEYSIZE
Definition: OTCrypto.cpp:275
#define OT_DEFAULT_SYMMETRIC_IV_SIZE
Definition: OTCrypto.cpp:262
#define OT_DEFAULT_ITERATION_COUNT
Definition: OTCrypto.cpp:258
const OTAsymmetricKey & GetPrivateEncrKey() const
#define OT_ASSERT(x)
Definition: Assert.hpp:150
virtual bool Base64Encode(const OTData &theInput, OTString &strOutput, bool bLineBreaks=true) const
Definition: OTCrypto.cpp:710
static EXPORT const OTString DefaultHashAlgorithm
bool VerifySignature(const OTString &strContractToVerify, const EVP_PKEY *pkey, const OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:4823
#define OT_ASSERT_MSG(x, s)
Definition: Assert.hpp:155
void SetSize(uint32_t size)
Definition: OTData.cpp:386
void reset()
Definition: OTData.hpp:186
EXPORT void SetPayloadSize(uint32_t lNewSize)
Definition: OTPayload.cpp:313
OTLOG_IMPORT OTLogStream otInfo
#define OT_KEY_ITERATION_COUNT
Definition: OTCrypto.cpp:269
EXPORT uint32_t getPasswordSize() const
Definition: OTPassword.cpp:613
EXPORT bool GetData(OTData &theData, bool bLineBreaks=true) const
EXPORT void swap(OTCrypto_Decrypt_Output &other)
Definition: OTCrypto.cpp:813
EXPORT void setFreeOnly()
Definition: OTCrypto.cpp:5077
std::multimap< std::string, OTAsymmetricKey * > mapOfAsymmetricKeys
Definition: OTCrypto.hpp:155
OTCrypto_OpenSSLdp * dp
Definition: OTCrypto.hpp:415
#define OT_FAIL
Definition: Assert.hpp:139
virtual bool Seal(mapOfAsymmetricKeys &RecipPubKeys, const OTString &theInput, OTData &dataOutput) const
Definition: OTCrypto.cpp:2454
#define OT_KEY_DIGEST_1_SIZE
Definition: OTCrypto.cpp:277
#define OT_FAIL_MSG(s)
Definition: Assert.hpp:144
static EXPORT uint32_t PublicKeysizeMax()
Definition: OTCrypto.cpp:403
OTLOG_IMPORT OTLogStream otWarn
EXPORT void release()
Definition: OTCrypto.cpp:5072
EXPORT const char * Get() const
Definition: OTString.cpp:1045
uint8_t * ot_openssl_base64_decode(const char *input, size_t *out_len, int32_t bLineBreaks)
Definition: OTCrypto.cpp:1291
EXPORT void Init() const
Definition: OTCrypto.cpp:646
EXPORT const void * GetPayloadPointer() const
Definition: OTPayload.cpp:318
OTLOG_IMPORT OTLogStream otErr
bool VerifyContractDefaultHash(const OTString &strContractToVerify, const EVP_PKEY *pkey, const OTSignature &theSignature, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:4008
EXPORT OTCrypto_Decrypt_Output & operator=(OTCrypto_Decrypt_Output other)
Definition: OTCrypto.cpp:826
#define OT_KEY_SYMMETRIC_BUFFER_SIZE
Definition: OTCrypto.cpp:274
void thread_cleanup() const
Definition: OTCrypto.cpp:1803
const void * GetPointer() const
Definition: OTData.hpp:162
EXPORT const uint8_t * getPassword_uint8() const
Definition: OTPassword.cpp:554
static EXPORT uint32_t Digest2Size()
Definition: OTCrypto.cpp:411
#define _PASSWORD_LEN
Definition: OTCrypto.cpp:485
OTAsymmetricKey_OpenSSLPrivdp * dp
EXPORT void Release_Envelope_Decrypt_Output() const
Definition: OTCrypto.cpp:848
static EXPORT uint32_t PublicKeysize()
Definition: OTCrypto.cpp:399
static EXPORT OT_OPENSSL_CALLBACK * GetPasswordCallback()
EXPORT void * getMemoryWritable()
Definition: OTPassword.cpp:589
EXPORT int32_t setPassword_uint8(const uint8_t *input, uint32_t size)
Definition: OTPassword.cpp:674
EXPORT void Cleanup() const
Definition: OTCrypto.cpp:678
#define OT_KEY_SYMMETRIC_KEY_SIZE
Definition: OTCrypto.cpp:271
#define OT_KEY_PUBLIC_KEYSIZE_MAX
Definition: OTCrypto.cpp:276
virtual bool Base64Decode(const OTString &strInput, OTData &theOutput, bool bLineBreaks=true) const
Definition: OTCrypto.cpp:740
virtual void SetBase62StringFromID(const OTIdentifier &theInput, OTString &strOutput) const
Definition: OTCrypto.cpp:1422
static const EVP_MD * GetOpenSSLDigestByName(const OTString &theName)
Definition: OTCrypto.cpp:1636
EXPORT uint32_t OTfread(uint8_t *data, uint32_t size)
Definition: OTData.cpp:214
EXPORT bool SetData(const OTData &theData, bool bLineBreaks=true)
virtual void Init_Override() const
Definition: OTCrypto.cpp:697
EXPORT bool IsEmpty() const
Definition: OTData.cpp:291
bool SignContract(const OTString &strContractUnsigned, const EVP_PKEY *pkey, OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:4640
virtual char * Base64Encode(const uint8_t *input, int32_t in_len, bool bLineBreaks) const
Definition: OTCrypto.cpp:1330
virtual bool VerifySignature(const OTString &strContractToVerify, const OTAsymmetricKey &theKey, const OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:4796
virtual bool Open(OTData &dataInput, const OTPseudonym &theRecipient, OTString &theOutput, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:3007
EXPORT bool Compare(OTPassword &rhs) const
Definition: OTPassword.cpp:637
virtual EXPORT void Release()
Definition: OTData.cpp:257
void ot_openssl_locking_callback(int32_t mode, int32_t type, char *file, int32_t line)
EXPORT bool MemSet(const char *mem, uint32_t size)
Definition: OTString.cpp:967
virtual ~OTCrypto()
Definition: OTCrypto.cpp:423
unsigned int64_t ot_openssl_thread_id(void)
Definition: OTCrypto.cpp:1103
virtual OTPassword * DeriveKey(const OTPassword &userPassword, const OTPayload &dataSalt, uint32_t uIterations, const OTPayload &dataCheckHash=OTPayload()) const
Definition: OTCrypto.cpp:1514
EXPORT void Concatenate(const void *data, uint32_t size)
Definition: OTData.cpp:333
static EXPORT uint32_t SymmetricKeySize()
Definition: OTCrypto.cpp:383
virtual EXPORT void Release()
Definition: OTString.cpp:765
EXPORT OpenSSL_BIO(BIO *pBIO)
Definition: OTCrypto.cpp:5048
uint32_t GetSize() const
Definition: OTData.hpp:174
static EXPORT const OTString HashAlgorithm1
static EXPORT const OTString & GlobalConfigFile()
Definition: OTPaths.cpp:286
OTLOG_IMPORT OTLogStream otLog5