Merge #12079: Improve prioritisetransaction test coverage
[bitcoinplatinum.git] / src / wallet / crypter.cpp
blobfd7e1bb56c33f0985eba02579e21fd1ca09a34d2
1 // Copyright (c) 2009-2017 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include <wallet/crypter.h>
7 #include <crypto/aes.h>
8 #include <crypto/sha512.h>
9 #include <script/script.h>
10 #include <script/standard.h>
11 #include <util.h>
13 #include <string>
14 #include <vector>
16 int CCrypter::BytesToKeySHA512AES(const std::vector<unsigned char>& chSalt, const SecureString& strKeyData, int count, unsigned char *key,unsigned char *iv) const
18 // This mimics the behavior of openssl's EVP_BytesToKey with an aes256cbc
19 // cipher and sha512 message digest. Because sha512's output size (64b) is
20 // greater than the aes256 block size (16b) + aes256 key size (32b),
21 // there's no need to process more than once (D_0).
23 if(!count || !key || !iv)
24 return 0;
26 unsigned char buf[CSHA512::OUTPUT_SIZE];
27 CSHA512 di;
29 di.Write((const unsigned char*)strKeyData.c_str(), strKeyData.size());
30 di.Write(chSalt.data(), chSalt.size());
31 di.Finalize(buf);
33 for(int i = 0; i != count - 1; i++)
34 di.Reset().Write(buf, sizeof(buf)).Finalize(buf);
36 memcpy(key, buf, WALLET_CRYPTO_KEY_SIZE);
37 memcpy(iv, buf + WALLET_CRYPTO_KEY_SIZE, WALLET_CRYPTO_IV_SIZE);
38 memory_cleanse(buf, sizeof(buf));
39 return WALLET_CRYPTO_KEY_SIZE;
42 bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
44 if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE)
45 return false;
47 int i = 0;
48 if (nDerivationMethod == 0)
49 i = BytesToKeySHA512AES(chSalt, strKeyData, nRounds, vchKey.data(), vchIV.data());
51 if (i != (int)WALLET_CRYPTO_KEY_SIZE)
53 memory_cleanse(vchKey.data(), vchKey.size());
54 memory_cleanse(vchIV.data(), vchIV.size());
55 return false;
58 fKeySet = true;
59 return true;
62 bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV)
64 if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_IV_SIZE)
65 return false;
67 memcpy(vchKey.data(), chNewKey.data(), chNewKey.size());
68 memcpy(vchIV.data(), chNewIV.data(), chNewIV.size());
70 fKeySet = true;
71 return true;
74 bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext) const
76 if (!fKeySet)
77 return false;
79 // max ciphertext len for a n bytes of plaintext is
80 // n + AES_BLOCKSIZE bytes
81 vchCiphertext.resize(vchPlaintext.size() + AES_BLOCKSIZE);
83 AES256CBCEncrypt enc(vchKey.data(), vchIV.data(), true);
84 size_t nLen = enc.Encrypt(&vchPlaintext[0], vchPlaintext.size(), vchCiphertext.data());
85 if(nLen < vchPlaintext.size())
86 return false;
87 vchCiphertext.resize(nLen);
89 return true;
92 bool CCrypter::Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext) const
94 if (!fKeySet)
95 return false;
97 // plaintext will always be equal to or lesser than length of ciphertext
98 int nLen = vchCiphertext.size();
100 vchPlaintext.resize(nLen);
102 AES256CBCDecrypt dec(vchKey.data(), vchIV.data(), true);
103 nLen = dec.Decrypt(vchCiphertext.data(), vchCiphertext.size(), &vchPlaintext[0]);
104 if(nLen == 0)
105 return false;
106 vchPlaintext.resize(nLen);
107 return true;
111 static bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext)
113 CCrypter cKeyCrypter;
114 std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE);
115 memcpy(chIV.data(), &nIV, WALLET_CRYPTO_IV_SIZE);
116 if(!cKeyCrypter.SetKey(vMasterKey, chIV))
117 return false;
118 return cKeyCrypter.Encrypt(*((const CKeyingMaterial*)&vchPlaintext), vchCiphertext);
121 static bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext)
123 CCrypter cKeyCrypter;
124 std::vector<unsigned char> chIV(WALLET_CRYPTO_IV_SIZE);
125 memcpy(chIV.data(), &nIV, WALLET_CRYPTO_IV_SIZE);
126 if(!cKeyCrypter.SetKey(vMasterKey, chIV))
127 return false;
128 return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext));
131 static bool DecryptKey(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCryptedSecret, const CPubKey& vchPubKey, CKey& key)
133 CKeyingMaterial vchSecret;
134 if(!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret))
135 return false;
137 if (vchSecret.size() != 32)
138 return false;
140 key.Set(vchSecret.begin(), vchSecret.end(), vchPubKey.IsCompressed());
141 return key.VerifyPubKey(vchPubKey);
144 bool CCryptoKeyStore::SetCrypted()
146 LOCK(cs_KeyStore);
147 if (fUseCrypto)
148 return true;
149 if (!mapKeys.empty())
150 return false;
151 fUseCrypto = true;
152 return true;
155 bool CCryptoKeyStore::IsLocked() const
157 if (!IsCrypted()) {
158 return false;
160 LOCK(cs_KeyStore);
161 return vMasterKey.empty();
164 bool CCryptoKeyStore::Lock()
166 if (!SetCrypted())
167 return false;
170 LOCK(cs_KeyStore);
171 vMasterKey.clear();
174 NotifyStatusChanged(this);
175 return true;
178 bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn)
181 LOCK(cs_KeyStore);
182 if (!SetCrypted())
183 return false;
185 bool keyPass = false;
186 bool keyFail = false;
187 CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
188 for (; mi != mapCryptedKeys.end(); ++mi)
190 const CPubKey &vchPubKey = (*mi).second.first;
191 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
192 CKey key;
193 if (!DecryptKey(vMasterKeyIn, vchCryptedSecret, vchPubKey, key))
195 keyFail = true;
196 break;
198 keyPass = true;
199 if (fDecryptionThoroughlyChecked)
200 break;
202 if (keyPass && keyFail)
204 LogPrintf("The wallet is probably corrupted: Some keys decrypt but not all.\n");
205 assert(false);
207 if (keyFail || !keyPass)
208 return false;
209 vMasterKey = vMasterKeyIn;
210 fDecryptionThoroughlyChecked = true;
212 NotifyStatusChanged(this);
213 return true;
216 bool CCryptoKeyStore::AddKeyPubKey(const CKey& key, const CPubKey &pubkey)
218 LOCK(cs_KeyStore);
219 if (!IsCrypted()) {
220 return CBasicKeyStore::AddKeyPubKey(key, pubkey);
223 if (IsLocked()) {
224 return false;
227 std::vector<unsigned char> vchCryptedSecret;
228 CKeyingMaterial vchSecret(key.begin(), key.end());
229 if (!EncryptSecret(vMasterKey, vchSecret, pubkey.GetHash(), vchCryptedSecret)) {
230 return false;
233 if (!AddCryptedKey(pubkey, vchCryptedSecret)) {
234 return false;
236 return true;
240 bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
242 LOCK(cs_KeyStore);
243 if (!SetCrypted()) {
244 return false;
247 mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret);
248 return true;
251 bool CCryptoKeyStore::HaveKey(const CKeyID &address) const
253 LOCK(cs_KeyStore);
254 if (!IsCrypted()) {
255 return CBasicKeyStore::HaveKey(address);
257 return mapCryptedKeys.count(address) > 0;
260 bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const
262 LOCK(cs_KeyStore);
263 if (!IsCrypted()) {
264 return CBasicKeyStore::GetKey(address, keyOut);
267 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
268 if (mi != mapCryptedKeys.end())
270 const CPubKey &vchPubKey = (*mi).second.first;
271 const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second;
272 return DecryptKey(vMasterKey, vchCryptedSecret, vchPubKey, keyOut);
274 return false;
277 bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
279 LOCK(cs_KeyStore);
280 if (!IsCrypted())
281 return CBasicKeyStore::GetPubKey(address, vchPubKeyOut);
283 CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address);
284 if (mi != mapCryptedKeys.end())
286 vchPubKeyOut = (*mi).second.first;
287 return true;
289 // Check for watch-only pubkeys
290 return CBasicKeyStore::GetPubKey(address, vchPubKeyOut);
293 std::set<CKeyID> CCryptoKeyStore::GetKeys() const
295 LOCK(cs_KeyStore);
296 if (!IsCrypted()) {
297 return CBasicKeyStore::GetKeys();
299 std::set<CKeyID> set_address;
300 for (const auto& mi : mapCryptedKeys) {
301 set_address.insert(mi.first);
303 return set_address;
306 bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn)
308 LOCK(cs_KeyStore);
309 if (!mapCryptedKeys.empty() || IsCrypted())
310 return false;
312 fUseCrypto = true;
313 for (KeyMap::value_type& mKey : mapKeys)
315 const CKey &key = mKey.second;
316 CPubKey vchPubKey = key.GetPubKey();
317 CKeyingMaterial vchSecret(key.begin(), key.end());
318 std::vector<unsigned char> vchCryptedSecret;
319 if (!EncryptSecret(vMasterKeyIn, vchSecret, vchPubKey.GetHash(), vchCryptedSecret))
320 return false;
321 if (!AddCryptedKey(vchPubKey, vchCryptedSecret))
322 return false;
324 mapKeys.clear();
325 return true;