Fabcoin Core  0.16.2
P2P Digital Currency
default.cpp
Go to the documentation of this file.
1 // default.cpp - written and placed in the public domain by Wei Dai
2 
3 #include "pch.h"
4 #include "config.h"
5 
6 #if CRYPTOPP_MSC_VERSION
7 # pragma warning(disable: 4127 4189)
8 #endif
9 
10 #include "cryptlib.h"
11 #include "filters.h"
12 #include "smartptr.h"
13 #include "default.h"
14 #include "queue.h"
15 
16 #include <time.h>
17 #include <memory>
18 
20 
21 // The purpose of this function Mash() is to take an arbitrary length input
22 // string and *deterministicly* produce an arbitrary length output string such
23 // that (1) it looks random, (2) no information about the input is
24 // deducible from it, and (3) it contains as much entropy as it can hold, or
25 // the amount of entropy in the input string, whichever is smaller.
26 
27 template <class H>
28 static void Mash(const byte *in, size_t inLen, byte *out, size_t outLen, int iterations)
29 {
30  if (BytePrecision(outLen) > 2)
31  throw InvalidArgument("Mash: output legnth too large");
32 
33  size_t bufSize = RoundUpToMultipleOf(outLen, (size_t)H::DIGESTSIZE);
34  byte b[2];
35  SecByteBlock buf(bufSize);
36  SecByteBlock outBuf(bufSize);
37  H hash;
38 
39  unsigned int i;
40  for(i=0; i<outLen; i+=H::DIGESTSIZE)
41  {
42  b[0] = (byte) (i >> 8);
43  b[1] = (byte) i;
44  hash.Update(b, 2);
45  hash.Update(in, inLen);
46  hash.Final(outBuf+i);
47  }
48 
49  while (iterations-- > 1)
50  {
51  memcpy(buf, outBuf, bufSize);
52  for (i=0; i<bufSize; i+=H::DIGESTSIZE)
53  {
54  b[0] = (byte) (i >> 8);
55  b[1] = (byte) i;
56  hash.Update(b, 2);
57  hash.Update(buf, bufSize);
58  hash.Final(outBuf+i);
59  }
60  }
61 
62  memcpy(out, outBuf, outLen);
63 }
64 
65 template <class BC, class H, class Info>
66 static void GenerateKeyIV(const byte *passphrase, size_t passphraseLength, const byte *salt, size_t saltLength, unsigned int iterations, byte *key, byte *IV)
67 {
68  SecByteBlock temp(passphraseLength+saltLength);
69  memcpy(temp, passphrase, passphraseLength);
70  memcpy(temp+passphraseLength, salt, saltLength);
71  SecByteBlock keyIV(Info::KEYLENGTH+Info::BLOCKSIZE);
72  Mash<H>(temp, passphraseLength + saltLength, keyIV, Info::KEYLENGTH+Info::BLOCKSIZE, iterations);
73  memcpy(key, keyIV, Info::KEYLENGTH);
74  memcpy(IV, keyIV+Info::KEYLENGTH, Info::BLOCKSIZE);
75 }
76 
77 // ********************************************************
78 
79 template <class BC, class H, class Info>
81  : ProxyFilter(NULL, 0, 0, attachment), m_passphrase((const byte *)passphrase, strlen(passphrase))
82 {
83  CRYPTOPP_COMPILE_ASSERT(SALTLENGTH <= DIGESTSIZE);
84  CRYPTOPP_COMPILE_ASSERT(BLOCKSIZE <= DIGESTSIZE);
85 }
86 
87 template <class BC, class H, class Info>
88 DataEncryptor<BC,H,Info>::DataEncryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment)
89  : ProxyFilter(NULL, 0, 0, attachment), m_passphrase(passphrase, passphraseLength)
90 {
91  CRYPTOPP_COMPILE_ASSERT(SALTLENGTH <= DIGESTSIZE);
92  CRYPTOPP_COMPILE_ASSERT(BLOCKSIZE <= DIGESTSIZE);
93 }
94 
95 template <class BC, class H, class Info>
97 {
98  SecByteBlock salt(DIGESTSIZE), keyCheck(DIGESTSIZE);
99  H hash;
100 
101  // use hash(passphrase | time | clock) as salt
102  hash.Update(m_passphrase, m_passphrase.size());
103  time_t t=time(0);
104  hash.Update((byte *)&t, sizeof(t));
105  clock_t c=clock();
106  hash.Update((byte *)&c, sizeof(c));
107  hash.Final(salt);
108 
109  // use hash(passphrase | salt) as key check
110  hash.Update(m_passphrase, m_passphrase.size());
111  hash.Update(salt, SALTLENGTH);
112  hash.Final(keyCheck);
113 
114  AttachedTransformation()->Put(salt, SALTLENGTH);
115 
116  // mash passphrase and salt together into key and IV
117  SecByteBlock key(KEYLENGTH);
118  SecByteBlock IV(BLOCKSIZE);
119  GenerateKeyIV<BC,H,Info>(m_passphrase, m_passphrase.size(), salt, SALTLENGTH, ITERATIONS, key, IV);
120 
121  m_cipher.SetKeyWithIV(key, key.size(), IV);
123 
124  m_filter->Put(keyCheck, BLOCKSIZE);
125 }
126 
127 template <class BC, class H, class Info>
128 void DataEncryptor<BC,H,Info>::LastPut(const byte *inString, size_t length)
129 {
130  CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
131  m_filter->MessageEnd();
132 }
133 
134 // ********************************************************
135 
136 template <class BC, class H, class Info>
137 DataDecryptor<BC,H,Info>::DataDecryptor(const char *p, BufferedTransformation *attachment, bool throwException)
138  : ProxyFilter(NULL, SALTLENGTH+BLOCKSIZE, 0, attachment)
139  , m_state(WAITING_FOR_KEYCHECK)
140  , m_passphrase((const byte *)p, strlen(p))
141  , m_throwException(throwException)
142 {
143  CRYPTOPP_COMPILE_ASSERT(SALTLENGTH <= DIGESTSIZE);
144  CRYPTOPP_COMPILE_ASSERT(BLOCKSIZE <= DIGESTSIZE);
145 }
146 
147 template <class BC, class H, class Info>
148 DataDecryptor<BC,H,Info>::DataDecryptor(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment, bool throwException)
149  : ProxyFilter(NULL, SALTLENGTH+BLOCKSIZE, 0, attachment)
151  , m_passphrase(passphrase, passphraseLength)
152  , m_throwException(throwException)
153 {
154  CRYPTOPP_COMPILE_ASSERT(SALTLENGTH <= DIGESTSIZE);
155  CRYPTOPP_COMPILE_ASSERT(BLOCKSIZE <= DIGESTSIZE);
156 }
157 
158 template <class BC, class H, class Info>
160 {
161  CheckKey(inString, inString+SALTLENGTH);
162 }
163 
164 template <class BC, class H, class Info>
165 void DataDecryptor<BC,H,Info>::LastPut(const byte *inString, size_t length)
166 {
167  CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
168  if (m_filter.get() == NULL)
169  {
170  m_state = KEY_BAD;
171  if (m_throwException)
172  throw KeyBadErr();
173  }
174  else
175  {
176  m_filter->MessageEnd();
178  }
179 }
180 
181 template <class BC, class H, class Info>
182 void DataDecryptor<BC,H,Info>::CheckKey(const byte *salt, const byte *keyCheck)
183 {
184  SecByteBlock check(STDMAX((unsigned int)2*BLOCKSIZE, (unsigned int)DIGESTSIZE));
185 
186  H hash;
187  hash.Update(m_passphrase, m_passphrase.size());
188  hash.Update(salt, SALTLENGTH);
189  hash.Final(check);
190 
191  SecByteBlock key(KEYLENGTH);
192  SecByteBlock IV(BLOCKSIZE);
193  GenerateKeyIV<BC,H,Info>(m_passphrase, m_passphrase.size(), salt, SALTLENGTH, ITERATIONS, key, IV);
194 
195  m_cipher.SetKeyWithIV(key, key.size(), IV);
197 
198  decryptor->Put(keyCheck, BLOCKSIZE);
199  decryptor->ForceNextPut();
200  decryptor->Get(check+BLOCKSIZE, BLOCKSIZE);
201 
202  SetFilter(decryptor.release());
203 
204  if (!VerifyBufsEqual(check, check+BLOCKSIZE, BLOCKSIZE))
205  {
206  m_state = KEY_BAD;
207  if (m_throwException)
208  throw KeyBadErr();
209  }
210  else
211  m_state = KEY_GOOD;
212 }
213 
214 // ********************************************************
215 
216 template <class H, class MAC>
217 static MAC* NewDataEncryptorMAC(const byte *passphrase, size_t passphraseLength)
218 {
219  size_t macKeyLength = MAC::StaticGetValidKeyLength(16);
220  SecByteBlock macKey(macKeyLength);
221  // since the MAC is encrypted there is no reason to mash the passphrase for many iterations
222  Mash<H>(passphrase, passphraseLength, macKey, macKeyLength, 1);
223  return new MAC(macKey, macKeyLength);
224 }
225 
226 template <class BC, class H, class MAC, class Info>
228  : ProxyFilter(NULL, 0, 0, attachment)
229  , m_mac(NewDataEncryptorMAC<H,MAC>((const byte *)passphrase, strlen(passphrase)))
230 {
231  SetFilter(new HashFilter(*m_mac, new DataEncryptor<BC,H,Info>(passphrase), true));
232 }
233 
234 template <class BC, class H, class MAC, class Info>
235 DataEncryptorWithMAC<BC,H,MAC,Info>::DataEncryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment)
236  : ProxyFilter(NULL, 0, 0, attachment)
237  , m_mac(NewDataEncryptorMAC<H,MAC>(passphrase, passphraseLength))
238 {
239  SetFilter(new HashFilter(*m_mac, new DataEncryptor<BC,H,Info>(passphrase, passphraseLength), true));
240 }
241 
242 template <class BC, class H, class MAC, class Info>
243 void DataEncryptorWithMAC<BC,H,MAC,Info>::LastPut(const byte *inString, size_t length)
244 {
245  CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
246  m_filter->MessageEnd();
247 }
248 
249 // ********************************************************
250 
251 template <class BC, class H, class MAC, class Info>
252 DataDecryptorWithMAC<BC,H,MAC,Info>::DataDecryptorWithMAC(const char *passphrase, BufferedTransformation *attachment, bool throwException)
253  : ProxyFilter(NULL, 0, 0, attachment)
254  , m_mac(NewDataEncryptorMAC<H,MAC>((const byte *)passphrase, strlen(passphrase)))
255  , m_throwException(throwException)
256 {
258 }
259 
260 template <class BC, class H, class MAC, class Info>
261 DataDecryptorWithMAC<BC,H,MAC,Info>::DataDecryptorWithMAC(const byte *passphrase, size_t passphraseLength, BufferedTransformation *attachment, bool throwException)
262  : ProxyFilter(NULL, 0, 0, attachment)
263  , m_mac(NewDataEncryptorMAC<H,MAC>(passphrase, passphraseLength))
264  , m_throwException(throwException)
265 {
266  SetFilter(new DataDecryptor<BC,H,Info>(passphrase, passphraseLength, m_hashVerifier=new HashVerificationFilter(*m_mac, NULL, HashVerificationFilter::PUT_MESSAGE), throwException));
267 }
268 
269 template <class BC, class H, class MAC, class Info>
271 {
272  return static_cast<const DataDecryptor<BC,H,Info> *>(m_filter.get())->CurrentState();
273 }
274 
275 template <class BC, class H, class MAC, class Info>
277 {
278  return m_hashVerifier->GetLastResult();
279 }
280 
281 template <class BC, class H, class MAC, class Info>
282 void DataDecryptorWithMAC<BC,H,MAC,Info>::LastPut(const byte *inString, size_t length)
283 {
284  CRYPTOPP_UNUSED(inString); CRYPTOPP_UNUSED(length);
285  m_filter->MessageEnd();
286  if (m_throwException && !CheckLastMAC())
287  throw MACBadErr();
288 }
289 
292 
301 
member_ptr< MAC > m_mac
Definition: default.h:199
An invalid argument was detected.
Definition: cryptlib.h:184
Exception thrown when a bad key is encountered in DefaultDecryptorWithMAC and LegacyDecryptorWithMAC...
Definition: default.h:44
Base class for Filter classes that are proxies for a chain of other filters.
Definition: filters.h:951
uint8_t byte
Definition: Common.h:57
member_ptr< BufferedTransformation > m_filter
Definition: filters.h:972
void LastPut(const byte *inString, size_t length)
Input the last block of data.
Definition: default.cpp:282
HashVerificationFilter * m_hashVerifier
Definition: default.h:245
CBC_Mode< BC >::Decryption m_cipher
Definition: default.h:157
bool GetLastResult() const
Definition: filters.h:593
unsigned int BytePrecision(const T &value)
Returns the number of 8-bit bytes or octets required for a value.
Definition: misc.h:632
#define NAMESPACE_BEGIN(x)
Definition: config.h:200
DataDecryptor< BC, H, Info >::State CurrentState() const
Definition: default.cpp:270
Password-based Encryptor.
Definition: default.h:83
Abstract base classes that provide a uniform interface to this library.
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:524
Password-based Decryptor.
Definition: default.h:122
Classes for automatic resource management.
#define c(i)
Classes for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC.
Library configuration file.
Interface for buffered transformations.
Definition: cryptlib.h:1352
Pointer that overloads operator ->
Definition: smartptr.h:39
DataEncryptor(const char *passphrase, BufferedTransformation *attachment=NULL)
Construct a DataEncryptor.
Definition: default.cpp:80
best_clock::type clock
Definition: bench.h:48
void LastPut(const byte *inString, size_t length)
Input the last block of data.
Definition: default.cpp:243
bool MessageEnd(int propagation=-1, bool blocking=true)
Signals the end of messages to the object.
Definition: cryptlib.h:1434
void FirstPut(const byte *inString)
Definition: default.cpp:159
Classes for an unlimited queue to store bytes.
#define CRYPTOPP_COMPILE_ASSERT(assertion)
Definition: misc.h:139
Filter wrapper for HashTransformation.
Definition: filters.h:550
Filter wrapper for HashTransformation.
Definition: filters.h:521
Password-based encryptor with MAC.
Definition: default.h:180
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition: cryptlib.h:1376
bool CheckLastMAC() const
Definition: default.cpp:276
DataEncryptorWithMAC(const char *passphrase, BufferedTransformation *attachment=NULL)
Constructs a DataEncryptorWithMAC.
Definition: default.cpp:227
BufferedTransformation * AttachedTransformation()
Retrieve attached transformation.
Definition: filters.cpp:36
Indicates the message should be passed to an attached transformation.
Definition: filters.h:573
#define H(x, y, z)
Definition: Hash.cpp:81
SecByteBlock m_passphrase
Definition: default.h:156
bool m_throwException
Definition: default.h:159
const T * get() const
Definition: smartptr.h:52
Algorithm information for password-based encryptors and decryptors.
Definition: default.h:61
#define b(i, j)
void LastPut(const byte *inString, size_t length)
Input the last block of data.
Definition: default.cpp:128
CBC_Mode< BC >::Encryption m_cipher
Definition: default.h:109
Implementation of BufferedTransformation&#39;s attachment interface.
Filter wrapper for StreamTransformation.
Definition: filters.h:491
State m_state
Definition: default.h:151
T * release()
Definition: smartptr.h:55
void * memcpy(void *a, const void *b, size_t c)
#define CRYPTOPP_UNUSED(x)
Definition: config.h:741
SecByteBlock m_passphrase
Definition: default.h:108
DataDecryptor(const char *passphrase, BufferedTransformation *attachment=NULL, bool throwException=true)
Constructs a DataDecryptor.
Definition: default.cpp:137
DataDecryptorWithMAC(const char *passphrase, BufferedTransformation *attachment=NULL, bool throwException=true)
Constructs a DataDecryptor.
Definition: default.cpp:252
void ForceNextPut()
Flushes data buffered by this object.
Definition: filters.cpp:441
uint8_t byte
Definition: Common.h:10
Password-based decryptor with MAC.
Definition: default.h:220
void FirstPut(const byte *)
Definition: default.cpp:96
void LastPut(const byte *inString, size_t length)
Input the last block of data.
Definition: default.cpp:165
T1 RoundUpToMultipleOf(const T1 &n, const T2 &m)
Rounds a value up to a multiple of a second value.
Definition: misc.h:905
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:487
#define NAMESPACE_END
Definition: config.h:201
member_ptr< MAC > m_mac
Definition: default.h:244
virtual size_t Get(byte &outByte)
Retrieve a 8-bit byte.
Definition: cryptlib.cpp:515
void CheckKey(const byte *salt, const byte *keyCheck)
Definition: default.cpp:182
void SetFilter(Filter *filter)
Sets the OutputProxy filter.
Definition: filters.cpp:496
Exception thrown when an incorrect MAC is encountered in DefaultDecryptorWithMAC and LegacyDecryptorW...
Definition: default.h:52
bool VerifyBufsEqual(const byte *buf, const byte *mask, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
Definition: misc.cpp:96