1/* crypto/evp/evp_enc.c */
2/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to.  The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 *    notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 *    notice, this list of conditions and the following disclaimer in the
30 *    documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 *    must display the following acknowledgement:
33 *    "This product includes cryptographic software written by
34 *     Eric Young (eay@cryptsoft.com)"
35 *    The word 'cryptographic' can be left out if the rouines from the library
36 *    being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 *    the apps directory (application code) you must include an acknowledgement:
39 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58
59#include <stdio.h>
60#include <limits.h>
61#include "cryptlib.h"
62#include <openssl/evp.h>
63#include <openssl/err.h>
64#include <openssl/rand.h>
65#ifndef OPENSSL_NO_ENGINE
66# include <openssl/engine.h>
67#endif
68#ifdef OPENSSL_FIPS
69# include <openssl/fips.h>
70#endif
71#include "evp_locl.h"
72
73#ifdef OPENSSL_FIPS
74# define M_do_cipher(ctx, out, in, inl) FIPS_cipher(ctx, out, in, inl)
75#else
76# define M_do_cipher(ctx, out, in, inl) ctx->cipher->do_cipher(ctx, out, in, inl)
77#endif
78
79const char EVP_version[] = "EVP" OPENSSL_VERSION_PTEXT;
80
81void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx)
82{
83    memset(ctx, 0, sizeof(EVP_CIPHER_CTX));
84    /* ctx->cipher=NULL; */
85}
86
87EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
88{
89    EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
90    if (ctx)
91        EVP_CIPHER_CTX_init(ctx);
92    return ctx;
93}
94
95int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
96                   const unsigned char *key, const unsigned char *iv, int enc)
97{
98    if (cipher)
99        EVP_CIPHER_CTX_init(ctx);
100    return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
101}
102
103int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
104                      ENGINE *impl, const unsigned char *key,
105                      const unsigned char *iv, int enc)
106{
107    if (enc == -1)
108        enc = ctx->encrypt;
109    else {
110        if (enc)
111            enc = 1;
112        ctx->encrypt = enc;
113    }
114#ifndef OPENSSL_NO_ENGINE
115    /*
116     * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
117     * this context may already have an ENGINE! Try to avoid releasing the
118     * previous handle, re-querying for an ENGINE, and having a
119     * reinitialisation, when it may all be unecessary.
120     */
121    if (ctx->engine && ctx->cipher && (!cipher ||
122                                       (cipher
123                                        && (cipher->nid ==
124                                            ctx->cipher->nid))))
125        goto skip_to_init;
126#endif
127    if (cipher) {
128        /*
129         * Ensure a context left lying around from last time is cleared (the
130         * previous check attempted to avoid this if the same ENGINE and
131         * EVP_CIPHER could be used).
132         */
133        if (ctx->cipher) {
134            unsigned long flags = ctx->flags;
135            EVP_CIPHER_CTX_cleanup(ctx);
136            /* Restore encrypt and flags */
137            ctx->encrypt = enc;
138            ctx->flags = flags;
139        }
140#ifndef OPENSSL_NO_ENGINE
141        if (impl) {
142            if (!ENGINE_init(impl)) {
143                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
144                return 0;
145            }
146        } else
147            /* Ask if an ENGINE is reserved for this job */
148            impl = ENGINE_get_cipher_engine(cipher->nid);
149        if (impl) {
150            /* There's an ENGINE for this job ... (apparently) */
151            const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
152            if (!c) {
153                /*
154                 * One positive side-effect of US's export control history,
155                 * is that we should at least be able to avoid using US
156                 * mispellings of "initialisation"?
157                 */
158                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
159                return 0;
160            }
161            /* We'll use the ENGINE's private cipher definition */
162            cipher = c;
163            /*
164             * Store the ENGINE functional reference so we know 'cipher' came
165             * from an ENGINE and we need to release it when done.
166             */
167            ctx->engine = impl;
168        } else
169            ctx->engine = NULL;
170#endif
171
172#ifdef OPENSSL_FIPS
173        if (FIPS_mode()) {
174            const EVP_CIPHER *fcipher = NULL;
175            if (cipher)
176                fcipher = evp_get_fips_cipher(cipher);
177            if (fcipher)
178                cipher = fcipher;
179            return FIPS_cipherinit(ctx, cipher, key, iv, enc);
180        }
181#endif
182        ctx->cipher = cipher;
183        if (ctx->cipher->ctx_size) {
184            ctx->cipher_data = OPENSSL_malloc(ctx->cipher->ctx_size);
185            if (!ctx->cipher_data) {
186                ctx->cipher = NULL;
187                EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
188                return 0;
189            }
190        } else {
191            ctx->cipher_data = NULL;
192        }
193        ctx->key_len = cipher->key_len;
194        /* Preserve wrap enable flag, zero everything else */
195        ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
196        if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
197            if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
198                ctx->cipher = NULL;
199                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
200                return 0;
201            }
202        }
203    } else if (!ctx->cipher) {
204        EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
205        return 0;
206    }
207#ifndef OPENSSL_NO_ENGINE
208 skip_to_init:
209#endif
210#ifdef OPENSSL_FIPS
211    if (FIPS_mode())
212        return FIPS_cipherinit(ctx, cipher, key, iv, enc);
213#endif
214    /* we assume block size is a power of 2 in *cryptUpdate */
215    OPENSSL_assert(ctx->cipher->block_size == 1
216                   || ctx->cipher->block_size == 8
217                   || ctx->cipher->block_size == 16);
218
219    if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
220        && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) {
221        EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED);
222        return 0;
223    }
224
225    if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
226        switch (EVP_CIPHER_CTX_mode(ctx)) {
227
228        case EVP_CIPH_STREAM_CIPHER:
229        case EVP_CIPH_ECB_MODE:
230            break;
231
232        case EVP_CIPH_CFB_MODE:
233        case EVP_CIPH_OFB_MODE:
234
235            ctx->num = 0;
236            /* fall-through */
237
238        case EVP_CIPH_CBC_MODE:
239
240            OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
241                           (int)sizeof(ctx->iv));
242            if (iv)
243                memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
244            memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
245            break;
246
247        case EVP_CIPH_CTR_MODE:
248            ctx->num = 0;
249            /* Don't reuse IV for CTR mode */
250            if (iv)
251                memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
252            break;
253
254        default:
255            return 0;
256            break;
257        }
258    }
259
260    if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
261        if (!ctx->cipher->init(ctx, key, iv, enc))
262            return 0;
263    }
264    ctx->buf_len = 0;
265    ctx->final_used = 0;
266    ctx->block_mask = ctx->cipher->block_size - 1;
267    return 1;
268}
269
270int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
271                     const unsigned char *in, int inl)
272{
273    if (ctx->encrypt)
274        return EVP_EncryptUpdate(ctx, out, outl, in, inl);
275    else
276        return EVP_DecryptUpdate(ctx, out, outl, in, inl);
277}
278
279int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
280{
281    if (ctx->encrypt)
282        return EVP_EncryptFinal_ex(ctx, out, outl);
283    else
284        return EVP_DecryptFinal_ex(ctx, out, outl);
285}
286
287int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
288{
289    if (ctx->encrypt)
290        return EVP_EncryptFinal(ctx, out, outl);
291    else
292        return EVP_DecryptFinal(ctx, out, outl);
293}
294
295int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
296                    const unsigned char *key, const unsigned char *iv)
297{
298    return EVP_CipherInit(ctx, cipher, key, iv, 1);
299}
300
301int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
302                       ENGINE *impl, const unsigned char *key,
303                       const unsigned char *iv)
304{
305    return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
306}
307
308int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
309                    const unsigned char *key, const unsigned char *iv)
310{
311    return EVP_CipherInit(ctx, cipher, key, iv, 0);
312}
313
314int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
315                       ENGINE *impl, const unsigned char *key,
316                       const unsigned char *iv)
317{
318    return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
319}
320
321static int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx,
322                                    unsigned char *out, int *outl,
323                                    const unsigned char *in, int inl)
324{
325    int i, j, bl;
326
327    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
328        i = M_do_cipher(ctx, out, in, inl);
329        if (i < 0)
330            return 0;
331        else
332            *outl = i;
333        return 1;
334    }
335
336    if (inl <= 0) {
337        *outl = 0;
338        return inl == 0;
339    }
340
341    if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
342        if (M_do_cipher(ctx, out, in, inl)) {
343            *outl = inl;
344            return 1;
345        } else {
346            *outl = 0;
347            return 0;
348        }
349    }
350    i = ctx->buf_len;
351    bl = ctx->cipher->block_size;
352    OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
353    if (i != 0) {
354        if (bl - i > inl) {
355            memcpy(&(ctx->buf[i]), in, inl);
356            ctx->buf_len += inl;
357            *outl = 0;
358            return 1;
359        } else {
360            j = bl - i;
361
362            /*
363             * Once we've processed the first j bytes from in, the amount of
364             * data left that is a multiple of the block length is:
365             * (inl - j) & ~(bl - 1)
366             * We must ensure that this amount of data, plus the one block that
367             * we process from ctx->buf does not exceed INT_MAX
368             */
369            if (((inl - j) & ~(bl - 1)) > INT_MAX - bl) {
370                EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE,
371                       EVP_R_OUTPUT_WOULD_OVERFLOW);
372                return 0;
373            }
374            memcpy(&(ctx->buf[i]), in, j);
375            if (!M_do_cipher(ctx, out, ctx->buf, bl))
376                return 0;
377            inl -= j;
378            in += j;
379            out += bl;
380            *outl = bl;
381        }
382    } else
383        *outl = 0;
384    i = inl & (bl - 1);
385    inl -= i;
386    if (inl > 0) {
387        if (!M_do_cipher(ctx, out, in, inl))
388            return 0;
389        *outl += inl;
390    }
391
392    if (i != 0)
393        memcpy(ctx->buf, &(in[inl]), i);
394    ctx->buf_len = i;
395    return 1;
396}
397
398int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
399                      const unsigned char *in, int inl)
400{
401    /* Prevent accidental use of decryption context when encrypting */
402    if (!ctx->encrypt) {
403        EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_INVALID_OPERATION);
404        return 0;
405    }
406
407    return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
408}
409
410int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
411{
412    int ret;
413    ret = EVP_EncryptFinal_ex(ctx, out, outl);
414    return ret;
415}
416
417int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
418{
419    int n, ret;
420    unsigned int i, b, bl;
421
422    /* Prevent accidental use of decryption context when encrypting */
423    if (!ctx->encrypt) {
424        EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_INVALID_OPERATION);
425        return 0;
426    }
427
428    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
429        ret = M_do_cipher(ctx, out, NULL, 0);
430        if (ret < 0)
431            return 0;
432        else
433            *outl = ret;
434        return 1;
435    }
436
437    b = ctx->cipher->block_size;
438    OPENSSL_assert(b <= sizeof(ctx->buf));
439    if (b == 1) {
440        *outl = 0;
441        return 1;
442    }
443    bl = ctx->buf_len;
444    if (ctx->flags & EVP_CIPH_NO_PADDING) {
445        if (bl) {
446            EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
447                   EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
448            return 0;
449        }
450        *outl = 0;
451        return 1;
452    }
453
454    n = b - bl;
455    for (i = bl; i < b; i++)
456        ctx->buf[i] = n;
457    ret = M_do_cipher(ctx, out, ctx->buf, b);
458
459    if (ret)
460        *outl = b;
461
462    return ret;
463}
464
465int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
466                      const unsigned char *in, int inl)
467{
468    int fix_len;
469    unsigned int b;
470
471    /* Prevent accidental use of encryption context when decrypting */
472    if (ctx->encrypt) {
473        EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_INVALID_OPERATION);
474        return 0;
475    }
476
477    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
478        fix_len = M_do_cipher(ctx, out, in, inl);
479        if (fix_len < 0) {
480            *outl = 0;
481            return 0;
482        } else
483            *outl = fix_len;
484        return 1;
485    }
486
487    if (inl <= 0) {
488        *outl = 0;
489        return inl == 0;
490    }
491
492    if (ctx->flags & EVP_CIPH_NO_PADDING)
493        return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
494
495    b = ctx->cipher->block_size;
496    OPENSSL_assert(b <= sizeof(ctx->final));
497
498    if (ctx->final_used) {
499        /*
500         * final_used is only ever set if buf_len is 0. Therefore the maximum
501         * length output we will ever see from evp_EncryptDecryptUpdate is
502         * the maximum multiple of the block length that is <= inl, or just:
503         * inl & ~(b - 1)
504         * Since final_used has been set then the final output length is:
505         * (inl & ~(b - 1)) + b
506         * This must never exceed INT_MAX
507         */
508        if ((inl & ~(b - 1)) > INT_MAX - b) {
509            EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_OUTPUT_WOULD_OVERFLOW);
510            return 0;
511        }
512        memcpy(out, ctx->final, b);
513        out += b;
514        fix_len = 1;
515    } else
516        fix_len = 0;
517
518    if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl))
519        return 0;
520
521    /*
522     * if we have 'decrypted' a multiple of block size, make sure we have a
523     * copy of this last block
524     */
525    if (b > 1 && !ctx->buf_len) {
526        *outl -= b;
527        ctx->final_used = 1;
528        memcpy(ctx->final, &out[*outl], b);
529    } else
530        ctx->final_used = 0;
531
532    if (fix_len)
533        *outl += b;
534
535    return 1;
536}
537
538int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
539{
540    int ret;
541    ret = EVP_DecryptFinal_ex(ctx, out, outl);
542    return ret;
543}
544
545int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
546{
547    int i, n;
548    unsigned int b;
549
550    /* Prevent accidental use of encryption context when decrypting */
551    if (ctx->encrypt) {
552        EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_INVALID_OPERATION);
553        return 0;
554    }
555
556    *outl = 0;
557
558    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
559        i = M_do_cipher(ctx, out, NULL, 0);
560        if (i < 0)
561            return 0;
562        else
563            *outl = i;
564        return 1;
565    }
566
567    b = ctx->cipher->block_size;
568    if (ctx->flags & EVP_CIPH_NO_PADDING) {
569        if (ctx->buf_len) {
570            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
571                   EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
572            return 0;
573        }
574        *outl = 0;
575        return 1;
576    }
577    if (b > 1) {
578        if (ctx->buf_len || !ctx->final_used) {
579            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
580            return (0);
581        }
582        OPENSSL_assert(b <= sizeof(ctx->final));
583
584        /*
585         * The following assumes that the ciphertext has been authenticated.
586         * Otherwise it provides a padding oracle.
587         */
588        n = ctx->final[b - 1];
589        if (n == 0 || n > (int)b) {
590            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
591            return (0);
592        }
593        for (i = 0; i < n; i++) {
594            if (ctx->final[--b] != n) {
595                EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
596                return (0);
597            }
598        }
599        n = ctx->cipher->block_size - n;
600        for (i = 0; i < n; i++)
601            out[i] = ctx->final[i];
602        *outl = n;
603    } else
604        *outl = 0;
605    return (1);
606}
607
608void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
609{
610    if (ctx) {
611        EVP_CIPHER_CTX_cleanup(ctx);
612        OPENSSL_free(ctx);
613    }
614}
615
616int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
617{
618#ifndef OPENSSL_FIPS
619    if (c->cipher != NULL) {
620        if (c->cipher->cleanup && !c->cipher->cleanup(c))
621            return 0;
622        /* Cleanse cipher context data */
623        if (c->cipher_data)
624            OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
625    }
626    if (c->cipher_data)
627        OPENSSL_free(c->cipher_data);
628#endif
629#ifndef OPENSSL_NO_ENGINE
630    if (c->engine)
631        /*
632         * The EVP_CIPHER we used belongs to an ENGINE, release the
633         * functional reference we held for this reason.
634         */
635        ENGINE_finish(c->engine);
636#endif
637#ifdef OPENSSL_FIPS
638    FIPS_cipher_ctx_cleanup(c);
639#endif
640    memset(c, 0, sizeof(EVP_CIPHER_CTX));
641    return 1;
642}
643
644int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
645{
646    if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
647        return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
648    if (c->key_len == keylen)
649        return 1;
650    if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
651        c->key_len = keylen;
652        return 1;
653    }
654    EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
655    return 0;
656}
657
658int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
659{
660    if (pad)
661        ctx->flags &= ~EVP_CIPH_NO_PADDING;
662    else
663        ctx->flags |= EVP_CIPH_NO_PADDING;
664    return 1;
665}
666
667int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
668{
669    int ret;
670    if (!ctx->cipher) {
671        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
672        return 0;
673    }
674
675    if (!ctx->cipher->ctrl) {
676        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
677        return 0;
678    }
679
680    ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
681    if (ret == -1) {
682        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
683               EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
684        return 0;
685    }
686    return ret;
687}
688
689int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
690{
691    if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
692        return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
693    if (RAND_bytes(key, ctx->key_len) <= 0)
694        return 0;
695    return 1;
696}
697
698int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
699{
700    if ((in == NULL) || (in->cipher == NULL)) {
701        EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
702        return 0;
703    }
704#ifndef OPENSSL_NO_ENGINE
705    /* Make sure it's safe to copy a cipher context using an ENGINE */
706    if (in->engine && !ENGINE_init(in->engine)) {
707        EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
708        return 0;
709    }
710#endif
711
712    EVP_CIPHER_CTX_cleanup(out);
713    memcpy(out, in, sizeof(*out));
714
715    if (in->cipher_data && in->cipher->ctx_size) {
716        out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
717        if (!out->cipher_data) {
718            out->cipher = NULL;
719            EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
720            return 0;
721        }
722        memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
723    }
724
725    if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
726        if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
727            out->cipher = NULL;
728            EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR);
729            return 0;
730        }
731    return 1;
732}
733