Open-Transactions  0.93.0-ge03d287
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
opentxs::OTCrypto_OpenSSL Class Reference

#include <OTCrypto.hpp>

Inheritance diagram for opentxs::OTCrypto_OpenSSL:
Collaboration diagram for opentxs::OTCrypto_OpenSSL:

Classes

class  OTCrypto_OpenSSLdp
 

Public Member Functions

virtual OTPasswordInstantiateBinarySecret () const
 
virtual bool RandomizeMemory (uint8_t *szDestination, uint32_t nNewSize) const
 
virtual bool CalculateDigest (const OTString &strInput, const OTString &strHashAlgorithm, OTIdentifier &theOutput) const
 
virtual bool CalculateDigest (const OTData &dataInput, const OTString &strHashAlgorithm, OTIdentifier &theOutput) const
 
virtual void SetIDFromBase62String (const OTString &strInput, OTIdentifier &theOutput) const
 
virtual void SetBase62StringFromID (const OTIdentifier &theInput, OTString &strOutput) const
 
virtual char * Base64Encode (const uint8_t *input, int32_t in_len, bool bLineBreaks) const
 
virtual uint8_t * Base64Decode (const char *input, size_t *out_len, bool bLineBreaks) const
 
virtual OTPasswordDeriveKey (const OTPassword &userPassword, const OTPayload &dataSalt, uint32_t uIterations, const OTPayload &dataCheckHash=OTPayload()) const
 
virtual OTPasswordDeriveNewKey (const OTPassword &userPassword, const OTPayload &dataSalt, uint32_t uIterations, OTPayload &dataCheckHash) const
 
virtual bool Encrypt (const OTPassword &theRawSymmetricKey, const char *szInput, uint32_t lInputLength, const OTPayload &theIV, OTPayload &theEncryptedOutput) const
 
virtual bool Decrypt (const OTPassword &theRawSymmetricKey, const char *szInput, uint32_t lInputLength, const OTPayload &theIV, OTCrypto_Decrypt_Output theDecryptedOutput) const
 
virtual bool Seal (mapOfAsymmetricKeys &RecipPubKeys, const OTString &theInput, OTData &dataOutput) const
 
virtual bool Open (OTData &dataInput, const OTPseudonym &theRecipient, OTString &theOutput, const OTPasswordData *pPWData=nullptr) const
 
virtual bool SignContract (const OTString &strContractUnsigned, const OTAsymmetricKey &theKey, OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr)
 
virtual bool VerifySignature (const OTString &strContractToVerify, const OTAsymmetricKey &theKey, const OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr) const
 
virtual bool SignContract (const OTString &strContractUnsigned, const OTString &strSigHashType, const std::string &strCertFileContents, OTSignature &theSignature, const OTPasswordData *pPWData=nullptr)
 
virtual bool VerifySignature (const OTString &strContractToVerify, const OTString &strSigHashType, const std::string &strCertFileContents, const OTSignature &theSignature, const OTPasswordData *pPWData=nullptr) const
 
void thread_setup () const
 
void thread_cleanup () const
 
virtual ~OTCrypto_OpenSSL ()
 
- Public Member Functions inherited from opentxs::OTCrypto
virtual ~OTCrypto ()
 
EXPORT bool GetPasswordFromConsole (OTPassword &theOutput, bool bRepeat=false) const
 
EXPORT bool GetPasswordFromConsoleLowLevel (OTPassword &theOutput, const char *szPrompt) const
 
bool IsBase62 (const std::string &str) const
 
virtual bool Base64Encode (const OTData &theInput, OTString &strOutput, bool bLineBreaks=true) const
 
virtual bool Base64Decode (const OTString &strInput, OTData &theOutput, bool bLineBreaks=true) const
 
EXPORT void Init () const
 
EXPORT void Cleanup () const
 

Static Public Attributes

static std::mutex * s_arrayMutex = nullptr
 

Protected Member Functions

 OTCrypto_OpenSSL ()
 
virtual void Init_Override () const
 
virtual void Cleanup_Override () const
 
- Protected Member Functions inherited from opentxs::OTCrypto
 OTCrypto ()
 

Protected Attributes

OTCrypto_OpenSSLdpdp
 

Friends

class OTCrypto
 

Additional Inherited Members

- Static Public Member Functions inherited from opentxs::OTCrypto
static EXPORT OTCryptoIt ()
 

