]> www.wagner.pp.ru Git - openssl-gost/engine.git/blob - gost_grasshopper_cipher.c
Merge pull request #82 from vt-alt/fix
[openssl-gost/engine.git] / gost_grasshopper_cipher.c
1 /*
2  * Maxim Tishkov 2016
3  * This file is distributed under the same license as OpenSSL
4  */
5
6 #if defined(__cplusplus)
7 extern "C" {
8 #endif
9
10 #include "gost_grasshopper_cipher.h"
11 #include "gost_grasshopper_defines.h"
12 #include "gost_grasshopper_math.h"
13 #include "gost_grasshopper_core.h"
14
15 #include <openssl/evp.h>
16 #include <openssl/rand.h>
17 #include <openssl/err.h>
18 #include <string.h>
19
20 #include "gost_lcl.h"
21 #include "e_gost_err.h"
22
23 enum GRASSHOPPER_CIPHER_TYPE {
24     GRASSHOPPER_CIPHER_ECB = 0,
25     GRASSHOPPER_CIPHER_CBC,
26     GRASSHOPPER_CIPHER_OFB,
27     GRASSHOPPER_CIPHER_CFB,
28     GRASSHOPPER_CIPHER_CTR,
29     GRASSHOPPER_CIPHER_CTRACPKM,
30 };
31
32 static EVP_CIPHER* gost_grasshopper_ciphers[6] = {
33         [GRASSHOPPER_CIPHER_ECB] = NULL,
34         [GRASSHOPPER_CIPHER_CBC] = NULL,
35         [GRASSHOPPER_CIPHER_OFB] = NULL,
36         [GRASSHOPPER_CIPHER_CFB] = NULL,
37         [GRASSHOPPER_CIPHER_CTR] = NULL,
38         [GRASSHOPPER_CIPHER_CTRACPKM] = NULL,
39 };
40
41 static GRASSHOPPER_INLINE void gost_grasshopper_cipher_destroy_ofb(gost_grasshopper_cipher_ctx* c);
42 static GRASSHOPPER_INLINE void gost_grasshopper_cipher_destroy_ctr(gost_grasshopper_cipher_ctx* c);
43
44 struct GRASSHOPPER_CIPHER_PARAMS {
45     int nid;
46     grasshopper_init_cipher_func init_cipher;
47     grasshopper_do_cipher_func do_cipher;
48     grasshopper_destroy_cipher_func destroy_cipher;
49     int block_size;
50     int ctx_size;
51     int iv_size;
52     bool padding;
53 };
54
55 static struct GRASSHOPPER_CIPHER_PARAMS gost_cipher_params[6] = {
56         [GRASSHOPPER_CIPHER_ECB] = {
57                 NID_grasshopper_ecb,
58                 gost_grasshopper_cipher_init_ecb,
59                 gost_grasshopper_cipher_do_ecb,
60                 NULL,
61                 16,
62                 sizeof(gost_grasshopper_cipher_ctx),
63                 0,
64                 true
65         },
66         [GRASSHOPPER_CIPHER_CBC] = {
67                 NID_grasshopper_cbc,
68                 gost_grasshopper_cipher_init_cbc,
69                 gost_grasshopper_cipher_do_cbc,
70                 NULL,
71                 16,
72                 sizeof(gost_grasshopper_cipher_ctx),
73                 16,
74                 true
75         },
76         [GRASSHOPPER_CIPHER_OFB] = {
77                 NID_grasshopper_ofb,
78                 gost_grasshopper_cipher_init_ofb,
79                 gost_grasshopper_cipher_do_ofb,
80                 gost_grasshopper_cipher_destroy_ofb,
81                 1,
82                 sizeof(gost_grasshopper_cipher_ctx_ofb),
83                 16,
84                 false
85         },
86         [GRASSHOPPER_CIPHER_CFB] = {
87                 NID_grasshopper_cfb,
88                 gost_grasshopper_cipher_init_cfb,
89                 gost_grasshopper_cipher_do_cfb,
90                 NULL,
91                 1,
92                 sizeof(gost_grasshopper_cipher_ctx),
93                 16,
94                 false
95         },
96         [GRASSHOPPER_CIPHER_CTR] = {
97                 NID_grasshopper_ctr,
98                 gost_grasshopper_cipher_init_ctr,
99                 gost_grasshopper_cipher_do_ctr,
100                 gost_grasshopper_cipher_destroy_ctr,
101                 1,
102                 sizeof(gost_grasshopper_cipher_ctx_ctr),
103                 /* IV size is set to match full block, to make it responsibility of
104                  * user to assign correct values (IV || 0), and to make naive context
105                  * copy possible (for software such as openssh) */
106                 16,
107                 false
108         },
109         [GRASSHOPPER_CIPHER_CTRACPKM] = {
110                 NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm,
111                 gost_grasshopper_cipher_init_ctracpkm,
112                 gost_grasshopper_cipher_do_ctracpkm,
113                 gost_grasshopper_cipher_destroy_ctr,
114                 1,
115                 sizeof(gost_grasshopper_cipher_ctx_ctr),
116                 16,
117                 false
118         },
119 };
120
121 /* first 256 bit of D from draft-irtf-cfrg-re-keying-12 */
122 static const unsigned char ACPKM_D_2018[] = {
123     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, /*  64 bit */
124     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, /* 128 bit */
125     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
126     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, /* 256 bit */
127 };
128
129 static void acpkm_next(gost_grasshopper_cipher_ctx *c)
130 {
131     unsigned char newkey[GRASSHOPPER_KEY_SIZE];
132     const int J = GRASSHOPPER_KEY_SIZE / GRASSHOPPER_BLOCK_SIZE;
133     int n;
134
135     for (n = 0; n < J; n++) {
136         const unsigned char *D_n = &ACPKM_D_2018[n * GRASSHOPPER_BLOCK_SIZE];
137
138         grasshopper_encrypt_block(&c->encrypt_round_keys,
139             (grasshopper_w128_t *)D_n,
140             (grasshopper_w128_t *)&newkey[n * GRASSHOPPER_BLOCK_SIZE],
141             &c->buffer);
142     }
143     gost_grasshopper_cipher_key(c, newkey);
144 }
145
146 /* Set 256 bit  key into context */
147 GRASSHOPPER_INLINE void gost_grasshopper_cipher_key(gost_grasshopper_cipher_ctx* c, const uint8_t* k) {
148                 int i;
149     for (i = 0; i < 2; i++) {
150         grasshopper_copy128(&c->key.k.k[i], (const grasshopper_w128_t*) (k + i * 16));
151     }
152     grasshopper_set_encrypt_key(&c->encrypt_round_keys, &c->key);
153     grasshopper_set_decrypt_key(&c->decrypt_round_keys, &c->key);
154 }
155
156 /* Cleans up key from context */
157 GRASSHOPPER_INLINE void gost_grasshopper_cipher_destroy(gost_grasshopper_cipher_ctx* c) {
158                 int i;
159     for (i = 0; i < 2; i++) {
160         grasshopper_zero128(&c->key.k.k[i]);
161     }
162     for (i = 0; i < GRASSHOPPER_ROUND_KEYS_COUNT; i++) {
163         grasshopper_zero128(&c->encrypt_round_keys.k[i]);
164     }
165     for (i = 0; i < GRASSHOPPER_ROUND_KEYS_COUNT; i++) {
166         grasshopper_zero128(&c->decrypt_round_keys.k[i]);
167     }
168     grasshopper_zero128(&c->buffer);
169 }
170
171 static GRASSHOPPER_INLINE void gost_grasshopper_cipher_destroy_ofb(gost_grasshopper_cipher_ctx* c) {
172     gost_grasshopper_cipher_ctx_ofb* ctx = (gost_grasshopper_cipher_ctx_ofb*) c;
173
174     grasshopper_zero128(&ctx->buffer1);
175 }
176
177 static GRASSHOPPER_INLINE void gost_grasshopper_cipher_destroy_ctr(gost_grasshopper_cipher_ctx* c) {
178     gost_grasshopper_cipher_ctx_ctr* ctx = (gost_grasshopper_cipher_ctx_ctr*) c;
179
180     grasshopper_zero128(&ctx->partial_buffer);
181 }
182
183 int gost_grasshopper_cipher_init(EVP_CIPHER_CTX* ctx, const unsigned char* key,
184                                         const unsigned char* iv, int enc) {
185     gost_grasshopper_cipher_ctx* c = EVP_CIPHER_CTX_get_cipher_data(ctx);
186
187     if (EVP_CIPHER_CTX_get_app_data(ctx) == NULL) {
188         EVP_CIPHER_CTX_set_app_data(ctx, EVP_CIPHER_CTX_get_cipher_data(ctx));
189     }
190
191     if (key != NULL) {
192         gost_grasshopper_cipher_key(c, key);
193     }
194
195     if (iv != NULL) {
196         memcpy((unsigned char*) EVP_CIPHER_CTX_original_iv(ctx), iv,
197                EVP_CIPHER_CTX_iv_length(ctx));
198     }
199
200     memcpy(EVP_CIPHER_CTX_iv_noconst(ctx),
201            EVP_CIPHER_CTX_original_iv(ctx),
202            EVP_CIPHER_CTX_iv_length(ctx));
203
204     grasshopper_zero128(&c->buffer);
205
206     return 1;
207 }
208
209 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ecb(EVP_CIPHER_CTX* ctx, const unsigned char* key,
210                                                                const unsigned char* iv,
211                                                                int enc) {
212     gost_grasshopper_cipher_ctx* c = EVP_CIPHER_CTX_get_cipher_data(ctx);
213     c->type = GRASSHOPPER_CIPHER_ECB;
214     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
215 }
216
217 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_cbc(EVP_CIPHER_CTX* ctx, const unsigned char* key,
218                                                                const unsigned char* iv,
219                                                                int enc) {
220     gost_grasshopper_cipher_ctx* c = EVP_CIPHER_CTX_get_cipher_data(ctx);
221     c->type = GRASSHOPPER_CIPHER_CBC;
222     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
223 }
224
225 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ofb(EVP_CIPHER_CTX* ctx, const unsigned char* key,
226                                                                const unsigned char* iv,
227                                                                int enc) {
228     gost_grasshopper_cipher_ctx_ofb* c = EVP_CIPHER_CTX_get_cipher_data(ctx);
229
230     c->c.type = GRASSHOPPER_CIPHER_OFB;
231
232     grasshopper_zero128(&c->buffer1);
233
234     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
235 }
236
237 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_cfb(EVP_CIPHER_CTX* ctx, const unsigned char* key,
238                                                                const unsigned char* iv,
239                                                                int enc) {
240     gost_grasshopper_cipher_ctx* c = EVP_CIPHER_CTX_get_cipher_data(ctx);
241     c->type = GRASSHOPPER_CIPHER_CFB;
242     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
243 }
244
245 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ctr(EVP_CIPHER_CTX* ctx, const unsigned char* key,
246                                                                const unsigned char* iv,
247                                                                int enc) {
248     gost_grasshopper_cipher_ctx_ctr* c = EVP_CIPHER_CTX_get_cipher_data(ctx);
249
250     c->c.type = GRASSHOPPER_CIPHER_CTR;
251     EVP_CIPHER_CTX_set_num(ctx, 0);
252
253     grasshopper_zero128(&c->partial_buffer);
254
255     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
256 }
257
258 GRASSHOPPER_INLINE int gost_grasshopper_cipher_init_ctracpkm(EVP_CIPHER_CTX *ctx, const unsigned char *key,
259                                                                const unsigned char *iv,
260                                                                int enc) {
261     gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
262
263     /* NB: setting type makes EVP do_cipher callback useless */
264     c->c.type = GRASSHOPPER_CIPHER_CTRACPKM;
265     EVP_CIPHER_CTX_set_num(ctx, 0);
266     c->section_size  = 4096;
267
268     return gost_grasshopper_cipher_init(ctx, key, iv, enc);
269 }
270
271 GRASSHOPPER_INLINE int gost_grasshopper_cipher_do(EVP_CIPHER_CTX* ctx, unsigned char* out,
272                                                          const unsigned char* in, size_t inl) {
273     gost_grasshopper_cipher_ctx* c = (gost_grasshopper_cipher_ctx*) EVP_CIPHER_CTX_get_cipher_data(ctx);
274     struct GRASSHOPPER_CIPHER_PARAMS* params = &gost_cipher_params[c->type];
275
276     return params->do_cipher(ctx, out, in, inl);
277 }
278
279 int gost_grasshopper_cipher_do_ecb(EVP_CIPHER_CTX* ctx, unsigned char* out,
280                                           const unsigned char* in, size_t inl) {
281     gost_grasshopper_cipher_ctx* c = (gost_grasshopper_cipher_ctx*) EVP_CIPHER_CTX_get_cipher_data(ctx);
282     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
283     const unsigned char* current_in = in;
284     unsigned char* current_out = out;
285     size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
286     size_t i;
287
288     for (i = 0; i < blocks; i++, current_in += GRASSHOPPER_BLOCK_SIZE, current_out += GRASSHOPPER_BLOCK_SIZE) {
289         if (encrypting) {
290             grasshopper_encrypt_block(&c->encrypt_round_keys, (grasshopper_w128_t*) current_in,
291                                       (grasshopper_w128_t*) current_out,
292                                       &c->buffer);
293         } else {
294             grasshopper_decrypt_block(&c->decrypt_round_keys, (grasshopper_w128_t*) current_in,
295                                       (grasshopper_w128_t*) current_out,
296                                       &c->buffer);
297         }
298     }
299
300     return 1;
301 }
302
303 int gost_grasshopper_cipher_do_cbc(EVP_CIPHER_CTX* ctx, unsigned char* out,
304                                           const unsigned char* in, size_t inl) {
305     gost_grasshopper_cipher_ctx* c = (gost_grasshopper_cipher_ctx*) EVP_CIPHER_CTX_get_cipher_data(ctx);
306     unsigned char* iv = EVP_CIPHER_CTX_iv_noconst(ctx);
307     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
308     const unsigned char* current_in = in;
309     unsigned char* current_out = out;
310     grasshopper_w128_t* currentInputBlock;
311     grasshopper_w128_t* currentOutputBlock;
312     size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
313     size_t i;
314     grasshopper_w128_t* currentBlock;
315
316     currentBlock = (grasshopper_w128_t*) iv;
317
318     for (i = 0; i < blocks; i++, current_in += GRASSHOPPER_BLOCK_SIZE, current_out += GRASSHOPPER_BLOCK_SIZE) {
319         currentInputBlock = (grasshopper_w128_t*) current_in;
320         currentOutputBlock = (grasshopper_w128_t*) current_out;
321         if (encrypting) {
322             grasshopper_append128(currentBlock, currentInputBlock);
323             grasshopper_encrypt_block(&c->encrypt_round_keys, currentBlock, currentOutputBlock, &c->buffer);
324             grasshopper_copy128(currentBlock, currentOutputBlock);
325         } else {
326             grasshopper_decrypt_block(&c->decrypt_round_keys, currentInputBlock, currentOutputBlock, &c->buffer);
327             grasshopper_append128(currentOutputBlock, currentBlock);
328             grasshopper_copy128(currentBlock, currentInputBlock);
329         }
330     }
331
332     return 1;
333 }
334
335 void inc_counter(unsigned char* counter, size_t counter_bytes)
336 {
337     unsigned char c;
338     unsigned int n = counter_bytes;
339
340     do {
341         --n;
342         c = counter[n];
343         ++c;
344         counter[n] = c;
345         if (c) return;
346     } while (n);
347 }
348
349 /* increment counter (128-bit int) by 1 */
350 static void ctr128_inc(unsigned char *counter)
351 {
352         inc_counter(counter, 16);
353 }
354
355 int gost_grasshopper_cipher_do_ctr(EVP_CIPHER_CTX* ctx, unsigned char* out,
356                                           const unsigned char* in, size_t inl) {
357     gost_grasshopper_cipher_ctx_ctr* c = (gost_grasshopper_cipher_ctx_ctr*) EVP_CIPHER_CTX_get_cipher_data(ctx);
358     unsigned char* iv = EVP_CIPHER_CTX_iv_noconst(ctx);
359     const unsigned char* current_in = in;
360     unsigned char* current_out = out;
361     grasshopper_w128_t* currentInputBlock;
362     grasshopper_w128_t* currentOutputBlock;
363     unsigned int n = EVP_CIPHER_CTX_num(ctx);
364     size_t lasted;
365     size_t i;
366
367     while (n && inl) {
368         *(current_out++) = *(current_in++) ^ c->partial_buffer.b[n];
369         --inl;
370         n = (n + 1) % GRASSHOPPER_BLOCK_SIZE;
371     }
372     EVP_CIPHER_CTX_set_num(ctx, n);
373     size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
374
375     grasshopper_w128_t* iv_buffer = (grasshopper_w128_t*) iv;
376
377     // full parts
378     for (i = 0; i < blocks; i++) {
379         currentInputBlock = (grasshopper_w128_t*) current_in;
380         currentOutputBlock = (grasshopper_w128_t*) current_out;
381         grasshopper_encrypt_block(&c->c.encrypt_round_keys, iv_buffer, currentOutputBlock, &c->c.buffer);
382         grasshopper_append128(currentOutputBlock, currentInputBlock);
383         ctr128_inc(iv_buffer->b);
384         current_in += GRASSHOPPER_BLOCK_SIZE;
385         current_out += GRASSHOPPER_BLOCK_SIZE;
386     }
387
388     // last part
389     lasted = inl - blocks * GRASSHOPPER_BLOCK_SIZE;
390     if (lasted > 0) {
391         currentInputBlock = (grasshopper_w128_t*) current_in;
392         currentOutputBlock = (grasshopper_w128_t*) current_out;
393         grasshopper_encrypt_block(&c->c.encrypt_round_keys, iv_buffer, &c->partial_buffer, &c->c.buffer);
394         for (i = 0; i < lasted; i++) {
395             currentOutputBlock->b[i] = c->partial_buffer.b[i] ^ currentInputBlock->b[i];
396         }
397         EVP_CIPHER_CTX_set_num(ctx, i);
398         ctr128_inc(iv_buffer->b);
399     }
400
401     return 1;
402 }
403
404 #define GRASSHOPPER_BLOCK_MASK (GRASSHOPPER_BLOCK_SIZE - 1)
405 static inline void apply_acpkm_grasshopper(gost_grasshopper_cipher_ctx_ctr *ctx, unsigned int *num)
406 {
407     if (!ctx->section_size ||
408         (*num < ctx->section_size))
409         return;
410     acpkm_next(&ctx->c);
411     *num &= GRASSHOPPER_BLOCK_MASK;
412 }
413
414 /* If meshing is not configured via ctrl (setting section_size)
415  * this function works exactly like plain ctr */
416 int gost_grasshopper_cipher_do_ctracpkm(EVP_CIPHER_CTX *ctx, unsigned char *out,
417     const unsigned char *in, size_t inl) {
418     gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
419     unsigned char *iv = EVP_CIPHER_CTX_iv_noconst(ctx);
420     unsigned int num = EVP_CIPHER_CTX_num(ctx);
421
422     while ((num & GRASSHOPPER_BLOCK_MASK) && inl) {
423         *out++ = *in++ ^ c->partial_buffer.b[num & GRASSHOPPER_BLOCK_MASK];
424         --inl;
425         num++;
426     }
427     size_t blocks = inl / GRASSHOPPER_BLOCK_SIZE;
428     size_t i;
429
430     // full parts
431     for (i = 0; i < blocks; i++) {
432         apply_acpkm_grasshopper(c, &num);
433         grasshopper_encrypt_block(&c->c.encrypt_round_keys,
434             (grasshopper_w128_t *)iv, (grasshopper_w128_t *)out, &c->c.buffer);
435         grasshopper_append128((grasshopper_w128_t *)out, (grasshopper_w128_t *)in);
436         ctr128_inc(iv);
437         in  += GRASSHOPPER_BLOCK_SIZE;
438         out += GRASSHOPPER_BLOCK_SIZE;
439         num += GRASSHOPPER_BLOCK_SIZE;
440     }
441
442     // last part
443     size_t lasted = inl - blocks * GRASSHOPPER_BLOCK_SIZE;
444     if (lasted > 0) {
445         apply_acpkm_grasshopper(c, &num);
446         grasshopper_encrypt_block(&c->c.encrypt_round_keys,
447             (grasshopper_w128_t *)iv, &c->partial_buffer, &c->c.buffer);
448         for (i = 0; i < lasted; i++)
449             out[i] = c->partial_buffer.b[i] ^ in[i];
450         ctr128_inc(iv);
451         num += lasted;
452     }
453     EVP_CIPHER_CTX_set_num(ctx, num);
454
455     return 1;
456 }
457
458 /*
459  * Fixed 128-bit IV implementation make shift regiser redundant.
460  */
461 static void gost_grasshopper_cnt_next(gost_grasshopper_cipher_ctx_ofb* ctx, grasshopper_w128_t* iv,
462                                       grasshopper_w128_t* buf) {
463     memcpy(&ctx->buffer1, iv, 16);
464     grasshopper_encrypt_block(&ctx->c.encrypt_round_keys, &ctx->buffer1, buf, &ctx->c.buffer);
465     memcpy(iv, buf, 16);
466 }
467
468 int gost_grasshopper_cipher_do_ofb(EVP_CIPHER_CTX* ctx, unsigned char* out,
469                                           const unsigned char* in, size_t inl) {
470     gost_grasshopper_cipher_ctx_ofb* c = (gost_grasshopper_cipher_ctx_ofb*) EVP_CIPHER_CTX_get_cipher_data(ctx);
471     const unsigned char* in_ptr = in;
472     unsigned char* out_ptr = out;
473     unsigned char* buf = EVP_CIPHER_CTX_buf_noconst(ctx);
474     unsigned char* iv = EVP_CIPHER_CTX_iv_noconst(ctx);
475     int num = EVP_CIPHER_CTX_num(ctx);
476     size_t i = 0;
477     size_t j;
478
479     /* process partial block if any */
480     if (num > 0) {
481         for (j = (size_t) num, i = 0; j < GRASSHOPPER_BLOCK_SIZE && i < inl;
482              j++, i++, in_ptr++, out_ptr++) {
483             *out_ptr = buf[j] ^ (*in_ptr);
484         }
485         if (j == GRASSHOPPER_BLOCK_SIZE) {
486             EVP_CIPHER_CTX_set_num(ctx, 0);
487         } else {
488             EVP_CIPHER_CTX_set_num(ctx, (int) j);
489             return 1;
490         }
491     }
492
493     for (; i + GRASSHOPPER_BLOCK_SIZE <
494            inl; i += GRASSHOPPER_BLOCK_SIZE, in_ptr += GRASSHOPPER_BLOCK_SIZE, out_ptr += GRASSHOPPER_BLOCK_SIZE) {
495         /*
496          * block cipher current iv
497          */
498         /* Encrypt */
499         gost_grasshopper_cnt_next(c, (grasshopper_w128_t*) iv, (grasshopper_w128_t*) buf);
500
501         /*
502          * xor next block of input text with it and output it
503          */
504         /*
505          * output this block
506          */
507         for (j = 0; j < GRASSHOPPER_BLOCK_SIZE; j++) {
508             out_ptr[j] = buf[j] ^ in_ptr[j];
509         }
510     }
511
512     /* Process rest of buffer */
513     if (i < inl) {
514         gost_grasshopper_cnt_next(c, (grasshopper_w128_t*) iv, (grasshopper_w128_t*) buf);
515         for (j = 0; i < inl; j++, i++) {
516             out_ptr[j] = buf[j] ^ in_ptr[j];
517         }
518         EVP_CIPHER_CTX_set_num(ctx, (int) j);
519     } else {
520         EVP_CIPHER_CTX_set_num(ctx, 0);
521     }
522
523     return 1;
524 }
525
526 int gost_grasshopper_cipher_do_cfb(EVP_CIPHER_CTX* ctx, unsigned char* out,
527                                           const unsigned char* in, size_t inl) {
528     gost_grasshopper_cipher_ctx* c = (gost_grasshopper_cipher_ctx*) EVP_CIPHER_CTX_get_cipher_data(ctx);
529     const unsigned char* in_ptr = in;
530     unsigned char* out_ptr = out;
531     unsigned char* buf = EVP_CIPHER_CTX_buf_noconst(ctx);
532     unsigned char* iv = EVP_CIPHER_CTX_iv_noconst(ctx);
533     bool encrypting = (bool) EVP_CIPHER_CTX_encrypting(ctx);
534     int num = EVP_CIPHER_CTX_num(ctx);
535     size_t i = 0;
536     size_t j = 0;
537
538     /* process partial block if any */
539     if (num > 0) {
540         for (j = (size_t) num, i = 0; j < GRASSHOPPER_BLOCK_SIZE && i < inl; j++, i++, in_ptr++, out_ptr++) {
541             if (!encrypting) {
542                 buf[j + GRASSHOPPER_BLOCK_SIZE] = *in_ptr;
543             }
544             *out_ptr = buf[j] ^ (*in_ptr);
545             if (encrypting) {
546                 buf[j + GRASSHOPPER_BLOCK_SIZE] = *out_ptr;
547             }
548         }
549         if (j == GRASSHOPPER_BLOCK_SIZE) {
550             memcpy(iv, buf + GRASSHOPPER_BLOCK_SIZE, GRASSHOPPER_BLOCK_SIZE);
551             EVP_CIPHER_CTX_set_num(ctx, 0);
552         } else {
553             EVP_CIPHER_CTX_set_num(ctx, (int) j);
554             return 1;
555         }
556     }
557
558     for (; i + GRASSHOPPER_BLOCK_SIZE <
559            inl; i += GRASSHOPPER_BLOCK_SIZE, in_ptr += GRASSHOPPER_BLOCK_SIZE, out_ptr += GRASSHOPPER_BLOCK_SIZE) {
560         /*
561          * block cipher current iv
562          */
563         grasshopper_encrypt_block(&c->encrypt_round_keys, (grasshopper_w128_t*) iv, (grasshopper_w128_t*) buf,
564                                   &c->buffer);
565         /*
566          * xor next block of input text with it and output it
567          */
568         /*
569          * output this block
570          */
571         if (!encrypting) {
572             memcpy(iv, in_ptr, GRASSHOPPER_BLOCK_SIZE);
573         }
574         for (j = 0; j < GRASSHOPPER_BLOCK_SIZE; j++) {
575             out_ptr[j] = buf[j] ^ in_ptr[j];
576         }
577         /* Encrypt */
578         /* Next iv is next block of cipher text */
579         if (encrypting) {
580             memcpy(iv, out_ptr, GRASSHOPPER_BLOCK_SIZE);
581         }
582     }
583
584     /* Process rest of buffer */
585     if (i < inl) {
586         grasshopper_encrypt_block(&c->encrypt_round_keys, (grasshopper_w128_t*) iv, (grasshopper_w128_t*) buf,
587                                   &c->buffer);
588         if (!encrypting) {
589             memcpy(buf + GRASSHOPPER_BLOCK_SIZE, in_ptr, inl - i);
590         }
591         for (j = 0; i < inl; j++, i++) {
592             out_ptr[j] = buf[j] ^ in_ptr[j];
593         }
594         EVP_CIPHER_CTX_set_num(ctx, (int) j);
595         if (encrypting) {
596             memcpy(buf + GRASSHOPPER_BLOCK_SIZE, out_ptr, j);
597         }
598     } else {
599         EVP_CIPHER_CTX_set_num(ctx, 0);
600     }
601
602     return 1;
603 }
604
605 int gost_grasshopper_cipher_cleanup(EVP_CIPHER_CTX* ctx) {
606     gost_grasshopper_cipher_ctx* c = (gost_grasshopper_cipher_ctx*) EVP_CIPHER_CTX_get_cipher_data(ctx);
607
608     if (!c)
609         return 1;
610
611     struct GRASSHOPPER_CIPHER_PARAMS* params = &gost_cipher_params[c->type];
612
613     gost_grasshopper_cipher_destroy(c);
614     if (params->destroy_cipher != NULL) {
615         params->destroy_cipher(c);
616     }
617
618     EVP_CIPHER_CTX_set_app_data(ctx, NULL);
619
620     return 1;
621 }
622
623 int gost_grasshopper_set_asn1_parameters(EVP_CIPHER_CTX* ctx, ASN1_TYPE* params) {
624     int len = 0;
625     unsigned char* buf = NULL;
626     ASN1_OCTET_STRING* os = NULL;
627
628     os = ASN1_OCTET_STRING_new();
629
630     if (!os || !ASN1_OCTET_STRING_set(os, buf, len)) {
631         OPENSSL_free(buf);
632         GOSTerr(GOST_F_GOST_GRASSHOPPER_SET_ASN1_PARAMETERS, ERR_R_MALLOC_FAILURE);
633         return 0;
634     }
635     OPENSSL_free(buf);
636
637     ASN1_TYPE_set(params, V_ASN1_SEQUENCE, os);
638     return 1;
639 }
640
641 GRASSHOPPER_INLINE int gost_grasshopper_get_asn1_parameters(EVP_CIPHER_CTX* ctx, ASN1_TYPE* params) {
642     int ret = -1;
643
644     if (ASN1_TYPE_get(params) != V_ASN1_SEQUENCE) {
645         return ret;
646     }
647
648     return 1;
649 }
650
651 int gost_grasshopper_cipher_ctl(EVP_CIPHER_CTX* ctx, int type, int arg, void* ptr) {
652     switch (type) {
653         case EVP_CTRL_RAND_KEY: {
654             if (RAND_bytes((unsigned char*) ptr, EVP_CIPHER_CTX_key_length(ctx)) <= 0) {
655                 GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_CTL, GOST_R_RNG_ERROR);
656                 return -1;
657             }
658             break;
659         }
660         case EVP_CTRL_KEY_MESH: {
661             gost_grasshopper_cipher_ctx_ctr *c = EVP_CIPHER_CTX_get_cipher_data(ctx);
662             if (c->c.type != GRASSHOPPER_CIPHER_CTRACPKM ||
663                 !arg || (arg % GRASSHOPPER_BLOCK_SIZE))
664                 return -1;
665             c->section_size = arg;
666             break;
667         }
668         default:
669             GOSTerr(GOST_F_GOST_GRASSHOPPER_CIPHER_CTL, GOST_R_UNSUPPORTED_CIPHER_CTL_COMMAND);
670             return -1;
671     }
672     return 1;
673 }
674
675 GRASSHOPPER_INLINE EVP_CIPHER* cipher_gost_grasshopper_create(int cipher_type, int block_size) {
676     return EVP_CIPHER_meth_new(cipher_type,
677                                block_size  /* block_size */,
678                                GRASSHOPPER_KEY_SIZE /* key_size */);
679 }
680
681 const int cipher_gost_grasshopper_setup(EVP_CIPHER* cipher, uint8_t mode, int iv_size, bool padding) {
682     return EVP_CIPHER_meth_set_iv_length(cipher, iv_size) &&
683            EVP_CIPHER_meth_set_flags(cipher, (unsigned long) (
684                    mode |
685                    ((!padding) ? EVP_CIPH_NO_PADDING : 0) |
686                    ((iv_size > 0) ? EVP_CIPH_CUSTOM_IV : 0) |
687                    EVP_CIPH_RAND_KEY |
688                    EVP_CIPH_ALWAYS_CALL_INIT)
689            ) &&
690            EVP_CIPHER_meth_set_cleanup(cipher, gost_grasshopper_cipher_cleanup) &&
691            EVP_CIPHER_meth_set_set_asn1_params(cipher, gost_grasshopper_set_asn1_parameters) &&
692            EVP_CIPHER_meth_set_get_asn1_params(cipher, gost_grasshopper_get_asn1_parameters) &&
693            EVP_CIPHER_meth_set_ctrl(cipher, gost_grasshopper_cipher_ctl) &&
694            EVP_CIPHER_meth_set_do_cipher(cipher, gost_grasshopper_cipher_do);
695 }
696
697 const GRASSHOPPER_INLINE EVP_CIPHER* cipher_gost_grasshopper(uint8_t mode, uint8_t num) {
698     EVP_CIPHER** cipher;
699     struct GRASSHOPPER_CIPHER_PARAMS* params;
700
701     cipher = &gost_grasshopper_ciphers[num];
702
703     if (*cipher == NULL) {
704         params = &gost_cipher_params[num];
705
706         int nid = params->nid;
707         grasshopper_init_cipher_func init_cipher = params->init_cipher;
708         int block_size = params->block_size;
709         int ctx_size = params->ctx_size;
710         int iv_size = params->iv_size;
711         bool padding = params->padding;
712
713         *cipher = cipher_gost_grasshopper_create(nid, block_size);
714         if (*cipher == NULL) {
715             return NULL;
716         }
717
718         if (!cipher_gost_grasshopper_setup(*cipher, mode, iv_size, padding) ||
719             !EVP_CIPHER_meth_set_init(*cipher, init_cipher) ||
720             !EVP_CIPHER_meth_set_impl_ctx_size(*cipher, ctx_size)) {
721             EVP_CIPHER_meth_free(*cipher);
722             *cipher = NULL;
723         }
724     }
725
726     return *cipher;
727 }
728
729 const GRASSHOPPER_INLINE EVP_CIPHER* cipher_gost_grasshopper_ecb() {
730     return cipher_gost_grasshopper(EVP_CIPH_ECB_MODE, GRASSHOPPER_CIPHER_ECB);
731 }
732
733 const GRASSHOPPER_INLINE EVP_CIPHER* cipher_gost_grasshopper_cbc() {
734     return cipher_gost_grasshopper(EVP_CIPH_CBC_MODE, GRASSHOPPER_CIPHER_CBC);
735 }
736
737 const GRASSHOPPER_INLINE EVP_CIPHER* cipher_gost_grasshopper_ofb() {
738     return cipher_gost_grasshopper(EVP_CIPH_OFB_MODE, GRASSHOPPER_CIPHER_OFB);
739 }
740
741 const GRASSHOPPER_INLINE EVP_CIPHER* cipher_gost_grasshopper_cfb() {
742     return cipher_gost_grasshopper(EVP_CIPH_CFB_MODE, GRASSHOPPER_CIPHER_CFB);
743 }
744
745 const GRASSHOPPER_INLINE EVP_CIPHER* cipher_gost_grasshopper_ctr() {
746     return cipher_gost_grasshopper(EVP_CIPH_CTR_MODE, GRASSHOPPER_CIPHER_CTR);
747 }
748
749 const GRASSHOPPER_INLINE EVP_CIPHER* cipher_gost_grasshopper_ctracpkm() {
750     return cipher_gost_grasshopper(EVP_CIPH_CTR_MODE, GRASSHOPPER_CIPHER_CTRACPKM);
751 }
752
753 void cipher_gost_grasshopper_destroy(void)
754 {
755     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_ECB]);
756     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_ECB] = NULL;
757     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CBC]);
758     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CBC] = NULL;
759     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_OFB]);
760     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_OFB] = NULL;
761     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CFB]);
762     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CFB] = NULL;
763     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTR]);
764     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTR] = NULL;
765     EVP_CIPHER_meth_free(gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKM]);
766     gost_grasshopper_ciphers[GRASSHOPPER_CIPHER_CTRACPKM] = NULL;
767 }
768
769 #if defined(__cplusplus)
770 }
771 #endif