Mercurial > hg > orthanc-object-storage
annotate Common/EncryptionHelpers.cpp @ 30:662b9d3f217d
fix missing definition of "byte" from CryptoPP
author | Sebastien Jodogne <s.jodogne@gmail.com> |
---|---|
date | Sat, 03 Oct 2020 10:39:45 +0200 |
parents | b0b7eb7cff73 |
children | f55b2afdf53d |
rev | line source |
---|---|
1 | 1 /** |
2 * Cloud storage plugins for Orthanc | |
3 * Copyright (C) 2017-2020 Osimis S.A., Belgium | |
4 * | |
5 * This program is free software: you can redistribute it and/or | |
6 * modify it under the terms of the GNU Affero General Public License | |
7 * as published by the Free Software Foundation, either version 3 of | |
8 * the License, or (at your option) any later version. | |
9 * | |
10 * This program is distributed in the hope that it will be useful, but | |
11 * WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
13 * Affero General Public License for more details. | |
14 * | |
15 * You should have received a copy of the GNU Affero General Public License | |
16 * along with this program. If not, see <http://www.gnu.org/licenses/>. | |
17 **/ | |
18 | |
19 #include "EncryptionHelpers.h" | |
20 #include <assert.h> | |
21 | |
22 #include <boost/lexical_cast.hpp> | |
23 #include <iostream> | |
30
662b9d3f217d
fix missing definition of "byte" from CryptoPP
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
25
diff
changeset
|
24 |
662b9d3f217d
fix missing definition of "byte" from CryptoPP
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
25
diff
changeset
|
25 #include <cryptopp/cryptlib.h> |
662b9d3f217d
fix missing definition of "byte" from CryptoPP
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
25
diff
changeset
|
26 #include <cryptopp/modes.h> |
662b9d3f217d
fix missing definition of "byte" from CryptoPP
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
25
diff
changeset
|
27 #include <cryptopp/hex.h> |
662b9d3f217d
fix missing definition of "byte" from CryptoPP
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
25
diff
changeset
|
28 #include <cryptopp/gcm.h> |
662b9d3f217d
fix missing definition of "byte" from CryptoPP
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
25
diff
changeset
|
29 #include <cryptopp/files.h> |
662b9d3f217d
fix missing definition of "byte" from CryptoPP
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
25
diff
changeset
|
30 #include <cryptopp/filters.h> |
1 | 31 |
32 const std::string EncryptionHelpers::HEADER_VERSION = "A1"; | |
33 | |
34 using namespace CryptoPP; | |
35 | |
30
662b9d3f217d
fix missing definition of "byte" from CryptoPP
Sebastien Jodogne <s.jodogne@gmail.com>
parents:
25
diff
changeset
|
36 std::string EncryptionHelpers::ToHexString(const void* block, size_t size) |
1 | 37 { |
38 std::string blockAsString = std::string(reinterpret_cast<const char*>(block), size); | |
39 | |
40 return ToHexString(blockAsString); | |
41 } | |
42 | |
43 std::string EncryptionHelpers::ToHexString(const std::string& block) | |
44 { | |
45 std::string hexString; | |
46 StringSource ss(block, true, | |
47 new HexEncoder( | |
48 new StringSink(hexString) | |
49 ) // StreamTransformationFilter | |
50 ); // StringSource | |
51 | |
52 return hexString; | |
53 } | |
54 | |
55 std::string EncryptionHelpers::ToHexString(const SecByteBlock& block) | |
56 { | |
57 return ToHexString(ToString(block)); | |
58 } | |
59 | |
60 std::string EncryptionHelpers::ToString(const CryptoPP::SecByteBlock& block) | |
61 { | |
62 return std::string(reinterpret_cast<const char*>(block.data()), block.size()); | |
63 } | |
64 | |
65 std::string EncryptionHelpers::ToString(uint32_t value) | |
66 { | |
67 return std::string(reinterpret_cast<const char*>(&value), 4); | |
68 } | |
69 | |
70 void EncryptionHelpers::ReadKey(CryptoPP::SecByteBlock& key, const std::string& path) | |
71 { | |
72 try | |
73 { | |
74 FileSource fs(path.c_str(), true, | |
75 new HexDecoder( | |
76 new ArraySink(key.begin(), key.size()) | |
77 ) | |
78 ); | |
79 } | |
80 catch (CryptoPP::Exception& ex) | |
81 { | |
82 throw EncryptionException("unabled to read key from file '" + path + "': " + ex.what()); | |
83 } | |
84 } | |
85 | |
86 void EncryptionHelpers::SetCurrentMasterKey(uint32_t id, const std::string& path) | |
87 { | |
88 SecByteBlock key(AES_KEY_SIZE); | |
89 | |
90 ReadKey(key, path); | |
91 SetCurrentMasterKey(id, key); | |
92 } | |
93 | |
94 void EncryptionHelpers::AddPreviousMasterKey(uint32_t id, const std::string& path) | |
95 { | |
96 SecByteBlock key(AES_KEY_SIZE); | |
97 | |
98 ReadKey(key, path); | |
99 AddPreviousMasterKey(id, key); | |
100 } | |
101 | |
102 EncryptionHelpers::EncryptionHelpers(size_t maxConcurrentInputSize) | |
103 : concurrentInputSizeSemaphore_(maxConcurrentInputSize), | |
104 maxConcurrentInputSize_(maxConcurrentInputSize) | |
105 { | |
106 } | |
107 | |
108 void EncryptionHelpers::SetCurrentMasterKey(uint32_t id, const CryptoPP::SecByteBlock& key) | |
109 { | |
110 encryptionMasterKey_ = key; | |
111 encryptionMasterKeyId_ = ToString(id); | |
112 } | |
113 | |
114 void EncryptionHelpers::AddPreviousMasterKey(uint32_t id, const CryptoPP::SecByteBlock& key) | |
115 { | |
116 previousMasterKeys_[ToString(id)] = key; | |
117 } | |
118 | |
119 const CryptoPP::SecByteBlock& EncryptionHelpers::GetMasterKey(const std::string& keyId) | |
120 { | |
121 if (encryptionMasterKeyId_ == keyId) | |
122 { | |
123 return encryptionMasterKey_; | |
124 } | |
125 | |
126 if (previousMasterKeys_.find(keyId) == previousMasterKeys_.end()) | |
127 { | |
128 throw EncryptionException("The master key whose id is '" + ToHexString(keyId) + "' could not be found. Unable to decrypt file"); | |
129 } | |
130 | |
131 return previousMasterKeys_.at(keyId); | |
132 } | |
133 | |
134 void EncryptionHelpers::GenerateKey(CryptoPP::SecByteBlock& key) | |
135 { | |
136 AutoSeededRandomPool prng; | |
137 | |
138 SecByteBlock tempKey(AES_KEY_SIZE); | |
139 prng.GenerateBlock( tempKey, tempKey.size() ); | |
140 key = tempKey; | |
141 } | |
142 | |
143 void EncryptionHelpers::Encrypt(std::string &output, const std::string &input) | |
144 { | |
145 Encrypt(output, input.data(), input.size()); | |
146 } | |
147 | |
148 void EncryptionHelpers::Encrypt(std::string &output, const char* data, size_t size) | |
149 { | |
150 if (size > maxConcurrentInputSize_) | |
151 { | |
152 throw EncryptionException("The file is too large to encrypt: " + boost::lexical_cast<std::string>(size) + " bytes. Try increasing the MaxConcurrentInputSize"); | |
153 } | |
154 | |
155 Orthanc::Semaphore::Locker lock(concurrentInputSizeSemaphore_, size); | |
156 | |
157 EncryptInternal(output, data, size, encryptionMasterKey_); | |
158 } | |
159 | |
160 void EncryptionHelpers::Decrypt(std::string &output, const std::string &input) | |
161 { | |
162 output.resize(input.size() - OVERHEAD_SIZE); | |
163 Decrypt(const_cast<char*>(output.data()), input.data(), input.size()); | |
164 } | |
165 | |
166 void EncryptionHelpers::Decrypt(char* output, const char* data, size_t size) | |
167 { | |
168 if (size > maxConcurrentInputSize_) | |
169 { | |
170 throw EncryptionException("The file is too large to decrypt: " + boost::lexical_cast<std::string>(size) + " bytes. Try increasing the MaxConcurrentInputSize"); | |
171 } | |
172 | |
173 Orthanc::Semaphore::Locker lock(concurrentInputSizeSemaphore_, size); | |
174 | |
175 if (size < HEADER_VERSION_SIZE) | |
176 { | |
177 throw EncryptionException("Unable to decrypt data, no header found"); | |
178 } | |
179 | |
180 std::string version = std::string(data, HEADER_VERSION_SIZE); | |
181 | |
182 if (version != "A1") | |
183 { | |
184 throw EncryptionException("Unable to decrypt data, version '" + version + "' is not supported"); | |
185 } | |
186 | |
187 if (size < (HEADER_VERSION_SIZE + MASTER_KEY_ID_SIZE)) | |
188 { | |
189 throw EncryptionException("Unable to decrypt data, no master key id found"); | |
190 } | |
191 | |
192 std::string decryptionMasterKeyId = std::string(data + HEADER_VERSION_SIZE, MASTER_KEY_ID_SIZE); | |
193 | |
194 const SecByteBlock& decryptionMasterKey = GetMasterKey(decryptionMasterKeyId); | |
195 DecryptInternal(output, data, size, decryptionMasterKey); | |
196 } | |
197 | |
198 void EncryptionHelpers::EncryptPrefixSecBlock(std::string& output, const CryptoPP::SecByteBlock& input, const CryptoPP::SecByteBlock& masterKey) | |
199 { | |
200 try | |
201 { | |
202 SecByteBlock iv(16); | |
203 memset(iv.data(), 0, iv.size()); | |
204 | |
205 CTR_Mode<AES>::Encryption e; | |
206 e.SetKeyWithIV(masterKey, masterKey.size(), iv.data(), iv.size()); | |
207 | |
208 std::string inputString = ToString(input); | |
209 | |
210 // The StreamTransformationFilter adds padding | |
211 // as required. ECB and CBC Mode must be padded | |
212 // to the block size of the cipher. | |
213 StringSource ss(inputString, true, | |
214 new StreamTransformationFilter(e, | |
215 new StringSink(output) | |
216 ) // StreamTransformationFilter | |
217 ); // StringSource | |
218 } | |
219 catch (CryptoPP::Exception& e) | |
220 { | |
221 throw EncryptionException(e.what()); | |
222 } | |
223 | |
224 assert(output.size() == input.size()); | |
225 } | |
226 | |
227 void EncryptionHelpers::DecryptPrefixSecBlock(CryptoPP::SecByteBlock& output, const std::string& input, const CryptoPP::SecByteBlock& masterKey) | |
228 { | |
229 try | |
230 { | |
231 SecByteBlock iv(16); | |
232 memset(iv.data(), 0, iv.size()); | |
233 | |
234 CTR_Mode<AES>::Decryption d; | |
235 d.SetKeyWithIV(masterKey, masterKey.size(), iv.data(), iv.size()); | |
236 | |
237 std::string outputString; | |
238 | |
239 // The StreamTransformationFilter adds padding | |
240 // as required. ECB and CBC Mode must be padded | |
241 // to the block size of the cipher. | |
242 StringSource ss(input, true, | |
243 new StreamTransformationFilter(d, | |
244 new StringSink(outputString) | |
245 ) // StreamTransformationFilter | |
246 ); // StringSource | |
247 | |
248 output.Assign((const byte*)outputString.data(), outputString.size()); | |
249 } | |
250 catch (CryptoPP::Exception& e) | |
251 { | |
252 throw EncryptionException(e.what()); | |
253 } | |
254 | |
255 assert(output.size() == input.size()); | |
256 } | |
257 | |
258 | |
259 void EncryptionHelpers::EncryptInternal(std::string& output, const char* data, size_t size, const CryptoPP::SecByteBlock& masterKey) | |
260 { | |
261 SecByteBlock iv(IV_SIZE); | |
262 randomGenerator_.GenerateBlock(iv, iv.size()); // with GCM, the iv is supposed to be a nonce (not a random number). However, since each dataKey is used only once, we consider a random number is fine. | |
263 | |
264 SecByteBlock dataKey; | |
265 GenerateKey(dataKey); | |
266 | |
267 // std::cout << ToHexString(dataKey) << std::endl; | |
268 // std::cout << ToHexString(iv) << std::endl; | |
269 std::string encryptedDataKey; | |
270 std::string encryptedIv; | |
271 | |
272 EncryptPrefixSecBlock(encryptedIv, iv, masterKey); | |
273 EncryptPrefixSecBlock(encryptedDataKey, dataKey, masterKey); | |
274 | |
275 std::string prefix = HEADER_VERSION + encryptionMasterKeyId_ + encryptedIv + encryptedDataKey; | |
276 | |
277 try | |
278 { | |
279 GCM<AES>::Encryption e; | |
25 | 280 e.SetKeyWithIV(dataKey, dataKey.size(), iv, iv.size()); |
1 | 281 |
282 // the output text starts with the unencrypted prefix | |
283 output = prefix; | |
284 | |
285 AuthenticatedEncryptionFilter ef(e, | |
286 new StringSink(output), false, INTEGRITY_CHECK_TAG_SIZE | |
287 ); | |
288 | |
289 | |
290 // AuthenticatedEncryptionFilter::ChannelPut | |
291 // defines two channels: "" (empty) and "AAD" | |
292 // channel "" is encrypted and authenticated | |
293 // channel "AAD" is authenticated | |
294 ef.ChannelPut("AAD", (const byte*)prefix.data(), prefix.size()); | |
295 ef.ChannelMessageEnd("AAD"); | |
296 | |
297 // Authenticated data *must* be pushed before | |
298 // Confidential/Authenticated data. Otherwise | |
299 // we must catch the BadState exception | |
300 ef.ChannelPut("", (const byte*)data, size); | |
301 ef.ChannelMessageEnd(""); | |
302 } | |
303 catch(CryptoPP::Exception& e) | |
304 { | |
305 throw EncryptionException(e.what()); | |
306 } | |
307 } | |
308 | |
309 void EncryptionHelpers::DecryptInternal(char* output, const char* data, size_t size, const CryptoPP::SecByteBlock& masterKey) | |
310 { | |
311 size_t prefixSize = HEADER_VERSION_SIZE + MASTER_KEY_ID_SIZE + IV_SIZE + AES_KEY_SIZE; | |
312 | |
313 std::string prefix = std::string(data, prefixSize); | |
314 std::string mac = std::string(data + size - INTEGRITY_CHECK_TAG_SIZE, INTEGRITY_CHECK_TAG_SIZE); | |
315 | |
316 std::string encryptedIv = prefix.substr(HEADER_VERSION_SIZE + MASTER_KEY_ID_SIZE, IV_SIZE); | |
317 std::string encryptedDataKey = prefix.substr(HEADER_VERSION_SIZE + MASTER_KEY_ID_SIZE + IV_SIZE, AES_KEY_SIZE); | |
318 | |
319 SecByteBlock dataKey; | |
320 SecByteBlock iv; | |
321 | |
322 DecryptPrefixSecBlock(iv, encryptedIv, masterKey); | |
323 DecryptPrefixSecBlock(dataKey, encryptedDataKey, masterKey); | |
324 // std::cout << ToHexString(dataKey) << std::endl; | |
325 // std::cout << ToHexString(iv) << std::endl; | |
326 | |
327 GCM<AES>::Decryption d; | |
25 | 328 d.SetKeyWithIV(dataKey, dataKey.size(), iv, iv.size()); |
1 | 329 |
330 try { | |
331 AuthenticatedDecryptionFilter df(d, NULL, | |
332 AuthenticatedDecryptionFilter::MAC_AT_BEGIN | | |
333 AuthenticatedDecryptionFilter::THROW_EXCEPTION, INTEGRITY_CHECK_TAG_SIZE); | |
334 | |
335 // The order of the following calls are important | |
336 df.ChannelPut("", (const byte*)mac.data(), mac.size()); | |
337 df.ChannelPut("AAD", (const byte*)prefix.data(), prefix.size()); | |
338 df.ChannelPut("", (const byte*)(data) + prefixSize, size - INTEGRITY_CHECK_TAG_SIZE - prefixSize); | |
339 | |
340 // If the object throws, it will most likely occur | |
341 // during ChannelMessageEnd() | |
342 df.ChannelMessageEnd("AAD"); | |
343 df.ChannelMessageEnd(""); | |
344 | |
345 // If the object does not throw, here's the only | |
346 // opportunity to check the data's integrity | |
347 if (!df.GetLastResult()) | |
348 { | |
349 throw EncryptionException("The decryption filter failed for some unknown reason. Integrity check failed ?"); | |
350 } | |
351 | |
352 // Remove data from channel | |
353 size_t n = (size_t)-1; | |
354 | |
355 // Recover plain text | |
356 df.SetRetrievalChannel(""); | |
357 n = (size_t)df.MaxRetrievable(); | |
358 | |
359 if(n > 0) | |
360 { | |
361 assert(n == size - OVERHEAD_SIZE); | |
362 | |
363 df.Get((byte*)output, n); | |
364 } | |
365 } | |
366 catch (CryptoPP::Exception& ex) | |
367 { | |
368 throw EncryptionException(ex.what()); | |
369 } | |
370 } |