]> Git Repo - VerusCoin.git/blob - src/crypter.h
overhaul serialization code
[VerusCoin.git] / src / crypter.h
1 // Copyright (c) 2009-2013 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #ifndef __CRYPTER_H__
6 #define __CRYPTER_H__
7
8 #include "allocators.h"
9 #include "serialize.h"
10 #include "keystore.h"
11
12 class uint256;
13
14 const unsigned int WALLET_CRYPTO_KEY_SIZE = 32;
15 const unsigned int WALLET_CRYPTO_SALT_SIZE = 8;
16
17 /*
18 Private key encryption is done based on a CMasterKey,
19 which holds a salt and random encryption key.
20
21 CMasterKeys are encrypted using AES-256-CBC using a key
22 derived using derivation method nDerivationMethod
23 (0 == EVP_sha512()) and derivation iterations nDeriveIterations.
24 vchOtherDerivationParameters is provided for alternative algorithms
25 which may require more parameters (such as scrypt).
26
27 Wallet Private Keys are then encrypted using AES-256-CBC
28 with the double-sha256 of the public key as the IV, and the
29 master key's key as the encryption key (see keystore.[ch]).
30 */
31
32 /** Master key for wallet encryption */
33 class CMasterKey
34 {
35 public:
36     std::vector<unsigned char> vchCryptedKey;
37     std::vector<unsigned char> vchSalt;
38     // 0 = EVP_sha512()
39     // 1 = scrypt()
40     unsigned int nDerivationMethod;
41     unsigned int nDeriveIterations;
42     // Use this for more parameters to key derivation,
43     // such as the various parameters to scrypt
44     std::vector<unsigned char> vchOtherDerivationParameters;
45
46     IMPLEMENT_SERIALIZE
47
48     template <typename T, typename Stream, typename Operation>
49     inline static size_t SerializationOp(T thisPtr, Stream& s, Operation ser_action, int nType, int nVersion) {
50         size_t nSerSize = 0;
51         READWRITE(thisPtr->vchCryptedKey);
52         READWRITE(thisPtr->vchSalt);
53         READWRITE(thisPtr->nDerivationMethod);
54         READWRITE(thisPtr->nDeriveIterations);
55         READWRITE(thisPtr->vchOtherDerivationParameters);
56         return nSerSize;
57     }
58
59     CMasterKey()
60     {
61         // 25000 rounds is just under 0.1 seconds on a 1.86 GHz Pentium M
62         // ie slightly lower than the lowest hardware we need bother supporting
63         nDeriveIterations = 25000;
64         nDerivationMethod = 0;
65         vchOtherDerivationParameters = std::vector<unsigned char>(0);
66     }
67 };
68
69 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CKeyingMaterial;
70
71 /** Encryption/decryption context with key information */
72 class CCrypter
73 {
74 private:
75     unsigned char chKey[WALLET_CRYPTO_KEY_SIZE];
76     unsigned char chIV[WALLET_CRYPTO_KEY_SIZE];
77     bool fKeySet;
78
79 public:
80     bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector<unsigned char>& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod);
81     bool Encrypt(const CKeyingMaterial& vchPlaintext, std::vector<unsigned char> &vchCiphertext);
82     bool Decrypt(const std::vector<unsigned char>& vchCiphertext, CKeyingMaterial& vchPlaintext);
83     bool SetKey(const CKeyingMaterial& chNewKey, const std::vector<unsigned char>& chNewIV);
84
85     void CleanKey()
86     {
87         OPENSSL_cleanse(chKey, sizeof(chKey));
88         OPENSSL_cleanse(chIV, sizeof(chIV));
89         fKeySet = false;
90     }
91
92     CCrypter()
93     {
94         fKeySet = false;
95
96         // Try to keep the key data out of swap (and be a bit over-careful to keep the IV that we don't even use out of swap)
97         // Note that this does nothing about suspend-to-disk (which will put all our key data on disk)
98         // Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process.
99         LockedPageManager::Instance().LockRange(&chKey[0], sizeof chKey);
100         LockedPageManager::Instance().LockRange(&chIV[0], sizeof chIV);
101     }
102
103     ~CCrypter()
104     {
105         CleanKey();
106
107         LockedPageManager::Instance().UnlockRange(&chKey[0], sizeof chKey);
108         LockedPageManager::Instance().UnlockRange(&chIV[0], sizeof chIV);
109     }
110 };
111
112 bool EncryptSecret(const CKeyingMaterial& vMasterKey, const CKeyingMaterial &vchPlaintext, const uint256& nIV, std::vector<unsigned char> &vchCiphertext);
113 bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector<unsigned char>& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext);
114
115 /** Keystore which keeps the private keys encrypted.
116  * It derives from the basic key store, which is used if no encryption is active.
117  */
118 class CCryptoKeyStore : public CBasicKeyStore
119 {
120 private:
121     CryptedKeyMap mapCryptedKeys;
122
123     CKeyingMaterial vMasterKey;
124
125     // if fUseCrypto is true, mapKeys must be empty
126     // if fUseCrypto is false, vMasterKey must be empty
127     bool fUseCrypto;
128
129     // keeps track of whether Unlock has run a thourough check before
130     bool fDecryptionThoroughlyChecked;
131
132 protected:
133     bool SetCrypted();
134
135     // will encrypt previously unencrypted keys
136     bool EncryptKeys(CKeyingMaterial& vMasterKeyIn);
137
138     bool Unlock(const CKeyingMaterial& vMasterKeyIn);
139
140 public:
141     CCryptoKeyStore() : fUseCrypto(false), fDecryptionThoroughlyChecked(false)
142     {
143     }
144
145     bool IsCrypted() const
146     {
147         return fUseCrypto;
148     }
149
150     bool IsLocked() const
151     {
152         if (!IsCrypted())
153             return false;
154         bool result;
155         {
156             LOCK(cs_KeyStore);
157             result = vMasterKey.empty();
158         }
159         return result;
160     }
161
162     bool Lock();
163
164     virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret);
165     bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey);
166     bool HaveKey(const CKeyID &address) const
167     {
168         {
169             LOCK(cs_KeyStore);
170             if (!IsCrypted())
171                 return CBasicKeyStore::HaveKey(address);
172             return mapCryptedKeys.count(address) > 0;
173         }
174         return false;
175     }
176     bool GetKey(const CKeyID &address, CKey& keyOut) const;
177     bool GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const;
178     void GetKeys(std::set<CKeyID> &setAddress) const
179     {
180         if (!IsCrypted())
181         {
182             CBasicKeyStore::GetKeys(setAddress);
183             return;
184         }
185         setAddress.clear();
186         CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin();
187         while (mi != mapCryptedKeys.end())
188         {
189             setAddress.insert((*mi).first);
190             mi++;
191         }
192     }
193
194     /* Wallet status (encrypted, locked) changed.
195      * Note: Called without locks held.
196      */
197     boost::signals2::signal<void (CCryptoKeyStore* wallet)> NotifyStatusChanged;
198 };
199
200 #endif
This page took 0.035863 seconds and 4 git commands to generate.