MagickCore 7.1.2-37
Convert, Edit, Or Compose Bitmap Images
Loading...
Searching...
No Matches
cipher.c
1/*
2%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
3% %
4% %
5% CCCC IIIII PPPP H H EEEEE RRRR %
6% C I P P H H E R R %
7% C I PPPP HHHHH EEE RRRR %
8% C I P H H E R R %
9% CCCC IIIII P H H EEEEE R R %
10% %
11% %
12% MagickCore Cipher Methods %
13% %
14% Software Design %
15% Cristy %
16% %
17% %
18% Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization %
19% dedicated to making software imaging solutions freely available. %
20% %
21% You may not use this file except in compliance with the License. You may %
22% obtain a copy of the License at %
23% %
24% https://imagemagick.org/license/ %
25% %
26% Unless required by applicable law or agreed to in writing, software %
27% distributed under the License is distributed on an "AS IS" BASIS, %
28% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
29% See the License for the specific language governing permissions and %
30% limitations under the License. %
31% %
32%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
33%
34%
35*/
36␌
37/*
38 Include declarations.
39*/
40#include "MagickCore/studio.h"
41#include "MagickCore/cache.h"
42#include "MagickCore/cipher.h"
43#include "MagickCore/exception.h"
44#include "MagickCore/exception-private.h"
45#include "MagickCore/image.h"
46#include "MagickCore/image-private.h"
47#include "MagickCore/linked-list.h"
48#include "MagickCore/list.h"
49#include "MagickCore/memory_.h"
50#include "MagickCore/memory-private.h"
51#include "MagickCore/monitor.h"
52#include "MagickCore/monitor-private.h"
53#include "MagickCore/property.h"
54#include "MagickCore/quantum-private.h"
55#include "MagickCore/registry.h"
56#include "MagickCore/semaphore.h"
57#include "MagickCore/signature-private.h"
58#include "MagickCore/splay-tree.h"
59#include "MagickCore/statistic.h"
60#include "MagickCore/string_.h"
61#include "MagickCore/timer-private.h"
62␌
63#if defined(MAGICKCORE_CIPHER_SUPPORT)
64/*
65 Define declarations.
66*/
67#define AESBlocksize 16
68#define AESKeyWords 60 /* 4*(14+1): worst case, AES-256 */
69␌
70/*
71 Typedef declarations.
72*/
73typedef struct _AESInfo
74{
75 StringInfo
76 *key;
77
78 unsigned int
79 blocksize,
80 *encipher_key;
81
82 ssize_t
83 rounds;
84
85 time_t
86 timestamp;
87
88 size_t
89 signature;
90} AESInfo;
91␌
92/*
93 Global declarations.
94*/
95static const unsigned char
96 SBox[256] =
97 {
98 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215,
99 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175,
100 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165,
101 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154,
102 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110,
103 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237,
104 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239,
105 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168,
106 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255,
107 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61,
108 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238,
109 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92,
110 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213,
111 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46,
112 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62,
113 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158,
114 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85,
115 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15,
116 176, 84, 187, 22
117 };
118␌
119/*
120 Forward declarations.
121*/
122static AESInfo
123 *DestroyAESInfo(AESInfo *);
124
125static void
126 EncipherAESBlock(AESInfo *,const unsigned char *,unsigned char *),
127 SetAESKey(AESInfo *,const StringInfo *);
128␌
129/*
130%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
131% %
132% %
133% %
134% A c q u i r e A E S I n f o %
135% %
136% %
137% %
138%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
139%
140% AcquireAESInfo() allocate the AESInfo structure.
141%
142% The format of the AcquireAESInfo method is:
143%
144% AESInfo *AcquireAESInfo(void)
145%
146*/
147static AESInfo *AcquireAESInfo(void)
148{
149 AESInfo
150 *aes_info;
151
152 aes_info=(AESInfo *) AcquireCriticalMemory(sizeof(*aes_info));
153 (void) memset(aes_info,0,sizeof(*aes_info));
154 aes_info->blocksize=AESBlocksize;
155 aes_info->key=AcquireStringInfo(32);
156 aes_info->encipher_key=(unsigned int *) AcquireQuantumMemory(AESKeyWords,
157 sizeof(*aes_info->encipher_key));
158 if ((aes_info->key == (StringInfo *) NULL) ||
159 (aes_info->encipher_key == (unsigned int *) NULL))
160 ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
161 (void) memset(aes_info->encipher_key,0,AESKeyWords*
162 sizeof(*aes_info->encipher_key));
163 aes_info->timestamp=GetMagickTime();
164 aes_info->signature=MagickCoreSignature;
165 return(aes_info);
166}
167␌
168/*
169%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
170% %
171% %
172% %
173% D e s t r o y A E S I n f o %
174% %
175% %
176% %
177%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
178%
179% DestroyAESInfo() zeros memory associated with the AESInfo structure.
180%
181% The format of the DestroyAESInfo method is:
182%
183% AESInfo *DestroyAESInfo(AESInfo *aes_info)
184%
185% A description of each parameter follows:
186%
187% o aes_info: the cipher context.
188%
189*/
190
191static inline void SecureZero(void *memory,const size_t length)
192{
193 volatile unsigned char
194 *p;
195
196 size_t
197 i;
198
199 /*
200 Securely wipe sensitive memory.
201 */
202 p=(volatile unsigned char *) memory;
203 for (i=0; i < length; i++)
204 p[i]=0;
205}
206
207static inline void WipeStringInfo(StringInfo *string_info)
208{
209 if ((string_info != (StringInfo *) NULL) &&
210 (GetStringInfoDatum(string_info) != (unsigned char *) NULL))
211 SecureZero(GetStringInfoDatum(string_info),
212 GetStringInfoLength(string_info));
213}
214
215static AESInfo *DestroyAESInfo(AESInfo *aes_info)
216{
217 assert(aes_info != (AESInfo *) NULL);
218 assert(aes_info->signature == MagickCoreSignature);
219 if (IsEventLogging() != MagickFalse)
220 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
221 if (aes_info->encipher_key != (unsigned int *) NULL)
222 {
223 SecureZero(aes_info->encipher_key,AESKeyWords*
224 sizeof(*aes_info->encipher_key));
225 aes_info->encipher_key=(unsigned int *) RelinquishMagickMemory(
226 aes_info->encipher_key);
227 }
228 if (aes_info->key != (StringInfo *) NULL)
229 {
230 WipeStringInfo(aes_info->key);
231 aes_info->key=DestroyStringInfo(aes_info->key);
232 }
233 aes_info->signature=(~MagickCoreSignature);
234 aes_info=(AESInfo *) RelinquishMagickMemory(aes_info);
235 return(aes_info);
236}
237␌
238/*
239%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
240% %
241% %
242% %
243% E n c i p h e r A E S B l o c k %
244% %
245% %
246% %
247%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
248%
249% EncipherAESBlock() enciphers a single block of plaintext to produce a block
250% of ciphertext.
251%
252% The format of the EncipherAESBlock method is:
253%
254% void EncipherAESBlock(AESInfo *aes_info,const unsigned char *plaintext,
255% unsigned char *ciphertext)
256%
257% A description of each parameter follows:
258%
259% o aes_info: the cipher context.
260%
261% o plaintext: the plain text.
262%
263% o ciphertext: the cipher text.
264%
265*/
266
267static inline void AddRoundKey(const unsigned int *ciphertext,
268 const unsigned int *key,unsigned int *plaintext)
269{
270 ssize_t
271 i;
272
273 /*
274 Xor corresponding text input and round key input bytes.
275 */
276 for (i=0; i < 4; i++)
277 plaintext[i]=key[i] ^ ciphertext[i];
278}
279
280static inline unsigned int ByteSubTransform(unsigned int x,
281 const unsigned char *s_box)
282{
283 unsigned int
284 key;
285
286 /*
287 Non-linear layer resists differential and linear cryptoanalysis attacks.
288 */
289 key=((unsigned int) s_box[x & 0xff]) |
290 ((unsigned int) s_box[(x >> 8) & 0xff] << 8) |
291 ((unsigned int) s_box[(x >> 16) & 0xff] << 16) |
292 ((unsigned int) s_box[(x >> 24) & 0xff] << 24);
293 return(key);
294}
295
296static void FinalizeRoundKey(const unsigned int *ciphertext,
297 const unsigned int *key,unsigned char *plaintext)
298{
299 unsigned char
300 *p;
301
302 unsigned int
303 i,
304 j;
305
306 unsigned int
307 value;
308
309 /*
310 The round key is XORed with the result of the mix-column transformation.
311 */
312 p=plaintext;
313 for (i=0; i < 4; i++)
314 {
315 value=ciphertext[i] ^ key[i];
316 for (j=0; j < 4; j++)
317 *p++=(unsigned char) ((value >> (8*j)) & 0xff);
318 }
319 SecureZero(&value,sizeof(value));
320}
321
322static void InitializeRoundKey(const unsigned char *ciphertext,
323 const unsigned int *key,unsigned int *plaintext)
324{
325 const unsigned char
326 *p;
327
328 unsigned int
329 i,
330 j;
331
332 unsigned int
333 value;
334
335 p=ciphertext;
336 for (i=0; i < 4; i++)
337 {
338 value=0;
339 for (j=0; j < 4; j++)
340 value|=((unsigned int) *p++ << (8*j));
341 plaintext[i]=key[i] ^ value;
342 }
343 SecureZero(&value,sizeof(value));
344}
345
346static inline unsigned int RotateLeft(const unsigned int x)
347{
348 return(((x << 8) | ((x >> 24) & 0xff)));
349}
350
351static void EncipherAESBlock(AESInfo *aes_info,const unsigned char *plaintext,
352 unsigned char *ciphertext)
353{
354 ssize_t
355 i,
356 j;
357
358 static const int
359 map[4][4] =
360 {
361 { 0, 1, 2, 3 },
362 { 1, 2, 3, 0 },
363 { 2, 3, 0, 1 },
364 { 3, 0, 1, 2 }
365 };
366
367 static const unsigned int
368 D[] =
369 {
370 0xa56363c6U, 0x847c7cf8U, 0x997777eeU, 0x8d7b7bf6U, 0x0df2f2ffU,
371 0xbd6b6bd6U, 0xb16f6fdeU, 0x54c5c591U, 0x50303060U, 0x03010102U,
372 0xa96767ceU, 0x7d2b2b56U, 0x19fefee7U, 0x62d7d7b5U, 0xe6abab4dU,
373 0x9a7676ecU, 0x45caca8fU, 0x9d82821fU, 0x40c9c989U, 0x877d7dfaU,
374 0x15fafaefU, 0xeb5959b2U, 0xc947478eU, 0x0bf0f0fbU, 0xecadad41U,
375 0x67d4d4b3U, 0xfda2a25fU, 0xeaafaf45U, 0xbf9c9c23U, 0xf7a4a453U,
376 0x967272e4U, 0x5bc0c09bU, 0xc2b7b775U, 0x1cfdfde1U, 0xae93933dU,
377 0x6a26264cU, 0x5a36366cU, 0x413f3f7eU, 0x02f7f7f5U, 0x4fcccc83U,
378 0x5c343468U, 0xf4a5a551U, 0x34e5e5d1U, 0x08f1f1f9U, 0x937171e2U,
379 0x73d8d8abU, 0x53313162U, 0x3f15152aU, 0x0c040408U, 0x52c7c795U,
380 0x65232346U, 0x5ec3c39dU, 0x28181830U, 0xa1969637U, 0x0f05050aU,
381 0xb59a9a2fU, 0x0907070eU, 0x36121224U, 0x9b80801bU, 0x3de2e2dfU,
382 0x26ebebcdU, 0x6927274eU, 0xcdb2b27fU, 0x9f7575eaU, 0x1b090912U,
383 0x9e83831dU, 0x742c2c58U, 0x2e1a1a34U, 0x2d1b1b36U, 0xb26e6edcU,
384 0xee5a5ab4U, 0xfba0a05bU, 0xf65252a4U, 0x4d3b3b76U, 0x61d6d6b7U,
385 0xceb3b37dU, 0x7b292952U, 0x3ee3e3ddU, 0x712f2f5eU, 0x97848413U,
386 0xf55353a6U, 0x68d1d1b9U, 0x00000000U, 0x2cededc1U, 0x60202040U,
387 0x1ffcfce3U, 0xc8b1b179U, 0xed5b5bb6U, 0xbe6a6ad4U, 0x46cbcb8dU,
388 0xd9bebe67U, 0x4b393972U, 0xde4a4a94U, 0xd44c4c98U, 0xe85858b0U,
389 0x4acfcf85U, 0x6bd0d0bbU, 0x2aefefc5U, 0xe5aaaa4fU, 0x16fbfbedU,
390 0xc5434386U, 0xd74d4d9aU, 0x55333366U, 0x94858511U, 0xcf45458aU,
391 0x10f9f9e9U, 0x06020204U, 0x817f7ffeU, 0xf05050a0U, 0x443c3c78U,
392 0xba9f9f25U, 0xe3a8a84bU, 0xf35151a2U, 0xfea3a35dU, 0xc0404080U,
393 0x8a8f8f05U, 0xad92923fU, 0xbc9d9d21U, 0x48383870U, 0x04f5f5f1U,
394 0xdfbcbc63U, 0xc1b6b677U, 0x75dadaafU, 0x63212142U, 0x30101020U,
395 0x1affffe5U, 0x0ef3f3fdU, 0x6dd2d2bfU, 0x4ccdcd81U, 0x140c0c18U,
396 0x35131326U, 0x2fececc3U, 0xe15f5fbeU, 0xa2979735U, 0xcc444488U,
397 0x3917172eU, 0x57c4c493U, 0xf2a7a755U, 0x827e7efcU, 0x473d3d7aU,
398 0xac6464c8U, 0xe75d5dbaU, 0x2b191932U, 0x957373e6U, 0xa06060c0U,
399 0x98818119U, 0xd14f4f9eU, 0x7fdcdca3U, 0x66222244U, 0x7e2a2a54U,
400 0xab90903bU, 0x8388880bU, 0xca46468cU, 0x29eeeec7U, 0xd3b8b86bU,
401 0x3c141428U, 0x79dedea7U, 0xe25e5ebcU, 0x1d0b0b16U, 0x76dbdbadU,
402 0x3be0e0dbU, 0x56323264U, 0x4e3a3a74U, 0x1e0a0a14U, 0xdb494992U,
403 0x0a06060cU, 0x6c242448U, 0xe45c5cb8U, 0x5dc2c29fU, 0x6ed3d3bdU,
404 0xefacac43U, 0xa66262c4U, 0xa8919139U, 0xa4959531U, 0x37e4e4d3U,
405 0x8b7979f2U, 0x32e7e7d5U, 0x43c8c88bU, 0x5937376eU, 0xb76d6ddaU,
406 0x8c8d8d01U, 0x64d5d5b1U, 0xd24e4e9cU, 0xe0a9a949U, 0xb46c6cd8U,
407 0xfa5656acU, 0x07f4f4f3U, 0x25eaeacfU, 0xaf6565caU, 0x8e7a7af4U,
408 0xe9aeae47U, 0x18080810U, 0xd5baba6fU, 0x887878f0U, 0x6f25254aU,
409 0x722e2e5cU, 0x241c1c38U, 0xf1a6a657U, 0xc7b4b473U, 0x51c6c697U,
410 0x23e8e8cbU, 0x7cdddda1U, 0x9c7474e8U, 0x211f1f3eU, 0xdd4b4b96U,
411 0xdcbdbd61U, 0x868b8b0dU, 0x858a8a0fU, 0x907070e0U, 0x423e3e7cU,
412 0xc4b5b571U, 0xaa6666ccU, 0xd8484890U, 0x05030306U, 0x01f6f6f7U,
413 0x120e0e1cU, 0xa36161c2U, 0x5f35356aU, 0xf95757aeU, 0xd0b9b969U,
414 0x91868617U, 0x58c1c199U, 0x271d1d3aU, 0xb99e9e27U, 0x38e1e1d9U,
415 0x13f8f8ebU, 0xb398982bU, 0x33111122U, 0xbb6969d2U, 0x70d9d9a9U,
416 0x898e8e07U, 0xa7949433U, 0xb69b9b2dU, 0x221e1e3cU, 0x92878715U,
417 0x20e9e9c9U, 0x49cece87U, 0xff5555aaU, 0x78282850U, 0x7adfdfa5U,
418 0x8f8c8c03U, 0xf8a1a159U, 0x80898909U, 0x170d0d1aU, 0xdabfbf65U,
419 0x31e6e6d7U, 0xc6424284U, 0xb86868d0U, 0xc3414182U, 0xb0999929U,
420 0x772d2d5aU, 0x110f0f1eU, 0xcbb0b07bU, 0xfc5454a8U, 0xd6bbbb6dU,
421 0x3a16162cU
422 };
423
424 unsigned int
425 alpha,
426 key[4],
427 text[4];
428
429 /*
430 Encipher one block.
431 */
432 (void) memset(text,0,sizeof(text));
433 InitializeRoundKey(plaintext,aes_info->encipher_key,text);
434 for (i=1; i < aes_info->rounds; i++)
435 {
436 for (j=0; j < 4; j++)
437 key[j]=D[text[j] & 0xff] ^
438 RotateLeft(D[(text[map[1][j]] >> 8) & 0xff] ^
439 RotateLeft(D[(text[map[2][j]] >> 16) & 0xff] ^
440 RotateLeft(D[(text[map[3][j]] >> 24) & 0xff])));
441 AddRoundKey(key,aes_info->encipher_key+4*i,text);
442 }
443 for (i=0; i < 4; i++)
444 {
445 alpha=(text[i] & 0x000000ff) | ((text[map[1][i]]) & 0x0000ff00) |
446 ((text[map[2][i]]) & 0x00ff0000) | ((text[map[3][i]]) & 0xff000000);
447 key[i]=ByteSubTransform(alpha,SBox);
448 }
449 FinalizeRoundKey(key,aes_info->encipher_key+4*aes_info->rounds,ciphertext);
450 SecureZero(&alpha,sizeof(alpha));
451 SecureZero(key,sizeof(key));
452 SecureZero(text,sizeof(text));
453}
454␌
455/*
456%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
457% %
458% %
459% %
460% C i p h e r I m a g e %
461% %
462% %
463% %
464%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
465%
466% The cipher is AES in counter (CTR) mode applied to the exported quantum
467% pixel rows. Enciphering and deciphering are the same keystream XOR, so both
468% public entry points share the implementation below.
469%
470%
471*/
472
473static inline MagickBooleanType IncrementCipherNonce(const size_t length,
474 unsigned char *nonce)
475{
476 ssize_t
477 i;
478
479 for (i=(ssize_t) (length-1); i >= 0; i--)
480 {
481 nonce[i]++;
482 if (nonce[i] != 0)
483 return(MagickTrue);
484 }
485 return(MagickFalse);
486}
487
488static void DeriveCipherCounter(const Image *image,StringInfo *nonce,
489 unsigned char *counter,char **hex_digest)
490{
491 MagickSizeType
492 extent;
493
494 SignatureInfo
495 *signature_info;
496
497 size_t
498 i;
499
500 unsigned char
501 extent_bytes[sizeof(extent)];
502
503 /*
504 The initial counter block is the leading bytes of SHA-256(nonce ||
505 columns*rows). The extent is serialized little-endian explicitly so the
506 result no longer depends on host byte order.
507 */
508 signature_info=AcquireSignatureInfo();
509 UpdateSignature(signature_info,nonce);
510 extent=(MagickSizeType) image->columns*image->rows;
511 for (i=0; i < sizeof(extent_bytes); i++)
512 extent_bytes[i]=(unsigned char) ((extent >> (8*i)) & 0xff);
513 WipeStringInfo(nonce);
514 SetStringInfoLength(nonce,sizeof(extent_bytes));
515 SetStringInfoDatum(nonce,extent_bytes);
516 UpdateSignature(signature_info,nonce);
517 FinalizeSignature(signature_info);
518 if (hex_digest != (char **) NULL)
519 *hex_digest=StringInfoToHexString(GetSignatureDigest(signature_info));
520 (void) memset(counter,0,AESBlocksize);
521 (void) memcpy(counter,GetStringInfoDatum(GetSignatureDigest(signature_info)),
522 MagickMin(AESBlocksize,GetSignatureDigestsize(signature_info)));
523 signature_info=DestroySignatureInfo(signature_info);
524}
525
526static MagickBooleanType XORCipherKeystream(AESInfo *aes_info,
527 unsigned char *counter,unsigned char *pixels,const size_t length)
528{
529 size_t
530 i,
531 x;
532
533 unsigned char
534 keystream[AESBlocksize];
535
536 /*
537 XOR exactly `length' bytes with the keystream. A trailing partial block
538 consumes one counter value and never touches bytes past `length'.
539 */
540 for (x=0; x < length; x+=AESBlocksize)
541 {
542 size_t
543 count;
544
545 count=MagickMin((size_t) AESBlocksize,length-x);
546 (void) memcpy(keystream,counter,AESBlocksize);
547 if (IncrementCipherNonce(AESBlocksize,counter) == MagickFalse)
548 {
549 SecureZero(keystream,sizeof(keystream));
550 return(MagickFalse);
551 }
552 EncipherAESBlock(aes_info,keystream,keystream);
553 for (i=0; i < count; i++)
554 pixels[x+i]^=keystream[i];
555 }
556 SecureZero(keystream,sizeof(keystream));
557 return(MagickTrue);
558}
559
560static MagickBooleanType CipherImage(Image *image,const StringInfo *passkey,
561 const MagickBooleanType encipher,ExceptionInfo *exception)
562{
563 AESInfo
564 *aes_info;
565
566 CacheView
567 *image_view;
568
569 char
570 *signature;
571
572 const char
573 *progress_tag;
574
575 MagickBooleanType
576 status;
577
578 QuantumInfo
579 *quantum_info;
580
581 QuantumType
582 quantum_type;
583
584 ssize_t
585 y;
586
587 StringInfo
588 *key,
589 *nonce;
590
591 unsigned char
592 counter[AESBlocksize],
593 *pixels;
594
595 if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
596 return(MagickFalse);
597 aes_info=AcquireAESInfo();
598 key=CloneStringInfo(passkey);
599 if (key == (StringInfo *) NULL)
600 {
601 aes_info=DestroyAESInfo(aes_info);
602 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
603 image->filename);
604 }
605 nonce=SplitStringInfo(key,GetStringInfoLength(key)/2);
606 if (nonce == (StringInfo *) NULL)
607 {
608 WipeStringInfo(key);
609 key=DestroyStringInfo(key);
610 aes_info=DestroyAESInfo(aes_info);
611 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
612 image->filename);
613 }
614 SetAESKey(aes_info,key);
615 WipeStringInfo(key);
616 key=DestroyStringInfo(key);
617 signature=(char *) NULL;
618 DeriveCipherCounter(image,nonce,counter,
619 encipher != MagickFalse ? &signature : (char **) NULL);
620 nonce=DestroyStringInfo(nonce);
621 if (signature != (char *) NULL)
622 {
623 (void) SetImageProperty(image,"cipher:type","AES",exception);
624 (void) SetImageProperty(image,"cipher:mode","CTR",exception);
625 (void) SetImageProperty(image,"cipher:nonce",signature,exception);
626 signature=DestroyString(signature);
627 }
628 quantum_info=AcquireQuantumInfo((const ImageInfo *) NULL,image);
629 if (quantum_info == (QuantumInfo *) NULL)
630 {
631 aes_info=DestroyAESInfo(aes_info);
632 SecureZero(counter,sizeof(counter));
633 ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
634 image->filename);
635 }
636 progress_tag=encipher != MagickFalse ? "Encipher/Image " : "Decipher/Image ";
637 quantum_type=GetQuantumType(image,exception);
638 pixels=(unsigned char *) GetQuantumPixels(quantum_info);
639 status=MagickTrue;
640 image_view=AcquireAuthenticCacheView(image,exception);
641 for (y=0; y < (ssize_t) image->rows; y++)
642 {
643 Quantum
644 *magick_restrict q;
645
646 size_t
647 length;
648
649 q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
650 if (q == (Quantum *) NULL)
651 {
652 status=MagickFalse;
653 break;
654 }
655 length=ExportQuantumPixels(image,image_view,quantum_info,quantum_type,
656 pixels,exception);
657 if (XORCipherKeystream(aes_info,counter,pixels,length) == MagickFalse)
658 {
659 (void) ThrowMagickException(exception,GetMagickModule(),
660 ResourceLimitError,"SequenceWrapError","`%s'",image->filename);
661 status=MagickFalse;
662 break;
663 }
664 (void) ImportQuantumPixels(image,image_view,quantum_info,quantum_type,
665 pixels,exception);
666 if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
667 {
668 status=MagickFalse;
669 break;
670 }
671 if (SetImageProgress(image,progress_tag,(MagickOffsetType) y,
672 image->rows) == MagickFalse)
673 {
674 status=MagickFalse;
675 break;
676 }
677 }
678 image_view=DestroyCacheView(image_view);
679 if (encipher == MagickFalse)
680 {
681 (void) DeleteImageProperty(image,"cipher:type");
682 (void) DeleteImageProperty(image,"cipher:mode");
683 (void) DeleteImageProperty(image,"cipher:nonce");
684 }
685 image->taint=MagickFalse;
686 quantum_info=DestroyQuantumInfo(quantum_info);
687 aes_info=DestroyAESInfo(aes_info);
688 SecureZero(counter,sizeof(counter));
689 return(status);
690}
691
692/*
693%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
694% %
695% %
696% %
697% D e c i p h e r I m a g e %
698% %
699% %
700% %
701%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
702%
703% DecipherImage() converts cipher pixels to plain pixels. The mode is
704% unauthenticated: a wrong passphrase is not detected and yields noise.
705%
706% The format of the DecipherImage method is:
707%
708% MagickBooleanType DecipherImage(Image *image,const char *passphrase,
709% ExceptionInfo *exception)
710%
711% A description of each parameter follows:
712%
713% o image: the image.
714%
715% o passphrase: decipher cipher pixels with this passphrase.
716%
717% o exception: return any errors or warnings in this structure.
718%
719*/
720MagickExport MagickBooleanType DecipherImage(Image *image,
721 const char *passphrase,ExceptionInfo *exception)
722{
723 MagickBooleanType
724 status;
725
726 StringInfo
727 *passkey;
728
729 if (passphrase == (const char *) NULL)
730 return(MagickTrue);
731 passkey=StringToStringInfo(passphrase);
732 if (passkey == (StringInfo *) NULL)
733 return(MagickFalse);
734 status=PasskeyDecipherImage(image,passkey,exception);
735 WipeStringInfo(passkey);
736 passkey=DestroyStringInfo(passkey);
737 return(status);
738}
739
740/*
741%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
742% %
743% %
744% %
745% P a s s k e y D e c i p h e r I m a g e %
746% %
747% %
748% %
749%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
750%
751% PasskeyDecipherImage() converts cipher pixels to plain pixels.
752%
753% The format of the PasskeyDecipherImage method is:
754%
755% MagickBooleanType PasskeyDecipherImage(Image *image,
756% const StringInfo *passkey,ExceptionInfo *exception)
757%
758% A description of each parameter follows:
759%
760% o image: the image.
761%
762% o passkey: decipher cipher pixels with this passkey.
763%
764% o exception: return any errors or warnings in this structure.
765%
766*/
767MagickExport MagickBooleanType PasskeyDecipherImage(Image *image,
768 const StringInfo *passkey,ExceptionInfo *exception)
769{
770 assert(image != (Image *) NULL);
771 assert(image->signature == MagickCoreSignature);
772 assert(exception != (ExceptionInfo *) NULL);
773 assert(exception->signature == MagickCoreSignature);
774 if (IsEventLogging() != MagickFalse)
775 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
776 if (passkey == (const StringInfo *) NULL)
777 return(MagickTrue);
778 return(CipherImage(image,passkey,MagickFalse,exception));
779}
780
781/*
782%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
783% %
784% %
785% %
786% E n c i p h e r I m a g e %
787% %
788% %
789% %
790%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
791%
792% EncipherImage() converts pixels to cipher-pixels.
793%
794% The format of the EncipherImage method is:
795%
796% MagickBooleanType EncipherImage(Image *image,const char *passphrase,
797% ExceptionInfo *exception)
798%
799% A description of each parameter follows:
800%
801% o image: the image.
802%
803% o passphrase: encipher pixels with this passphrase.
804%
805% o exception: return any errors or warnings in this structure.
806%
807*/
808MagickExport MagickBooleanType EncipherImage(Image *image,
809 const char *passphrase,ExceptionInfo *exception)
810{
811 MagickBooleanType
812 status;
813
814 StringInfo
815 *passkey;
816
817 if (passphrase == (const char *) NULL)
818 return(MagickTrue);
819 passkey=StringToStringInfo(passphrase);
820 if (passkey == (StringInfo *) NULL)
821 return(MagickFalse);
822 status=PasskeyEncipherImage(image,passkey,exception);
823 WipeStringInfo(passkey);
824 passkey=DestroyStringInfo(passkey);
825 return(status);
826}
827
828/*
829%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
830% %
831% %
832% %
833% P a s s k e y E n c i p h e r I m a g e %
834% %
835% %
836% %
837%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
838%
839% PasskeyEncipherImage() converts pixels to cipher-pixels. The passkey must
840% be at least two bytes long (it is split in two halves); shorter passkeys
841% would produce an empty, all-zero AES key and are rejected.
842%
843% The format of the PasskeyEncipherImage method is:
844%
845% MagickBooleanType PasskeyEncipherImage(Image *image,
846% const StringInfo *passkey,ExceptionInfo *exception)
847%
848% A description of each parameter follows:
849%
850% o image: the image.
851%
852% o passkey: encipher pixels with this passkey.
853%
854% o exception: return any errors or warnings in this structure.
855%
856*/
857MagickExport MagickBooleanType PasskeyEncipherImage(Image *image,
858 const StringInfo *passkey,ExceptionInfo *exception)
859{
860 assert(image != (Image *) NULL);
861 assert(image->signature == MagickCoreSignature);
862 assert(exception != (ExceptionInfo *) NULL);
863 assert(exception->signature == MagickCoreSignature);
864 if (IsEventLogging() != MagickFalse)
865 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
866 if (passkey == (const StringInfo *) NULL)
867 return(MagickTrue);
868 if (GetStringInfoLength(passkey) < 2)
869 ThrowBinaryException(OptionError,"PassphraseTooShort",image->filename);
870 return(CipherImage(image,passkey,MagickTrue,exception));
871}
872
873/*
874%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
875% %
876% %
877% %
878% S e t A E S K e y %
879% %
880% %
881% %
882%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
883%
884% SetAESKey() sets the key for the AES cipher. Only the encryption key
885% schedule is built: CTR mode never runs the inverse cipher.
886%
887*/
888
889static inline unsigned int XTime(unsigned char alpha)
890{
891 unsigned char
892 beta;
893
894 beta=(unsigned char) ((alpha & 0x80) != 0 ? 0x1b : 0);
895 alpha<<=1;
896 alpha^=beta;
897 return(alpha);
898}
899
900static inline unsigned int RotateRight(const unsigned int x)
901{
902 return((x >> 8) | ((x & 0xff) << 24));
903}
904
905static void SetAESKey(AESInfo *aes_info,const StringInfo *key)
906{
907 ssize_t
908 words,
909 i,
910 n;
911
912 unsigned char
913 *datum;
914
915 unsigned int
916 alpha,
917 beta;
918
919 assert(aes_info != (AESInfo *) NULL);
920 assert(aes_info->signature == MagickCoreSignature);
921 assert(key != (StringInfo *) NULL);
922 if (IsEventLogging() != MagickFalse)
923 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
924 n=4;
925 aes_info->rounds=10;
926 if ((8*GetStringInfoLength(key)) >= 256)
927 {
928 n=8;
929 aes_info->rounds=14;
930 }
931 else
932 if ((8*GetStringInfoLength(key)) >= 192)
933 {
934 n=6;
935 aes_info->rounds=12;
936 }
937
938 datum=GetStringInfoDatum(aes_info->key);
939 (void) memset(datum,0,GetStringInfoLength(aes_info->key));
940 (void) memcpy(datum,GetStringInfoDatum(key),MagickMin(
941 GetStringInfoLength(key),GetStringInfoLength(aes_info->key)));
942 for (i=0; i < n; i++)
943 aes_info->encipher_key[i]=(unsigned int) datum[4*i] |
944 ((unsigned int) datum[4*i+1] << 8) |
945 ((unsigned int) datum[4*i+2] << 16) |
946 ((unsigned int) datum[4*i+3] << 24);
947 beta=1;
948 words=(AESBlocksize/4)*(aes_info->rounds+1);
949 for (i=n; i < words; i++)
950 {
951 alpha=aes_info->encipher_key[i-1];
952 if ((i % n) == 0)
953 {
954 alpha=ByteSubTransform(RotateRight(alpha),SBox) ^ beta;
955 beta=XTime((unsigned char) (beta & 0xff));
956 }
957 else
958 if ((n > 6) && ((i % n) == 4))
959 alpha=ByteSubTransform(alpha,SBox);
960 aes_info->encipher_key[i]=aes_info->encipher_key[i-n] ^ alpha;
961 }
962 datum=GetStringInfoDatum(aes_info->key);
963 (void) memset(datum,0,GetStringInfoLength(aes_info->key));
964 SecureZero(&alpha,sizeof(alpha));
965 SecureZero(&beta,sizeof(beta));
966}
967#else
968␌
969/*
970 Disabled cipher support fallback stubs.
971*/
972MagickExport MagickBooleanType DecipherImage(Image *image,
973 const char *passphrase,ExceptionInfo *exception)
974{
975 assert(image != (Image *) NULL);
976 assert(image->signature == MagickCoreSignature);
977 assert(exception != (ExceptionInfo *) NULL);
978 assert(exception->signature == MagickCoreSignature);
979 if (IsEventLogging() != MagickFalse)
980 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
981 (void) passphrase;
982 ThrowBinaryException(ImageError,"CipherSupportNotEnabled",image->filename);
983}
984
985MagickExport MagickBooleanType PasskeyDecipherImage(Image *image,
986 const StringInfo *passkey,ExceptionInfo *exception)
987{
988 assert(image != (Image *) NULL);
989 assert(image->signature == MagickCoreSignature);
990 assert(exception != (ExceptionInfo *) NULL);
991 assert(exception->signature == MagickCoreSignature);
992 if (IsEventLogging() != MagickFalse)
993 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
994 (void) passkey;
995 ThrowBinaryException(ImageError,"CipherSupportNotEnabled",image->filename);
996}
997
998MagickExport MagickBooleanType EncipherImage(Image *image,
999 const char *passphrase,ExceptionInfo *exception)
1000{
1001 assert(image != (Image *) NULL);
1002 assert(image->signature == MagickCoreSignature);
1003 assert(exception != (ExceptionInfo *) NULL);
1004 assert(exception->signature == MagickCoreSignature);
1005 if (IsEventLogging() != MagickFalse)
1006 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1007 (void) passphrase;
1008 ThrowBinaryException(ImageError,"CipherSupportNotEnabled",image->filename);
1009}
1010
1011MagickExport MagickBooleanType PasskeyEncipherImage(Image *image,
1012 const StringInfo *passkey,ExceptionInfo *exception)
1013{
1014 assert(image != (Image *) NULL);
1015 assert(image->signature == MagickCoreSignature);
1016 assert(exception != (ExceptionInfo *) NULL);
1017 assert(exception->signature == MagickCoreSignature);
1018 if (IsEventLogging() != MagickFalse)
1019 (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
1020 (void) passkey;
1021 ThrowBinaryException(ImageError,"CipherSupportNotEnabled",image->filename);
1022}
1023#endif