197e1b3998017883860bd9eb89d7d88c0c7a4d78
[libgcrypt.git] / cipher / camellia-glue.c
1 /* camellia-glue.c - Glue for the Camellia cipher
2  * Copyright (C) 2007 Free Software Foundation, Inc.
3  *
4  * This file is part of Libgcrypt.
5  *
6  * Libgcrypt is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2.1 of
9  * the License, or (at your option) any later version.
10  *
11  * Libgcrypt is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19  * 02110-1301, USA.
20  */
21
22 /* I put all the libgcrypt-specific stuff in this file to keep the
23    camellia.c/camellia.h files exactly as provided by NTT.  If they
24    update their code, this should make it easier to bring the changes
25    in. - dshaw
26
27    There is one small change which needs to be done: Include the
28    following code at the top of camellia.h: */
29 #if 0
30
31 /* To use Camellia with libraries it is often useful to keep the name
32  * space of the library clean.  The following macro is thus useful:
33  *
34  *     #define CAMELLIA_EXT_SYM_PREFIX foo_
35  *
36  * This prefixes all external symbols with "foo_".
37  */
38 #ifdef HAVE_CONFIG_H
39 #include <config.h>
40 #endif
41 #ifdef CAMELLIA_EXT_SYM_PREFIX
42 #define CAMELLIA_PREFIX1(x,y) x ## y
43 #define CAMELLIA_PREFIX2(x,y) CAMELLIA_PREFIX1(x,y)
44 #define CAMELLIA_PREFIX(x)    CAMELLIA_PREFIX2(CAMELLIA_EXT_SYM_PREFIX,x)
45 #define Camellia_Ekeygen      CAMELLIA_PREFIX(Camellia_Ekeygen)
46 #define Camellia_EncryptBlock CAMELLIA_PREFIX(Camellia_EncryptBlock)
47 #define Camellia_DecryptBlock CAMELLIA_PREFIX(Camellia_DecryptBlock)
48 #define camellia_decrypt128   CAMELLIA_PREFIX(camellia_decrypt128)
49 #define camellia_decrypt256   CAMELLIA_PREFIX(camellia_decrypt256)
50 #define camellia_encrypt128   CAMELLIA_PREFIX(camellia_encrypt128)
51 #define camellia_encrypt256   CAMELLIA_PREFIX(camellia_encrypt256)
52 #define camellia_setup128     CAMELLIA_PREFIX(camellia_setup128)
53 #define camellia_setup192     CAMELLIA_PREFIX(camellia_setup192)
54 #define camellia_setup256     CAMELLIA_PREFIX(camellia_setup256)
55 #endif /*CAMELLIA_EXT_SYM_PREFIX*/
56
57 #endif /* Code sample. */
58
59
60 #include <config.h>
61 #include "types.h"
62 #include "g10lib.h"
63 #include "cipher.h"
64 #include "camellia.h"
65 #include "bufhelp.h"
66 #include "cipher-internal.h"
67 #include "cipher-selftest.h"
68
69 /* Helper macro to force alignment to 16 bytes.  */
70 #ifdef HAVE_GCC_ATTRIBUTE_ALIGNED
71 # define ATTR_ALIGNED_16  __attribute__ ((aligned (16)))
72 #else
73 # define ATTR_ALIGNED_16
74 #endif
75
76 /* USE_AESNI inidicates whether to compile with Intel AES-NI/AVX code. */
77 #undef USE_AESNI_AVX
78 #if defined(ENABLE_AESNI_SUPPORT) && defined(ENABLE_AVX_SUPPORT)
79 # if defined(__x86_64__) && (defined(HAVE_COMPATIBLE_GCC_AMD64_PLATFORM_AS) || \
80      defined(HAVE_COMPATIBLE_GCC_WIN64_PLATFORM_AS))
81 #  define USE_AESNI_AVX 1
82 # endif
83 #endif
84
85 /* USE_AESNI_AVX2 inidicates whether to compile with Intel AES-NI/AVX2 code. */
86 #undef USE_AESNI_AVX2
87 #if defined(ENABLE_AESNI_SUPPORT) && defined(ENABLE_AVX2_SUPPORT)
88 # if defined(__x86_64__) && (defined(HAVE_COMPATIBLE_GCC_AMD64_PLATFORM_AS) || \
89      defined(HAVE_COMPATIBLE_GCC_WIN64_PLATFORM_AS))
90 #  define USE_AESNI_AVX2 1
91 # endif
92 #endif
93
94 typedef struct
95 {
96   KEY_TABLE_TYPE keytable;
97   int keybitlength;
98 #ifdef USE_AESNI_AVX
99   unsigned int use_aesni_avx:1; /* AES-NI/AVX implementation shall be used.  */
100 #endif /*USE_AESNI_AVX*/
101 #ifdef USE_AESNI_AVX2
102   unsigned int use_aesni_avx2:1;/* AES-NI/AVX2 implementation shall be used.  */
103 #endif /*USE_AESNI_AVX2*/
104 } CAMELLIA_context;
105
106 /* Assembly implementations use SystemV ABI, ABI conversion and additional
107  * stack to store XMM6-XMM15 needed on Win64. */
108 #undef ASM_FUNC_ABI
109 #undef ASM_EXTRA_STACK
110 #if defined(USE_AESNI_AVX) || defined(USE_AESNI_AVX2)
111 # ifdef HAVE_COMPATIBLE_GCC_WIN64_PLATFORM_AS
112 #  define ASM_FUNC_ABI __attribute__((sysv_abi))
113 #  define ASM_EXTRA_STACK (10 * 16)
114 # else
115 #  define ASM_FUNC_ABI
116 #  define ASM_EXTRA_STACK 0
117 # endif
118 #endif
119
120 #ifdef USE_AESNI_AVX
121 /* Assembler implementations of Camellia using AES-NI and AVX.  Process data
122    in 16 block same time.
123  */
124 extern void _gcry_camellia_aesni_avx_ctr_enc(CAMELLIA_context *ctx,
125                                              unsigned char *out,
126                                              const unsigned char *in,
127                                              unsigned char *ctr) ASM_FUNC_ABI;
128
129 extern void _gcry_camellia_aesni_avx_cbc_dec(CAMELLIA_context *ctx,
130                                              unsigned char *out,
131                                              const unsigned char *in,
132                                              unsigned char *iv) ASM_FUNC_ABI;
133
134 extern void _gcry_camellia_aesni_avx_cfb_dec(CAMELLIA_context *ctx,
135                                              unsigned char *out,
136                                              const unsigned char *in,
137                                              unsigned char *iv) ASM_FUNC_ABI;
138
139 extern void _gcry_camellia_aesni_avx_ocb_enc(CAMELLIA_context *ctx,
140                                              unsigned char *out,
141                                              const unsigned char *in,
142                                              unsigned char *offset,
143                                              unsigned char *checksum,
144                                              const void *Ls[16]) ASM_FUNC_ABI;
145
146 extern void _gcry_camellia_aesni_avx_ocb_dec(CAMELLIA_context *ctx,
147                                              unsigned char *out,
148                                              const unsigned char *in,
149                                              unsigned char *offset,
150                                              unsigned char *checksum,
151                                              const void *Ls[16]) ASM_FUNC_ABI;
152
153 extern void _gcry_camellia_aesni_avx_ocb_auth(CAMELLIA_context *ctx,
154                                              const unsigned char *abuf,
155                                              unsigned char *offset,
156                                              unsigned char *checksum,
157                                              const void *Ls[16]) ASM_FUNC_ABI;
158
159 extern void _gcry_camellia_aesni_avx_keygen(CAMELLIA_context *ctx,
160                                             const unsigned char *key,
161                                             unsigned int keylen) ASM_FUNC_ABI;
162 #endif
163
164 #ifdef USE_AESNI_AVX2
165 /* Assembler implementations of Camellia using AES-NI and AVX2.  Process data
166    in 32 block same time.
167  */
168 extern void _gcry_camellia_aesni_avx2_ctr_enc(CAMELLIA_context *ctx,
169                                               unsigned char *out,
170                                               const unsigned char *in,
171                                               unsigned char *ctr) ASM_FUNC_ABI;
172
173 extern void _gcry_camellia_aesni_avx2_cbc_dec(CAMELLIA_context *ctx,
174                                               unsigned char *out,
175                                               const unsigned char *in,
176                                               unsigned char *iv) ASM_FUNC_ABI;
177
178 extern void _gcry_camellia_aesni_avx2_cfb_dec(CAMELLIA_context *ctx,
179                                               unsigned char *out,
180                                               const unsigned char *in,
181                                               unsigned char *iv) ASM_FUNC_ABI;
182
183 extern void _gcry_camellia_aesni_avx2_ocb_enc(CAMELLIA_context *ctx,
184                                               unsigned char *out,
185                                               const unsigned char *in,
186                                               unsigned char *offset,
187                                               unsigned char *checksum,
188                                               const void *Ls[32]) ASM_FUNC_ABI;
189
190 extern void _gcry_camellia_aesni_avx2_ocb_dec(CAMELLIA_context *ctx,
191                                               unsigned char *out,
192                                               const unsigned char *in,
193                                               unsigned char *offset,
194                                               unsigned char *checksum,
195                                               const void *Ls[32]) ASM_FUNC_ABI;
196
197 extern void _gcry_camellia_aesni_avx2_ocb_auth(CAMELLIA_context *ctx,
198                                                const unsigned char *abuf,
199                                                unsigned char *offset,
200                                                unsigned char *checksum,
201                                                const void *Ls[32]) ASM_FUNC_ABI;
202 #endif
203
204 static const char *selftest(void);
205
206 static gcry_err_code_t
207 camellia_setkey(void *c, const byte *key, unsigned keylen)
208 {
209   CAMELLIA_context *ctx=c;
210   static int initialized=0;
211   static const char *selftest_failed=NULL;
212 #if defined(USE_AESNI_AVX) || defined(USE_AESNI_AVX2)
213   unsigned int hwf = _gcry_get_hw_features ();
214 #endif
215
216   if(keylen!=16 && keylen!=24 && keylen!=32)
217     return GPG_ERR_INV_KEYLEN;
218
219   if(!initialized)
220     {
221       initialized=1;
222       selftest_failed=selftest();
223       if(selftest_failed)
224         log_error("%s\n",selftest_failed);
225     }
226
227   if(selftest_failed)
228     return GPG_ERR_SELFTEST_FAILED;
229
230 #ifdef USE_AESNI_AVX
231   ctx->use_aesni_avx = (hwf & HWF_INTEL_AESNI) && (hwf & HWF_INTEL_AVX);
232 #endif
233 #ifdef USE_AESNI_AVX2
234   ctx->use_aesni_avx2 = (hwf & HWF_INTEL_AESNI) && (hwf & HWF_INTEL_AVX2);
235 #endif
236
237   ctx->keybitlength=keylen*8;
238
239   if (0)
240     { }
241 #ifdef USE_AESNI_AVX
242   else if (ctx->use_aesni_avx)
243     _gcry_camellia_aesni_avx_keygen(ctx, key, keylen);
244   else
245 #endif
246     {
247       Camellia_Ekeygen(ctx->keybitlength,key,ctx->keytable);
248       _gcry_burn_stack
249         ((19+34+34)*sizeof(u32)+2*sizeof(void*) /* camellia_setup256 */
250          +(4+32)*sizeof(u32)+2*sizeof(void*)    /* camellia_setup192 */
251          +0+sizeof(int)+2*sizeof(void*)         /* Camellia_Ekeygen */
252          +3*2*sizeof(void*)                     /* Function calls.  */
253          );
254     }
255
256   return 0;
257 }
258
259 #ifdef USE_ARM_ASM
260
261 /* Assembly implementations of Camellia. */
262 extern void _gcry_camellia_arm_encrypt_block(const KEY_TABLE_TYPE keyTable,
263                                                byte *outbuf, const byte *inbuf,
264                                                const int keybits);
265
266 extern void _gcry_camellia_arm_decrypt_block(const KEY_TABLE_TYPE keyTable,
267                                                byte *outbuf, const byte *inbuf,
268                                                const int keybits);
269
270 static void Camellia_EncryptBlock(const int keyBitLength,
271                                   const unsigned char *plaintext,
272                                   const KEY_TABLE_TYPE keyTable,
273                                   unsigned char *cipherText)
274 {
275   _gcry_camellia_arm_encrypt_block(keyTable, cipherText, plaintext,
276                                      keyBitLength);
277 }
278
279 static void Camellia_DecryptBlock(const int keyBitLength,
280                                   const unsigned char *cipherText,
281                                   const KEY_TABLE_TYPE keyTable,
282                                   unsigned char *plaintext)
283 {
284   _gcry_camellia_arm_decrypt_block(keyTable, plaintext, cipherText,
285                                      keyBitLength);
286 }
287
288 static unsigned int
289 camellia_encrypt(void *c, byte *outbuf, const byte *inbuf)
290 {
291   CAMELLIA_context *ctx = c;
292   Camellia_EncryptBlock(ctx->keybitlength,inbuf,ctx->keytable,outbuf);
293 #define CAMELLIA_encrypt_stack_burn_size (15*4)
294   return /*burn_stack*/ (CAMELLIA_encrypt_stack_burn_size);
295 }
296
297 static unsigned int
298 camellia_decrypt(void *c, byte *outbuf, const byte *inbuf)
299 {
300   CAMELLIA_context *ctx=c;
301   Camellia_DecryptBlock(ctx->keybitlength,inbuf,ctx->keytable,outbuf);
302 #define CAMELLIA_decrypt_stack_burn_size (15*4)
303   return /*burn_stack*/ (CAMELLIA_decrypt_stack_burn_size);
304 }
305
306 #else /*USE_ARM_ASM*/
307
308 static unsigned int
309 camellia_encrypt(void *c, byte *outbuf, const byte *inbuf)
310 {
311   CAMELLIA_context *ctx=c;
312
313   Camellia_EncryptBlock(ctx->keybitlength,inbuf,ctx->keytable,outbuf);
314
315 #define CAMELLIA_encrypt_stack_burn_size \
316   (sizeof(int)+2*sizeof(unsigned char *)+sizeof(void*/*KEY_TABLE_TYPE*/) \
317      +4*sizeof(u32)+4*sizeof(u32) \
318      +2*sizeof(u32*)+4*sizeof(u32) \
319      +2*2*sizeof(void*) /* Function calls.  */ \
320     )
321
322   return /*burn_stack*/ (CAMELLIA_encrypt_stack_burn_size);
323 }
324
325 static unsigned int
326 camellia_decrypt(void *c, byte *outbuf, const byte *inbuf)
327 {
328   CAMELLIA_context *ctx=c;
329
330   Camellia_DecryptBlock(ctx->keybitlength,inbuf,ctx->keytable,outbuf);
331
332 #define CAMELLIA_decrypt_stack_burn_size \
333     (sizeof(int)+2*sizeof(unsigned char *)+sizeof(void*/*KEY_TABLE_TYPE*/) \
334      +4*sizeof(u32)+4*sizeof(u32) \
335      +2*sizeof(u32*)+4*sizeof(u32) \
336      +2*2*sizeof(void*) /* Function calls.  */ \
337     )
338
339   return /*burn_stack*/ (CAMELLIA_decrypt_stack_burn_size);
340 }
341
342 #endif /*!USE_ARM_ASM*/
343
344 /* Bulk encryption of complete blocks in CTR mode.  This function is only
345    intended for the bulk encryption feature of cipher.c.  CTR is expected to be
346    of size CAMELLIA_BLOCK_SIZE. */
347 void
348 _gcry_camellia_ctr_enc(void *context, unsigned char *ctr,
349                        void *outbuf_arg, const void *inbuf_arg,
350                        size_t nblocks)
351 {
352   CAMELLIA_context *ctx = context;
353   unsigned char *outbuf = outbuf_arg;
354   const unsigned char *inbuf = inbuf_arg;
355   unsigned char tmpbuf[CAMELLIA_BLOCK_SIZE];
356   int burn_stack_depth = CAMELLIA_encrypt_stack_burn_size;
357   int i;
358
359 #ifdef USE_AESNI_AVX2
360   if (ctx->use_aesni_avx2)
361     {
362       int did_use_aesni_avx2 = 0;
363
364       /* Process data in 32 block chunks. */
365       while (nblocks >= 32)
366         {
367           _gcry_camellia_aesni_avx2_ctr_enc(ctx, outbuf, inbuf, ctr);
368
369           nblocks -= 32;
370           outbuf += 32 * CAMELLIA_BLOCK_SIZE;
371           inbuf  += 32 * CAMELLIA_BLOCK_SIZE;
372           did_use_aesni_avx2 = 1;
373         }
374
375       if (did_use_aesni_avx2)
376         {
377           int avx2_burn_stack_depth = 32 * CAMELLIA_BLOCK_SIZE + 16 +
378                                         2 * sizeof(void *) + ASM_EXTRA_STACK;
379
380           if (burn_stack_depth < avx2_burn_stack_depth)
381             burn_stack_depth = avx2_burn_stack_depth;
382         }
383
384       /* Use generic code to handle smaller chunks... */
385       /* TODO: use caching instead? */
386     }
387 #endif
388
389 #ifdef USE_AESNI_AVX
390   if (ctx->use_aesni_avx)
391     {
392       int did_use_aesni_avx = 0;
393
394       /* Process data in 16 block chunks. */
395       while (nblocks >= 16)
396         {
397           _gcry_camellia_aesni_avx_ctr_enc(ctx, outbuf, inbuf, ctr);
398
399           nblocks -= 16;
400           outbuf += 16 * CAMELLIA_BLOCK_SIZE;
401           inbuf  += 16 * CAMELLIA_BLOCK_SIZE;
402           did_use_aesni_avx = 1;
403         }
404
405       if (did_use_aesni_avx)
406         {
407           int avx_burn_stack_depth = 16 * CAMELLIA_BLOCK_SIZE +
408                                        2 * sizeof(void *) + ASM_EXTRA_STACK;
409
410           if (burn_stack_depth < avx_burn_stack_depth)
411             burn_stack_depth = avx_burn_stack_depth;
412         }
413
414       /* Use generic code to handle smaller chunks... */
415       /* TODO: use caching instead? */
416     }
417 #endif
418
419   for ( ;nblocks; nblocks-- )
420     {
421       /* Encrypt the counter. */
422       Camellia_EncryptBlock(ctx->keybitlength, ctr, ctx->keytable, tmpbuf);
423       /* XOR the input with the encrypted counter and store in output.  */
424       buf_xor(outbuf, tmpbuf, inbuf, CAMELLIA_BLOCK_SIZE);
425       outbuf += CAMELLIA_BLOCK_SIZE;
426       inbuf  += CAMELLIA_BLOCK_SIZE;
427       /* Increment the counter.  */
428       for (i = CAMELLIA_BLOCK_SIZE; i > 0; i--)
429         {
430           ctr[i-1]++;
431           if (ctr[i-1])
432             break;
433         }
434     }
435
436   wipememory(tmpbuf, sizeof(tmpbuf));
437   _gcry_burn_stack(burn_stack_depth);
438 }
439
440 /* Bulk decryption of complete blocks in CBC mode.  This function is only
441    intended for the bulk encryption feature of cipher.c. */
442 void
443 _gcry_camellia_cbc_dec(void *context, unsigned char *iv,
444                        void *outbuf_arg, const void *inbuf_arg,
445                        size_t nblocks)
446 {
447   CAMELLIA_context *ctx = context;
448   unsigned char *outbuf = outbuf_arg;
449   const unsigned char *inbuf = inbuf_arg;
450   unsigned char savebuf[CAMELLIA_BLOCK_SIZE];
451   int burn_stack_depth = CAMELLIA_decrypt_stack_burn_size;
452
453 #ifdef USE_AESNI_AVX2
454   if (ctx->use_aesni_avx2)
455     {
456       int did_use_aesni_avx2 = 0;
457
458       /* Process data in 32 block chunks. */
459       while (nblocks >= 32)
460         {
461           _gcry_camellia_aesni_avx2_cbc_dec(ctx, outbuf, inbuf, iv);
462
463           nblocks -= 32;
464           outbuf += 32 * CAMELLIA_BLOCK_SIZE;
465           inbuf  += 32 * CAMELLIA_BLOCK_SIZE;
466           did_use_aesni_avx2 = 1;
467         }
468
469       if (did_use_aesni_avx2)
470         {
471           int avx2_burn_stack_depth = 32 * CAMELLIA_BLOCK_SIZE + 16 +
472                                         2 * sizeof(void *) + ASM_EXTRA_STACK;;
473
474           if (burn_stack_depth < avx2_burn_stack_depth)
475             burn_stack_depth = avx2_burn_stack_depth;
476         }
477
478       /* Use generic code to handle smaller chunks... */
479     }
480 #endif
481
482 #ifdef USE_AESNI_AVX
483   if (ctx->use_aesni_avx)
484     {
485       int did_use_aesni_avx = 0;
486
487       /* Process data in 16 block chunks. */
488       while (nblocks >= 16)
489         {
490           _gcry_camellia_aesni_avx_cbc_dec(ctx, outbuf, inbuf, iv);
491
492           nblocks -= 16;
493           outbuf += 16 * CAMELLIA_BLOCK_SIZE;
494           inbuf  += 16 * CAMELLIA_BLOCK_SIZE;
495           did_use_aesni_avx = 1;
496         }
497
498       if (did_use_aesni_avx)
499         {
500           int avx_burn_stack_depth = 16 * CAMELLIA_BLOCK_SIZE +
501                                        2 * sizeof(void *) + ASM_EXTRA_STACK;
502
503           if (burn_stack_depth < avx_burn_stack_depth)
504             burn_stack_depth = avx_burn_stack_depth;
505         }
506
507       /* Use generic code to handle smaller chunks... */
508     }
509 #endif
510
511   for ( ;nblocks; nblocks-- )
512     {
513       /* INBUF is needed later and it may be identical to OUTBUF, so store
514          the intermediate result to SAVEBUF.  */
515       Camellia_DecryptBlock(ctx->keybitlength, inbuf, ctx->keytable, savebuf);
516
517       buf_xor_n_copy_2(outbuf, savebuf, iv, inbuf, CAMELLIA_BLOCK_SIZE);
518       inbuf += CAMELLIA_BLOCK_SIZE;
519       outbuf += CAMELLIA_BLOCK_SIZE;
520     }
521
522   wipememory(savebuf, sizeof(savebuf));
523   _gcry_burn_stack(burn_stack_depth);
524 }
525
526 /* Bulk decryption of complete blocks in CFB mode.  This function is only
527    intended for the bulk encryption feature of cipher.c. */
528 void
529 _gcry_camellia_cfb_dec(void *context, unsigned char *iv,
530                        void *outbuf_arg, const void *inbuf_arg,
531                        size_t nblocks)
532 {
533   CAMELLIA_context *ctx = context;
534   unsigned char *outbuf = outbuf_arg;
535   const unsigned char *inbuf = inbuf_arg;
536   int burn_stack_depth = CAMELLIA_decrypt_stack_burn_size;
537
538 #ifdef USE_AESNI_AVX2
539   if (ctx->use_aesni_avx2)
540     {
541       int did_use_aesni_avx2 = 0;
542
543       /* Process data in 32 block chunks. */
544       while (nblocks >= 32)
545         {
546           _gcry_camellia_aesni_avx2_cfb_dec(ctx, outbuf, inbuf, iv);
547
548           nblocks -= 32;
549           outbuf += 32 * CAMELLIA_BLOCK_SIZE;
550           inbuf  += 32 * CAMELLIA_BLOCK_SIZE;
551           did_use_aesni_avx2 = 1;
552         }
553
554       if (did_use_aesni_avx2)
555         {
556           int avx2_burn_stack_depth = 32 * CAMELLIA_BLOCK_SIZE + 16 +
557                                         2 * sizeof(void *) + ASM_EXTRA_STACK;
558
559           if (burn_stack_depth < avx2_burn_stack_depth)
560             burn_stack_depth = avx2_burn_stack_depth;
561         }
562
563       /* Use generic code to handle smaller chunks... */
564     }
565 #endif
566
567 #ifdef USE_AESNI_AVX
568   if (ctx->use_aesni_avx)
569     {
570       int did_use_aesni_avx = 0;
571
572       /* Process data in 16 block chunks. */
573       while (nblocks >= 16)
574         {
575           _gcry_camellia_aesni_avx_cfb_dec(ctx, outbuf, inbuf, iv);
576
577           nblocks -= 16;
578           outbuf += 16 * CAMELLIA_BLOCK_SIZE;
579           inbuf  += 16 * CAMELLIA_BLOCK_SIZE;
580           did_use_aesni_avx = 1;
581         }
582
583       if (did_use_aesni_avx)
584         {
585           int avx_burn_stack_depth = 16 * CAMELLIA_BLOCK_SIZE +
586                                        2 * sizeof(void *) + ASM_EXTRA_STACK;
587
588           if (burn_stack_depth < avx_burn_stack_depth)
589             burn_stack_depth = avx_burn_stack_depth;
590         }
591
592       /* Use generic code to handle smaller chunks... */
593     }
594 #endif
595
596   for ( ;nblocks; nblocks-- )
597     {
598       Camellia_EncryptBlock(ctx->keybitlength, iv, ctx->keytable, iv);
599       buf_xor_n_copy(outbuf, iv, inbuf, CAMELLIA_BLOCK_SIZE);
600       outbuf += CAMELLIA_BLOCK_SIZE;
601       inbuf  += CAMELLIA_BLOCK_SIZE;
602     }
603
604   _gcry_burn_stack(burn_stack_depth);
605 }
606
607 static inline const unsigned char *
608 get_l (gcry_cipher_hd_t c, unsigned char *l_tmp, u64 i)
609 {
610   unsigned int ntz = _gcry_ctz64 (i);
611
612   if (ntz < OCB_L_TABLE_SIZE)
613       return c->u_mode.ocb.L[ntz];
614   else
615       return _gcry_cipher_ocb_get_l (c, l_tmp, i);
616 }
617
618 /* Bulk encryption/decryption of complete blocks in OCB mode. */
619 void
620 _gcry_camellia_ocb_crypt (gcry_cipher_hd_t c, void *outbuf_arg,
621                           const void *inbuf_arg, size_t nblocks, int encrypt)
622 {
623   CAMELLIA_context *ctx = (void *)&c->context.c;
624   unsigned char *outbuf = outbuf_arg;
625   const unsigned char *inbuf = inbuf_arg;
626   unsigned char l_tmp[CAMELLIA_BLOCK_SIZE];
627   const unsigned char *l;
628   int burn_stack_depth;
629   u64 blkn = c->u_mode.ocb.data_nblocks;
630
631   burn_stack_depth = encrypt ? CAMELLIA_encrypt_stack_burn_size :
632                               CAMELLIA_decrypt_stack_burn_size;
633
634 #ifdef USE_AESNI_AVX2
635   if (ctx->use_aesni_avx2)
636     {
637       int did_use_aesni_avx2 = 0;
638       const void *Ls[32];
639       int i;
640
641       /* Process data in 32 block chunks. */
642       while (nblocks >= 32)
643         {
644           /* l_tmp will be used only every 65536-th block. */
645           for (i = 0; i < 32; i += 4)
646             {
647               Ls[i + 0] = get_l(c, l_tmp, blkn + 1);
648               Ls[i + 1] = get_l(c, l_tmp, blkn + 2);
649               Ls[i + 2] = get_l(c, l_tmp, blkn + 3);
650               Ls[i + 3] = get_l(c, l_tmp, blkn + 4);
651               blkn += 4;
652             }
653
654           if (encrypt)
655             _gcry_camellia_aesni_avx2_ocb_enc(ctx, outbuf, inbuf, c->u_iv.iv,
656                                               c->u_ctr.ctr, Ls);
657           else
658             _gcry_camellia_aesni_avx2_ocb_dec(ctx, outbuf, inbuf, c->u_iv.iv,
659                                               c->u_ctr.ctr, Ls);
660
661           nblocks -= 32;
662           outbuf += 32 * CAMELLIA_BLOCK_SIZE;
663           inbuf  += 32 * CAMELLIA_BLOCK_SIZE;
664           did_use_aesni_avx2 = 1;
665         }
666
667       if (did_use_aesni_avx2)
668         {
669           int avx2_burn_stack_depth = 32 * CAMELLIA_BLOCK_SIZE +
670                                       2 * sizeof(void *) + ASM_EXTRA_STACK;
671
672           if (burn_stack_depth < avx2_burn_stack_depth)
673             burn_stack_depth = avx2_burn_stack_depth;
674         }
675
676       /* Use generic code to handle smaller chunks... */
677     }
678 #endif
679
680 #ifdef USE_AESNI_AVX
681   if (ctx->use_aesni_avx)
682     {
683       int did_use_aesni_avx = 0;
684       const void *Ls[16];
685       int i;
686
687       /* Process data in 16 block chunks. */
688       while (nblocks >= 16)
689         {
690           /* l_tmp will be used only every 65536-th block. */
691           for (i = 0; i < 16; i += 4)
692             {
693               Ls[i + 0] = get_l(c, l_tmp, blkn + 1);
694               Ls[i + 1] = get_l(c, l_tmp, blkn + 2);
695               Ls[i + 2] = get_l(c, l_tmp, blkn + 3);
696               Ls[i + 3] = get_l(c, l_tmp, blkn + 4);
697               blkn += 4;
698             }
699
700           if (encrypt)
701             _gcry_camellia_aesni_avx_ocb_enc(ctx, outbuf, inbuf, c->u_iv.iv,
702                                             c->u_ctr.ctr, Ls);
703           else
704             _gcry_camellia_aesni_avx_ocb_dec(ctx, outbuf, inbuf, c->u_iv.iv,
705                                             c->u_ctr.ctr, Ls);
706
707           nblocks -= 16;
708           outbuf += 16 * CAMELLIA_BLOCK_SIZE;
709           inbuf  += 16 * CAMELLIA_BLOCK_SIZE;
710           did_use_aesni_avx = 1;
711         }
712
713       if (did_use_aesni_avx)
714         {
715           int avx_burn_stack_depth = 16 * CAMELLIA_BLOCK_SIZE +
716                                       2 * sizeof(void *) + ASM_EXTRA_STACK;
717
718           if (burn_stack_depth < avx_burn_stack_depth)
719             burn_stack_depth = avx_burn_stack_depth;
720         }
721
722       /* Use generic code to handle smaller chunks... */
723     }
724 #endif
725
726   if (encrypt)
727     {
728       for (; nblocks; nblocks--)
729         {
730           l = get_l(c, l_tmp, ++blkn);
731
732           /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */
733           buf_xor_1 (c->u_iv.iv, l, CAMELLIA_BLOCK_SIZE);
734           buf_cpy (l_tmp, inbuf, CAMELLIA_BLOCK_SIZE);
735           /* Checksum_i = Checksum_{i-1} xor P_i  */
736           buf_xor_1 (c->u_ctr.ctr, l_tmp, CAMELLIA_BLOCK_SIZE);
737           /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)  */
738           buf_xor_1 (l_tmp, c->u_iv.iv, CAMELLIA_BLOCK_SIZE);
739           Camellia_EncryptBlock(ctx->keybitlength, l_tmp, ctx->keytable, l_tmp);
740           buf_xor_1 (l_tmp, c->u_iv.iv, CAMELLIA_BLOCK_SIZE);
741           buf_cpy (outbuf, l_tmp, CAMELLIA_BLOCK_SIZE);
742
743           inbuf += CAMELLIA_BLOCK_SIZE;
744           outbuf += CAMELLIA_BLOCK_SIZE;
745         }
746     }
747   else
748     {
749       for (; nblocks; nblocks--)
750         {
751           l = get_l(c, l_tmp, ++blkn);
752
753           /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */
754           buf_xor_1 (c->u_iv.iv, l, CAMELLIA_BLOCK_SIZE);
755           buf_cpy (l_tmp, inbuf, CAMELLIA_BLOCK_SIZE);
756           /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i)  */
757           buf_xor_1 (l_tmp, c->u_iv.iv, CAMELLIA_BLOCK_SIZE);
758           Camellia_DecryptBlock(ctx->keybitlength, l_tmp, ctx->keytable, l_tmp);
759           buf_xor_1 (l_tmp, c->u_iv.iv, CAMELLIA_BLOCK_SIZE);
760           /* Checksum_i = Checksum_{i-1} xor P_i  */
761           buf_xor_1 (c->u_ctr.ctr, l_tmp, CAMELLIA_BLOCK_SIZE);
762           buf_cpy (outbuf, l_tmp, CAMELLIA_BLOCK_SIZE);
763
764           inbuf += CAMELLIA_BLOCK_SIZE;
765           outbuf += CAMELLIA_BLOCK_SIZE;
766         }
767     }
768
769   c->u_mode.ocb.data_nblocks = blkn;
770
771   wipememory(&l_tmp, sizeof(l_tmp));
772
773   if (burn_stack_depth)
774     _gcry_burn_stack (burn_stack_depth + 4 * sizeof(void *));
775 }
776
777 /* Bulk authentication of complete blocks in OCB mode. */
778 void
779 _gcry_camellia_ocb_auth (gcry_cipher_hd_t c, const void *abuf_arg,
780                         size_t nblocks)
781 {
782   CAMELLIA_context *ctx = (void *)&c->context.c;
783   const unsigned char *abuf = abuf_arg;
784   unsigned char l_tmp[CAMELLIA_BLOCK_SIZE];
785   const unsigned char *l;
786   int burn_stack_depth;
787   u64 blkn = c->u_mode.ocb.aad_nblocks;
788
789   burn_stack_depth = CAMELLIA_encrypt_stack_burn_size;
790
791 #ifdef USE_AESNI_AVX2
792   if (ctx->use_aesni_avx2)
793     {
794       int did_use_aesni_avx2 = 0;
795       const void *Ls[32];
796       int i;
797
798       /* Process data in 32 block chunks. */
799       while (nblocks >= 32)
800         {
801           /* l_tmp will be used only every 65536-th block. */
802           for (i = 0; i < 32; i += 4)
803             {
804               Ls[i + 0] = get_l(c, l_tmp, blkn + 1);
805               Ls[i + 1] = get_l(c, l_tmp, blkn + 2);
806               Ls[i + 2] = get_l(c, l_tmp, blkn + 3);
807               Ls[i + 3] = get_l(c, l_tmp, blkn + 4);
808               blkn += 4;
809             }
810
811           _gcry_camellia_aesni_avx2_ocb_auth(ctx, abuf, c->u_mode.ocb.aad_offset,
812                                             c->u_mode.ocb.aad_sum, Ls);
813
814           nblocks -= 32;
815           abuf += 32 * CAMELLIA_BLOCK_SIZE;
816           did_use_aesni_avx2 = 1;
817         }
818
819       if (did_use_aesni_avx2)
820         {
821           int avx2_burn_stack_depth = 32 * CAMELLIA_BLOCK_SIZE +
822                                       2 * sizeof(void *) + ASM_EXTRA_STACK;
823
824           if (burn_stack_depth < avx2_burn_stack_depth)
825             burn_stack_depth = avx2_burn_stack_depth;
826         }
827
828       /* Use generic code to handle smaller chunks... */
829     }
830 #endif
831
832 #ifdef USE_AESNI_AVX
833   if (ctx->use_aesni_avx)
834     {
835       int did_use_aesni_avx = 0;
836       const void *Ls[16];
837       int i;
838
839       /* Process data in 16 block chunks. */
840       while (nblocks >= 16)
841         {
842           /* l_tmp will be used only every 65536-th block. */
843           for (i = 0; i < 16; i += 4)
844             {
845               Ls[i + 0] = get_l(c, l_tmp, blkn + 1);
846               Ls[i + 1] = get_l(c, l_tmp, blkn + 2);
847               Ls[i + 2] = get_l(c, l_tmp, blkn + 3);
848               Ls[i + 3] = get_l(c, l_tmp, blkn + 4);
849               blkn += 4;
850             }
851
852           _gcry_camellia_aesni_avx_ocb_auth(ctx, abuf, c->u_mode.ocb.aad_offset,
853                                             c->u_mode.ocb.aad_sum, Ls);
854
855           nblocks -= 16;
856           abuf += 16 * CAMELLIA_BLOCK_SIZE;
857           did_use_aesni_avx = 1;
858         }
859
860       if (did_use_aesni_avx)
861         {
862           int avx_burn_stack_depth = 16 * CAMELLIA_BLOCK_SIZE +
863                                       2 * sizeof(void *) + ASM_EXTRA_STACK;
864
865           if (burn_stack_depth < avx_burn_stack_depth)
866             burn_stack_depth = avx_burn_stack_depth;
867         }
868
869       /* Use generic code to handle smaller chunks... */
870     }
871 #endif
872
873   for (; nblocks; nblocks--)
874     {
875       l = get_l(c, l_tmp, ++blkn);
876
877       /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */
878       buf_xor_1 (c->u_mode.ocb.aad_offset, l, CAMELLIA_BLOCK_SIZE);
879       /* Sum_i = Sum_{i-1} xor ENCIPHER(K, A_i xor Offset_i)  */
880       buf_xor (l_tmp, c->u_mode.ocb.aad_offset, abuf, CAMELLIA_BLOCK_SIZE);
881       Camellia_EncryptBlock(ctx->keybitlength, l_tmp, ctx->keytable, l_tmp);
882       buf_xor_1 (c->u_mode.ocb.aad_sum, l_tmp, CAMELLIA_BLOCK_SIZE);
883
884       abuf += CAMELLIA_BLOCK_SIZE;
885     }
886
887   c->u_mode.ocb.aad_nblocks = blkn;
888
889   wipememory(&l_tmp, sizeof(l_tmp));
890
891   if (burn_stack_depth)
892     _gcry_burn_stack (burn_stack_depth + 4 * sizeof(void *));
893 }
894
895 /* Run the self-tests for CAMELLIA-CTR-128, tests IV increment of bulk CTR
896    encryption.  Returns NULL on success. */
897 static const char*
898 selftest_ctr_128 (void)
899 {
900   const int nblocks = 32+16+1;
901   const int blocksize = CAMELLIA_BLOCK_SIZE;
902   const int context_size = sizeof(CAMELLIA_context);
903
904   return _gcry_selftest_helper_ctr("CAMELLIA", &camellia_setkey,
905            &camellia_encrypt, &_gcry_camellia_ctr_enc, nblocks, blocksize,
906            context_size);
907 }
908
909 /* Run the self-tests for CAMELLIA-CBC-128, tests bulk CBC decryption.
910    Returns NULL on success. */
911 static const char*
912 selftest_cbc_128 (void)
913 {
914   const int nblocks = 32+16+2;
915   const int blocksize = CAMELLIA_BLOCK_SIZE;
916   const int context_size = sizeof(CAMELLIA_context);
917
918   return _gcry_selftest_helper_cbc("CAMELLIA", &camellia_setkey,
919            &camellia_encrypt, &_gcry_camellia_cbc_dec, nblocks, blocksize,
920            context_size);
921 }
922
923 /* Run the self-tests for CAMELLIA-CFB-128, tests bulk CFB decryption.
924    Returns NULL on success. */
925 static const char*
926 selftest_cfb_128 (void)
927 {
928   const int nblocks = 32+16+2;
929   const int blocksize = CAMELLIA_BLOCK_SIZE;
930   const int context_size = sizeof(CAMELLIA_context);
931
932   return _gcry_selftest_helper_cfb("CAMELLIA", &camellia_setkey,
933            &camellia_encrypt, &_gcry_camellia_cfb_dec, nblocks, blocksize,
934            context_size);
935 }
936
937 static const char *
938 selftest(void)
939 {
940   CAMELLIA_context ctx;
941   byte scratch[16];
942   const char *r;
943
944   /* These test vectors are from RFC-3713 */
945   static const byte plaintext[]=
946     {
947       0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
948       0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10
949     };
950   static const byte key_128[]=
951     {
952       0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,
953       0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10
954     };
955   static const byte ciphertext_128[]=
956     {
957       0x67,0x67,0x31,0x38,0x54,0x96,0x69,0x73,
958       0x08,0x57,0x06,0x56,0x48,0xea,0xbe,0x43
959     };
960   static const byte key_192[]=
961     {
962       0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,0x98,
963       0x76,0x54,0x32,0x10,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77
964     };
965   static const byte ciphertext_192[]=
966     {
967       0xb4,0x99,0x34,0x01,0xb3,0xe9,0x96,0xf8,
968       0x4e,0xe5,0xce,0xe7,0xd7,0x9b,0x09,0xb9
969     };
970   static const byte key_256[]=
971     {
972       0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef,0xfe,0xdc,0xba,
973       0x98,0x76,0x54,0x32,0x10,0x00,0x11,0x22,0x33,0x44,0x55,
974       0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff
975     };
976   static const byte ciphertext_256[]=
977     {
978       0x9a,0xcc,0x23,0x7d,0xff,0x16,0xd7,0x6c,
979       0x20,0xef,0x7c,0x91,0x9e,0x3a,0x75,0x09
980     };
981
982   camellia_setkey(&ctx,key_128,sizeof(key_128));
983   camellia_encrypt(&ctx,scratch,plaintext);
984   if(memcmp(scratch,ciphertext_128,sizeof(ciphertext_128))!=0)
985     return "CAMELLIA-128 test encryption failed.";
986   camellia_decrypt(&ctx,scratch,scratch);
987   if(memcmp(scratch,plaintext,sizeof(plaintext))!=0)
988     return "CAMELLIA-128 test decryption failed.";
989
990   camellia_setkey(&ctx,key_192,sizeof(key_192));
991   camellia_encrypt(&ctx,scratch,plaintext);
992   if(memcmp(scratch,ciphertext_192,sizeof(ciphertext_192))!=0)
993     return "CAMELLIA-192 test encryption failed.";
994   camellia_decrypt(&ctx,scratch,scratch);
995   if(memcmp(scratch,plaintext,sizeof(plaintext))!=0)
996     return "CAMELLIA-192 test decryption failed.";
997
998   camellia_setkey(&ctx,key_256,sizeof(key_256));
999   camellia_encrypt(&ctx,scratch,plaintext);
1000   if(memcmp(scratch,ciphertext_256,sizeof(ciphertext_256))!=0)
1001     return "CAMELLIA-256 test encryption failed.";
1002   camellia_decrypt(&ctx,scratch,scratch);
1003   if(memcmp(scratch,plaintext,sizeof(plaintext))!=0)
1004     return "CAMELLIA-256 test decryption failed.";
1005
1006   if ( (r = selftest_ctr_128 ()) )
1007     return r;
1008
1009   if ( (r = selftest_cbc_128 ()) )
1010     return r;
1011
1012   if ( (r = selftest_cfb_128 ()) )
1013     return r;
1014
1015   return NULL;
1016 }
1017
1018 /* These oids are from
1019    <http://info.isl.ntt.co.jp/crypt/eng/camellia/specifications_oid.html>,
1020    retrieved May 1, 2007. */
1021
1022 static gcry_cipher_oid_spec_t camellia128_oids[] =
1023   {
1024     {"1.2.392.200011.61.1.1.1.2", GCRY_CIPHER_MODE_CBC},
1025     {"0.3.4401.5.3.1.9.1", GCRY_CIPHER_MODE_ECB},
1026     {"0.3.4401.5.3.1.9.3", GCRY_CIPHER_MODE_OFB},
1027     {"0.3.4401.5.3.1.9.4", GCRY_CIPHER_MODE_CFB},
1028     { NULL }
1029   };
1030
1031 static gcry_cipher_oid_spec_t camellia192_oids[] =
1032   {
1033     {"1.2.392.200011.61.1.1.1.3", GCRY_CIPHER_MODE_CBC},
1034     {"0.3.4401.5.3.1.9.21", GCRY_CIPHER_MODE_ECB},
1035     {"0.3.4401.5.3.1.9.23", GCRY_CIPHER_MODE_OFB},
1036     {"0.3.4401.5.3.1.9.24", GCRY_CIPHER_MODE_CFB},
1037     { NULL }
1038   };
1039
1040 static gcry_cipher_oid_spec_t camellia256_oids[] =
1041   {
1042     {"1.2.392.200011.61.1.1.1.4", GCRY_CIPHER_MODE_CBC},
1043     {"0.3.4401.5.3.1.9.41", GCRY_CIPHER_MODE_ECB},
1044     {"0.3.4401.5.3.1.9.43", GCRY_CIPHER_MODE_OFB},
1045     {"0.3.4401.5.3.1.9.44", GCRY_CIPHER_MODE_CFB},
1046     { NULL }
1047   };
1048
1049 gcry_cipher_spec_t _gcry_cipher_spec_camellia128 =
1050   {
1051     GCRY_CIPHER_CAMELLIA128, {0, 0},
1052     "CAMELLIA128",NULL,camellia128_oids,CAMELLIA_BLOCK_SIZE,128,
1053     sizeof(CAMELLIA_context),camellia_setkey,camellia_encrypt,camellia_decrypt
1054   };
1055
1056 gcry_cipher_spec_t _gcry_cipher_spec_camellia192 =
1057   {
1058     GCRY_CIPHER_CAMELLIA192, {0, 0},
1059     "CAMELLIA192",NULL,camellia192_oids,CAMELLIA_BLOCK_SIZE,192,
1060     sizeof(CAMELLIA_context),camellia_setkey,camellia_encrypt,camellia_decrypt
1061   };
1062
1063 gcry_cipher_spec_t _gcry_cipher_spec_camellia256 =
1064   {
1065     GCRY_CIPHER_CAMELLIA256, {0, 0},
1066     "CAMELLIA256",NULL,camellia256_oids,CAMELLIA_BLOCK_SIZE,256,
1067     sizeof(CAMELLIA_context),camellia_setkey,camellia_encrypt,camellia_decrypt
1068   };