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