Detailed Description

Definition at line 406 of file OTCrypto.hpp.

Constructor & Destructor Documentation

opentxs::OTCrypto_OpenSSL::OTCrypto_OpenSSL ( )
protected

Definition at line 932 of file OTCrypto.cpp.

933  : OTCrypto()
934  , dp(nullptr)
935 {
936 }
OTCrypto_OpenSSLdp * dp
Definition: OTCrypto.hpp:415
opentxs::OTCrypto_OpenSSL::~OTCrypto_OpenSSL ( )
virtual

Definition at line 938 of file OTCrypto.cpp.

939 {
940 }

Member Function Documentation

uint8_t * opentxs::OTCrypto_OpenSSL::Base64Decode ( const char *  input,
size_t *  out_len,
bool  bLineBreaks 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1337 of file OTCrypto.cpp.

1339 {
1340  return ot_openssl_base64_decode(input, out_len, (bLineBreaks ? 1 : 0));
1341 }
uint8_t * ot_openssl_base64_decode(const char *input, size_t *out_len, int32_t bLineBreaks)
Definition: OTCrypto.cpp:1291
char * opentxs::OTCrypto_OpenSSL::Base64Encode ( const uint8_t *  input,
int32_t  in_len,
bool  bLineBreaks 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1330 of file OTCrypto.cpp.

1332 {
1333  return ot_openssl_base64_encode(input, in_len, (bLineBreaks ? 1 : 0));
1334 }
char * ot_openssl_base64_encode(const uint8_t *input, int32_t in_len, int32_t bLineBreaks)
Definition: OTCrypto.cpp:1251
bool opentxs::OTCrypto_OpenSSL::CalculateDigest ( const OTString strInput,
const OTString strHashAlgorithm,
OTIdentifier theOutput 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1659 of file OTCrypto.cpp.

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 }
OTLOG_IMPORT OTLogStream otErr
static const EVP_MD * GetOpenSSLDigestByName(const OTString &theName)
Definition: OTCrypto.cpp:1636
bool opentxs::OTCrypto_OpenSSL::CalculateDigest ( const OTData dataInput,
const OTString strHashAlgorithm,
OTIdentifier theOutput 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1701 of file OTCrypto.cpp.

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 }
OTLOG_IMPORT OTLogStream otErr
static const EVP_MD * GetOpenSSLDigestByName(const OTString &theName)
Definition: OTCrypto.cpp:1636
void opentxs::OTCrypto_OpenSSL::Cleanup_Override ( ) const
protectedvirtual

Reimplemented from opentxs::OTCrypto.

Definition at line 2122 of file OTCrypto.cpp.

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 }
OTLOG_IMPORT OTLogStream otLog4
void thread_cleanup() const
Definition: OTCrypto.cpp:1803
bool opentxs::OTCrypto_OpenSSL::Decrypt ( const OTPassword theRawSymmetricKey,
const char *  szInput,
uint32_t  lInputLength,
const OTPayload theIV,
OTCrypto_Decrypt_Output  theDecryptedOutput 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 2318 of file OTCrypto.cpp.

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 }
static EXPORT uint32_t SymmetricIvSize()
Definition: OTCrypto.cpp:391
static EXPORT uint32_t SymmetricBufferSize()
Definition: OTCrypto.cpp:395
#define OT_ASSERT(x)
Definition: Assert.hpp:150
OTLOG_IMPORT OTLogStream otErr
static EXPORT uint32_t SymmetricKeySize()
Definition: OTCrypto.cpp:383
OTPassword * opentxs::OTCrypto_OpenSSL::DeriveKey ( const OTPassword userPassword,
const OTPayload dataSalt,
uint32_t  uIterations,
const OTPayload dataCheckHash = OTPayload() 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1514 of file OTCrypto.cpp.

1518 {
1519  OTPayload tempPayload = dataCheckHash;
1520  return OTCrypto_OpenSSL::DeriveNewKey(userPassword, dataSalt, uIterations,
1521  tempPayload);
1522 }
virtual OTPassword * DeriveNewKey(const OTPassword &userPassword, const OTPayload &dataSalt, uint32_t uIterations, OTPayload &dataCheckHash) const
Definition: OTCrypto.cpp:1524
OTPassword * opentxs::OTCrypto_OpenSSL::DeriveNewKey ( const OTPassword userPassword,
const OTPayload dataSalt,
uint32_t  uIterations,
OTPayload dataCheckHash 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1524 of file OTCrypto.cpp.

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;
1567  tmpHashCheck.SetPayloadSize(OTCryptoConfig::SymmetricKeySize());
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 }
virtual OTPassword * InstantiateBinarySecret() const
Definition: OTCrypto.cpp:1756
#define OT_ASSERT(x)
Definition: Assert.hpp:150
OTLOG_IMPORT OTLogStream otInfo
static EXPORT uint32_t SymmetricKeySize()
Definition: OTCrypto.cpp:383
bool opentxs::OTCrypto_OpenSSL::Encrypt ( const OTPassword theRawSymmetricKey,
const char *  szInput,
uint32_t  lInputLength,
const OTPayload theIV,
OTPayload theEncryptedOutput 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 2195 of file OTCrypto.cpp.

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 }
static EXPORT uint32_t SymmetricIvSize()
Definition: OTCrypto.cpp:391
static EXPORT uint32_t SymmetricBufferSize()
Definition: OTCrypto.cpp:395
#define OT_ASSERT(x)
Definition: Assert.hpp:150
OTLOG_IMPORT OTLogStream otErr
static EXPORT uint32_t SymmetricKeySize()
Definition: OTCrypto.cpp:383
void opentxs::OTCrypto_OpenSSL::Init_Override ( ) const
protectedvirtual

Reimplemented from opentxs::OTCrypto.

Definition at line 1814 of file OTCrypto.cpp.

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 }
void thread_setup() const
Definition: OTCrypto.cpp:1773
#define OT_FAIL_MSG(s)
Definition: Assert.hpp:144
OTLOG_IMPORT OTLogStream otWarn
OTLOG_IMPORT OTLogStream otErr
OTPassword * opentxs::OTCrypto_OpenSSL::InstantiateBinarySecret ( ) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1756 of file OTCrypto.cpp.

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 }
#define OT_ASSERT_MSG(x, s)
Definition: Assert.hpp:155
static EXPORT uint32_t SymmetricKeySize()
Definition: OTCrypto.cpp:383
bool opentxs::OTCrypto_OpenSSL::Open ( OTData dataInput,
const OTPseudonym theRecipient,
OTString theOutput,
const OTPasswordData pPWData = nullptr 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 3007 of file OTCrypto.cpp.

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 }
static EXPORT uint32_t SymmetricIvSize()
Definition: OTCrypto.cpp:391
OTLOG_IMPORT OTLogStream otOut
#define OT_ASSERT(x)
Definition: Assert.hpp:150
OTLOG_IMPORT OTLogStream otErr
OTLOG_IMPORT OTLogStream otLog5
bool opentxs::OTCrypto_OpenSSL::RandomizeMemory ( uint8_t *  szDestination,
uint32_t  nNewSize 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1457 of file OTCrypto.cpp.

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 }
#define OT_ASSERT(x)
Definition: Assert.hpp:150
OTLOG_IMPORT OTLogStream otErr
bool opentxs::OTCrypto_OpenSSL::Seal ( mapOfAsymmetricKeys RecipPubKeys,
const OTString theInput,
OTData dataOutput 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 2454 of file OTCrypto.cpp.

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 }
#define OT_ASSERT(x)
Definition: Assert.hpp:150
#define OT_ASSERT_MSG(x, s)
Definition: Assert.hpp:155
std::multimap< std::string, OTAsymmetricKey * > mapOfAsymmetricKeys
Definition: OTCrypto.hpp:155
#define OT_FAIL
Definition: Assert.hpp:139
OTLOG_IMPORT OTLogStream otErr
OTLOG_IMPORT OTLogStream otLog5
void opentxs::OTCrypto_OpenSSL::SetBase62StringFromID ( const OTIdentifier theInput,
OTString strOutput 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1422 of file OTCrypto.cpp.

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 }
#define OT_ASSERT(x)
Definition: Assert.hpp:150
void opentxs::OTCrypto_OpenSSL::SetIDFromBase62String ( const OTString strInput,
OTIdentifier theOutput 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 1351 of file OTCrypto.cpp.

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 }
bool IsBase62(const std::string &str) const
Definition: OTCrypto.cpp:427
#define OT_ASSERT(x)
Definition: Assert.hpp:150
bool opentxs::OTCrypto_OpenSSL::SignContract ( const OTString strContractUnsigned,
const OTAsymmetricKey theKey,
OTSignature theSignature,
const OTString strHashType,
const OTPasswordData pPWData = nullptr 
)
virtual

