std::string HDSeed::SaveSeed( const OTPassword& words, const OTPassword& passphrase) const { OT_ASSERT(words.isPassword() && passphrase.isPassword()); auto seed = aes_.InstantiateBinarySecretSP(); bip39_.WordsToSeed(words, *seed, passphrase); OT_ASSERT(1 < seed->getMemorySize()); // the fingerprint is used as the identifier of the seed for indexing // purposes. Always use the secp256k1 version for this. auto fingerprint = bip32_.SeedToFingerprint(EcdsaCurve::SECP256K1, *seed); const OTPasswordData reason("Encrypting a new BIP39 seed"); auto key = symmetric_.Key(reason, DEFAULT_ENCRYPTION_MODE); OT_ASSERT(key.get()); proto::Seed serialized; serialized.set_version(2); serialized.set_index(0); auto& encryptedWords = *serialized.mutable_words(); auto& encryptedPassphrase = *serialized.mutable_passphrase(); serialized.set_fingerprint(fingerprint); auto empty = Data::Factory(); const bool haveWords = key->Encrypt(words, empty, reason, encryptedWords); if (false == haveWords) { otErr << OT_METHOD << __FUNCTION__ << ": Failed to encrypt seed." << std::endl; return ""; } bool havePassphrase = key->Encrypt(passphrase, empty, reason, encryptedPassphrase, false); if (!havePassphrase) { otErr << OT_METHOD << __FUNCTION__ << ": Failed to encrypt passphrase." << std::endl; return ""; } const bool stored = storage_.Store(serialized, fingerprint); if (!stored) { otErr << OT_METHOD << __FUNCTION__ << ": Failed to store seed." << std::endl; return ""; } return fingerprint; }
bool HDSeed::SeedToData( const OTPassword& words, const OTPassword& passphrase, OTPassword& output) const { OT_ASSERT(words.isPassword()); OT_ASSERT(passphrase.isPassword()); bip39_.WordsToSeed(words, output, passphrase); return true; }
bool HDSeed::DecryptSeed( const proto::Seed& seed, OTPassword& words, OTPassword& phrase) const { if (!proto::Validate(seed, VERBOSE)) { return false; } const auto& cwords = seed.words(); const auto& cphrase = seed.passphrase(); const OTPasswordData reason("Decrypting a new BIP39 seed"); auto key = symmetric_.Key(cwords.key(), cwords.mode()); OT_ASSERT(key.get()); OT_ASSERT(words.isPassword()); const bool haveWords = key->Decrypt(seed.words(), reason, words); if (!haveWords) { otErr << OT_METHOD << __FUNCTION__ << ": Failed to decrypt words." << std::endl; return false; } OT_ASSERT(phrase.isPassword()); if (seed.has_passphrase()) { const bool havePassphrase = key->Decrypt(cphrase, reason, phrase); if (!havePassphrase) { otErr << OT_METHOD << __FUNCTION__ << ": Failed to decrypt passphrase." << std::endl; return false; } } return true; }
bool OTPassword::Compare(OTPassword & rhs) const { OT_ASSERT(this->isPassword() || this->isMemory()); OT_ASSERT(rhs.isPassword() || rhs.isMemory()); if (this->isPassword() && !rhs.isPassword()) return false; if (this->isMemory() && !rhs.isMemory()) return false; const uint32_t nThisSize = this->isPassword() ? this->getPasswordSize() : this->getMemorySize(); const uint32_t nRhsSize = rhs.isPassword() ? rhs.getPasswordSize() : rhs.getMemorySize(); if (nThisSize != nRhsSize) return false; if (0 == memcmp(this->isPassword() ? this->getPassword_uint8() : this->getMemory_uint8(), rhs. isPassword() ? rhs. getPassword_uint8() : rhs. getMemory_uint8(), rhs. isPassword() ? rhs. getPasswordSize() : rhs. getMemorySize()) ) return true; return false; }
OTPassword::OTPassword(const OTPassword& rhs) : size_(0) , isText_(rhs.isPassword()) , isBinary_(rhs.isMemory()) , isPageLocked_(false) , blockSize_( rhs.blockSize_) // The buffer has this size+1 as its static size. { if (isText_) { data_[0] = '\0'; setPassword_uint8(rhs.getPassword_uint8(), rhs.getPasswordSize()); } else if (isBinary_) { setMemory(rhs.getMemory_uint8(), rhs.getMemorySize()); } }
OTPassword::OTPassword(const OTPassword & rhs) : m_nPasswordSize(0), m_bIsText(rhs.isPassword()), m_bIsBinary(rhs.isMemory()), m_bIsPageLocked(false), m_theBlockSize(rhs.m_theBlockSize) // The buffer has this size+1 as its static size. { if (m_bIsText) { m_szPassword[0] = '\0'; setPassword_uint8(rhs.getPassword_uint8(), rhs.getPasswordSize()); } else if (m_bIsBinary) { setMemory(rhs.getMemory_uint8(), rhs.getMemorySize()); } }
bool OTEnvelope::Decrypt(String& theOutput, const OTSymmetricKey& theKey, const OTPassword& thePassword) { const char* szFunc = "OTEnvelope::Decrypt"; OT_ASSERT( (thePassword.isPassword() && (thePassword.getPasswordSize() > 0)) || (thePassword.isMemory() && (thePassword.getMemorySize() > 0))); OT_ASSERT(theKey.IsGenerated()); OTPassword theRawSymmetricKey; if (false == theKey.GetRawKeyFromPassphrase(thePassword, theRawSymmetricKey)) { otErr << szFunc << ": Failed trying to retrieve raw symmetric key " "using password. (Wrong password?)\n"; return false; } uint32_t nRead = 0; uint32_t nRunningTotal = 0; m_dataContents.reset(); // Reset the fread position on this object to 0. // // Read the ENVELOPE TYPE (as network order version -- and convert to host // version.) // // 0 == Error // 1 == Asymmetric Key (this function -- Seal / Open) // 2 == Symmetric Key (other functions -- Encrypt / Decrypt use this.) // Anything else: error. // uint16_t env_type_n = 0; if (0 == (nRead = m_dataContents.OTfread( reinterpret_cast<uint8_t*>(&env_type_n), static_cast<uint32_t>(sizeof(env_type_n))))) { otErr << szFunc << ": Error reading Envelope Type. Expected " "asymmetric(1) or symmetric (2).\n"; return false; } nRunningTotal += nRead; OT_ASSERT(nRead == static_cast<uint32_t>(sizeof(env_type_n))); // convert that envelope type from network to HOST endian. // const uint16_t env_type = ntohs(env_type_n); // nRunningTotal += env_type; // NOPE! Just because envelope type is 1 // or 2, doesn't mean we add 1 or 2 extra bytes to the length here. Nope! if (2 != env_type) { const uint32_t l_env_type = static_cast<uint32_t>(env_type); otErr << szFunc << ": Error: Expected Envelope for Symmetric key (type " "2) but instead found type: " << l_env_type << ".\n"; return false; } // Read network-order IV size (and convert to host version) // const uint32_t max_iv_length = OTCryptoConfig::SymmetricIvSize(); // I believe this is a max length, so // it may not match the actual length // of the IV. // Read the IV SIZE (network order version -- convert to host version.) // uint32_t iv_size_n = 0; if (0 == (nRead = m_dataContents.OTfread( reinterpret_cast<uint8_t*>(&iv_size_n), static_cast<uint32_t>(sizeof(iv_size_n))))) { otErr << szFunc << ": Error reading IV Size.\n"; return false; } nRunningTotal += nRead; OT_ASSERT(nRead == static_cast<uint32_t>(sizeof(iv_size_n))); // convert that iv size from network to HOST endian. // const uint32_t iv_size_host_order = ntohl(iv_size_n); if (iv_size_host_order > max_iv_length) { otErr << szFunc << ": Error: iv_size (" << static_cast<int64_t>(iv_size_host_order) << ") is larger than max_iv_length (" << static_cast<int64_t>(max_iv_length) << ").\n"; return false; } // nRunningTotal += iv_size_host_order; // Nope! // Then read the IV (initialization vector) itself. // OTData theIV; theIV.SetSize(iv_size_host_order); if (0 == (nRead = m_dataContents.OTfread( static_cast<uint8_t*>(const_cast<void*>(theIV.GetPointer())), static_cast<uint32_t>(iv_size_host_order)))) { otErr << szFunc << ": Error reading initialization vector.\n"; return false; } nRunningTotal += nRead; OT_ASSERT(nRead == static_cast<uint32_t>(iv_size_host_order)); OT_ASSERT(nRead <= max_iv_length); // We create an OTData object to store the ciphertext itself, which // begins AFTER the end of the IV. // So we see pointer + nRunningTotal as the starting point for the // ciphertext. // the size of the ciphertext, meanwhile, is the size of the entire thing, // MINUS nRunningTotal. // OTData theCipherText( static_cast<const void*>( static_cast<const uint8_t*>(m_dataContents.GetPointer()) + nRunningTotal), m_dataContents.GetSize() - nRunningTotal); // Now we've got all the pieces together, let's try to decrypt it... // OTData thePlaintext; // for output. const bool bDecrypted = OTCrypto::It()->Decrypt( theRawSymmetricKey, // The symmetric key, in clear form. static_cast<const char*>( theCipherText.GetPointer()), // This is the Ciphertext. theCipherText.GetSize(), theIV, thePlaintext); // OUTPUT. (Recovered plaintext.) You can pass // OTPassword& OR OTData& here (either will // work.) // theOutput is where we'll put the decrypted data. // theOutput.Release(); if (bDecrypted) { // Make sure it's null-terminated... // uint32_t nIndex = thePlaintext.GetSize() - 1; (static_cast<uint8_t*>( const_cast<void*>(thePlaintext.GetPointer())))[nIndex] = '\0'; // Set it into theOutput (to return the plaintext to the caller) // theOutput.Set(static_cast<const char*>(thePlaintext.GetPointer())); } return bDecrypted; }
bool OTEnvelope::Encrypt(const String& theInput, OTSymmetricKey& theKey, const OTPassword& thePassword) { OT_ASSERT( (thePassword.isPassword() && (thePassword.getPasswordSize() > 0)) || (thePassword.isMemory() && (thePassword.getMemorySize() > 0))); OT_ASSERT(theInput.Exists()); // Generate a random initialization vector. // OTData theIV; if (!theIV.Randomize(OTCryptoConfig::SymmetricIvSize())) { otErr << __FUNCTION__ << ": Failed trying to randomly generate IV.\n"; return false; } // If the symmetric key hasn't already been generated, we'll just do that // now... // (The passphrase is used to derive another key that is used to encrypt the // actual symmetric key, and to access it later.) // if ((false == theKey.IsGenerated()) && (false == theKey.GenerateKey(thePassword))) { otErr << __FUNCTION__ << ": Failed trying to generate symmetric key using password.\n"; return false; } if (!theKey.HasHashCheck()) { if (!theKey.GenerateHashCheck(thePassword)) { otErr << __FUNCTION__ << ": Failed trying to generate hash check using password.\n"; return false; } } OT_ASSERT(theKey.HasHashCheck()); OTPassword theRawSymmetricKey; if (false == theKey.GetRawKeyFromPassphrase(thePassword, theRawSymmetricKey)) { otErr << __FUNCTION__ << ": Failed trying to retrieve raw symmetric " "key using password.\n"; return false; } OTData theCipherText; const bool bEncrypted = OTCrypto::It()->Encrypt( theRawSymmetricKey, // The symmetric key, in clear form. theInput.Get(), // This is the Plaintext. theInput.GetLength() + 1, // for null terminator theIV, // Initialization vector. theCipherText); // OUTPUT. (Ciphertext.) // // Success? // if (!bEncrypted) { otErr << __FUNCTION__ << ": (static) call failed to encrypt. Wrong " "key? (Returning false.)\n"; return false; } // This is where the envelope final contents will be placed, // including the envelope type, the size of the IV, the IV // itself, and the ciphertext. // m_dataContents.Release(); // Write the ENVELOPE TYPE (network order version.) // // 0 == Error // 1 == Asymmetric Key (other functions -- Seal / Open.) // 2 == Symmetric Key (this function -- Encrypt / Decrypt.) // Anything else: error. // Calculate "network-order" version of envelope type 2. uint16_t env_type_n = htons(static_cast<uint16_t>(2)); m_dataContents.Concatenate(reinterpret_cast<void*>(&env_type_n), // (uint32_t here is the 2nd parameter to // Concatenate, and has nothing to do with // env_type_n being uint16_t) static_cast<uint32_t>(sizeof(env_type_n))); // Write IV size (in network-order) // uint32_t ivlen = OTCryptoConfig::SymmetricIvSize(); // Length of IV for this cipher... OT_ASSERT(ivlen >= theIV.GetSize()); uint32_t ivlen_n = htonl( theIV.GetSize()); // Calculate "network-order" version of iv length. m_dataContents.Concatenate(reinterpret_cast<void*>(&ivlen_n), static_cast<uint32_t>(sizeof(ivlen_n))); // Write the IV itself. // m_dataContents.Concatenate(theIV.GetPointer(), theIV.GetSize()); // Write the Ciphertext. // m_dataContents.Concatenate(theCipherText.GetPointer(), theCipherText.GetSize()); // We don't write the size of the ciphertext before the ciphertext itself, // since the decryption is able to deduce the size based on the total // envelope // size minus the other pieces. We might still want to add that size here, // however. // (for security / safety reasons.) return true; }