Implements opentxs::OTCrypto.

Definition at line 4770 of file OTCrypto.cpp.

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 }
#define OT_ASSERT(x)
Definition: Assert.hpp:150
OTCrypto_OpenSSLdp * dp
Definition: OTCrypto.hpp:415
OTLOG_IMPORT OTLogStream otErr
bool SignContract(const OTString &strContractUnsigned, const EVP_PKEY *pkey, OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:4640
bool opentxs::OTCrypto_OpenSSL::SignContract ( const OTString strContractUnsigned,
const OTString strSigHashType,
const std::string &  strCertFileContents,
OTSignature theSignature,
const OTPasswordData pPWData = nullptr 
)
virtual

Implements opentxs::OTCrypto.

Definition at line 4922 of file OTCrypto.cpp.

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 }
#define OT_ASSERT(x)
Definition: Assert.hpp:150
#define OT_ASSERT_MSG(x, s)
Definition: Assert.hpp:155
OTCrypto_OpenSSLdp * dp
Definition: OTCrypto.hpp:415
OTLOG_IMPORT OTLogStream otErr
static EXPORT OT_OPENSSL_CALLBACK * GetPasswordCallback()
bool SignContract(const OTString &strContractUnsigned, const EVP_PKEY *pkey, OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:4640
void opentxs::OTCrypto_OpenSSL::thread_cleanup ( ) const

Definition at line 1803 of file OTCrypto.cpp.

1804 {
1805  CRYPTO_set_locking_callback(nullptr);
1806 
1807  if (nullptr != OTCrypto_OpenSSL::s_arrayMutex) {
1809  }
1810 
1812 }
static std::mutex * s_arrayMutex
Definition: OTCrypto.hpp:419
void opentxs::OTCrypto_OpenSSL::thread_setup ( ) const

Definition at line 1773 of file OTCrypto.cpp.

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 }
static std::mutex * s_arrayMutex
Definition: OTCrypto.hpp:419
void ot_openssl_locking_callback(int32_t mode, int32_t type, char *file, int32_t line)
unsigned int64_t ot_openssl_thread_id(void)
Definition: OTCrypto.cpp:1103
bool opentxs::OTCrypto_OpenSSL::VerifySignature ( const OTString strContractToVerify,
const OTAsymmetricKey theKey,
const OTSignature theSignature,
const OTString strHashType,
const OTPasswordData pPWData = nullptr 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 4796 of file OTCrypto.cpp.

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 }
OTLOG_IMPORT OTLogStream otLog3
#define OT_ASSERT(x)
Definition: Assert.hpp:150
bool VerifySignature(const OTString &strContractToVerify, const EVP_PKEY *pkey, const OTSignature &theSignature, const OTString &strHashType, const OTPasswordData *pPWData=nullptr) const
Definition: OTCrypto.cpp:4823
OTCrypto_OpenSSLdp * dp
Definition: OTCrypto.hpp:415
bool opentxs::OTCrypto_OpenSSL::VerifySignature ( const OTString strContractToVerify,
const OTString strSigHashType,
const std::string &  strCertFileContents,
const OTSignature theSignature,
const OTPasswordData pPWData = nullptr 
) const
virtual

Implements opentxs::OTCrypto.

Definition at line 4981 of file OTCrypto.cpp.

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 }
#define OT_ASSERT(x)
Definition: Assert.hpp:150
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
OTCrypto_OpenSSLdp * dp
Definition: OTCrypto.hpp:415
OTLOG_IMPORT OTLogStream otErr
static EXPORT OT_OPENSSL_CALLBACK * GetPasswordCallback()

Friends And Related Function Documentation

friend class OTCrypto
friend

Definition at line 408 of file OTCrypto.hpp.

Member Data Documentation

OTCrypto_OpenSSLdp* opentxs::OTCrypto_OpenSSL::dp
protected

Definition at line 415 of file OTCrypto.hpp.

std::mutex * opentxs::OTCrypto_OpenSSL::s_arrayMutex = nullptr
static

Definition at line 419 of file OTCrypto.hpp.


The documentation for this class was generated from the following files: