evp_enc.c revision 296341
158234Skato/* crypto/evp/evp_enc.c */
258234Skato/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3169441Snyan * All rights reserved.
458234Skato *
579530Sru * This package is an SSL implementation written
658234Skato * by Eric Young (eay@cryptsoft.com).
758234Skato * The implementation was written so as to conform with Netscapes SSL.
8169441Snyan *
958234Skato * This library is free for commercial and non-commercial use as long as
1068960Sru * the following conditions are aheared to.  The following conditions
11156032Simp * apply to all code found in this distribution, be it the RC4, RSA,
12169416Snyan * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1358234Skato * included with this distribution is covered by the same copyright terms
1468960Sru * except that the holder is Tim Hudson (tjh@cryptsoft.com).
1558234Skato *
1658234Skato * Copyright remains Eric Young's, and as such any Copyright notices in
1758234Skato * the code are not to be removed.
1858234Skato * If this package is used in a product, Eric Young should be given attribution
1958234Skato * as the author of the parts of the library used.
2058234Skato * This can be in the form of a textual message at program startup or
2158234Skato * in documentation (online or textual) provided with the package.
22169441Snyan *
2358234Skato * Redistribution and use in source and binary forms, with or without
24169441Snyan * modification, are permitted provided that the following conditions
25131488Sru * are met:
26131488Sru * 1. Redistributions of source code must retain the copyright
27169441Snyan *    notice, this list of conditions and the following disclaimer.
28169441Snyan * 2. Redistributions in binary form must reproduce the above copyright
29169419Snyan *    notice, this list of conditions and the following disclaimer in the
3058234Skato *    documentation and/or other materials provided with the distribution.
31169441Snyan * 3. All advertising materials mentioning features or use of this software
32169419Snyan *    must display the following acknowledgement:
33169419Snyan *    "This product includes cryptographic software written by
34169441Snyan *     Eric Young (eay@cryptsoft.com)"
35169419Snyan *    The word 'cryptographic' can be left out if the rouines from the library
36169419Snyan *    being used are not cryptographic related :-).
3758234Skato * 4. If you include any Windows specific code (or a derivative thereof) from
38169441Snyan *    the apps directory (application code) you must include an acknowledgement:
39169419Snyan *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
4058234Skato *
4158234Skato * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4268716Sru * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43169419Snyan * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44169419Snyan * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45169419Snyan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46169419Snyan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47169419Snyan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48131488Sru * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49169441Snyan * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50131488Sru * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51169441Snyan * SUCH DAMAGE.
52169419Snyan *
5358234Skato * The licence and distribution terms for any publically available version or
5458234Skato * derivative of this code cannot be changed.  i.e. this code cannot simply be
5558234Skato * copied and put under another distribution licence
56169419Snyan * [including the GNU Public Licence.]
5758234Skato */
58169441Snyan
59131488Sru#include <stdio.h>
6058234Skato#include "cryptlib.h"
6158234Skato#include <openssl/evp.h>
6258234Skato#include <openssl/err.h>
63131488Sru#include <openssl/rand.h>
64169419Snyan#ifndef OPENSSL_NO_ENGINE
6558234Skato# include <openssl/engine.h>
6658234Skato#endif
6758234Skato#ifdef OPENSSL_FIPS
68169441Snyan# include <openssl/fips.h>
6958234Skato#endif
7058234Skato#include "evp_locl.h"
7158234Skato
72169441Snyan#ifdef OPENSSL_FIPS
7358234Skato# define M_do_cipher(ctx, out, in, inl) FIPS_cipher(ctx, out, in, inl)
74169441Snyan#else
75169419Snyan# define M_do_cipher(ctx, out, in, inl) ctx->cipher->do_cipher(ctx, out, in, inl)
76169419Snyan#endif
77169419Snyan
7858234Skatoconst char EVP_version[] = "EVP" OPENSSL_VERSION_PTEXT;
79131488Sru
80131488Sruvoid EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx)
8158234Skato{
82169419Snyan    memset(ctx, 0, sizeof(EVP_CIPHER_CTX));
83169419Snyan    /* ctx->cipher=NULL; */
84169419Snyan}
85131488Sru
8658234SkatoEVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
8758234Skato{
8858234Skato    EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
8971895Sru    if (ctx)
9058234Skato        EVP_CIPHER_CTX_init(ctx);
9158234Skato    return ctx;
92169441Snyan}
93131488Sru
94131488Sruint EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
95156032Simp                   const unsigned char *key, const unsigned char *iv, int enc)
96162395Sru{
97162395Sru    if (cipher)
98156032Simp        EVP_CIPHER_CTX_init(ctx);
99156032Simp    return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
100156032Simp}
101156032Simp
102169419Snyanint EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
103169441Snyan                      ENGINE *impl, const unsigned char *key,
104169419Snyan                      const unsigned char *iv, int enc)
105169419Snyan{
106169419Snyan    if (enc == -1)
107169419Snyan        enc = ctx->encrypt;
108169441Snyan    else {
10958234Skato        if (enc)
11058234Skato            enc = 1;
11158234Skato        ctx->encrypt = enc;
112169441Snyan    }
113131488Sru#ifndef OPENSSL_NO_ENGINE
11458234Skato    /*
115169441Snyan     * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
116131488Sru     * this context may already have an ENGINE! Try to avoid releasing the
11758234Skato     * previous handle, re-querying for an ENGINE, and having a
11858234Skato     * reinitialisation, when it may all be unecessary.
119169441Snyan     */
120131488Sru    if (ctx->engine && ctx->cipher && (!cipher ||
12158234Skato                                       (cipher
12258234Skato                                        && (cipher->nid ==
12358234Skato                                            ctx->cipher->nid))))
124131488Sru        goto skip_to_init;
125169441Snyan#endif
126131488Sru    if (cipher) {
12758234Skato        /*
12858234Skato         * Ensure a context left lying around from last time is cleared (the
12958234Skato         * previous check attempted to avoid this if the same ENGINE and
130169441Snyan         * EVP_CIPHER could be used).
13158234Skato         */
132169441Snyan        if (ctx->cipher) {
133131488Sru            unsigned long flags = ctx->flags;
13458234Skato            EVP_CIPHER_CTX_cleanup(ctx);
13558234Skato            /* Restore encrypt and flags */
13658234Skato            ctx->encrypt = enc;
13758234Skato            ctx->flags = flags;
13858234Skato        }
139169419Snyan#ifndef OPENSSL_NO_ENGINE
14081449Sru        if (impl) {
141169419Snyan            if (!ENGINE_init(impl)) {
142169419Snyan                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
143169419Snyan                return 0;
144169419Snyan            }
145169419Snyan        } else
146169419Snyan            /* Ask if an ENGINE is reserved for this job */
14758234Skato            impl = ENGINE_get_cipher_engine(cipher->nid);
148169441Snyan        if (impl) {
14958234Skato            /* There's an ENGINE for this job ... (apparently) */
15058234Skato            const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
151169419Snyan            if (!c) {
15258234Skato                /*
15358234Skato                 * One positive side-effect of US's export control history,
15479754Sdd                 * is that we should at least be able to avoid using US
15558234Skato                 * mispellings of "initialisation"?
15658234Skato                 */
15779754Sdd                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
15858234Skato                return 0;
15958234Skato            }
16058234Skato            /* We'll use the ENGINE's private cipher definition */
16158234Skato            cipher = c;
16258234Skato            /*
16358234Skato             * Store the ENGINE functional reference so we know 'cipher' came
16458234Skato             * from an ENGINE and we need to release it when done.
16558234Skato             */
16658234Skato            ctx->engine = impl;
16758234Skato        } else
16858234Skato            ctx->engine = NULL;
16958234Skato#endif
17058234Skato
17158234Skato#ifdef OPENSSL_FIPS
17258234Skato        if (FIPS_mode())
17358234Skato            return FIPS_cipherinit(ctx, cipher, key, iv, enc);
17458234Skato#endif
17558234Skato        ctx->cipher = cipher;
17658234Skato        if (ctx->cipher->ctx_size) {
17758234Skato            ctx->cipher_data = OPENSSL_malloc(ctx->cipher->ctx_size);
17858234Skato            if (!ctx->cipher_data) {
17958234Skato                EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
18058234Skato                return 0;
18158234Skato            }
18258234Skato        } else {
18358234Skato            ctx->cipher_data = NULL;
18458234Skato        }
18558234Skato        ctx->key_len = cipher->key_len;
18658234Skato        ctx->flags = 0;
18758234Skato        if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
18858234Skato            if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
18958234Skato                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
19058234Skato                return 0;
19158234Skato            }
19258234Skato        }
19358234Skato    } else if (!ctx->cipher) {
19458234Skato        EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
19558234Skato        return 0;
19658234Skato    }
19758234Skato#ifndef OPENSSL_NO_ENGINE
19858234Skato skip_to_init:
19958234Skato#endif
20058234Skato#ifdef OPENSSL_FIPS
20158234Skato    if (FIPS_mode())
20258234Skato        return FIPS_cipherinit(ctx, cipher, key, iv, enc);
203169441Snyan#endif
204169441Snyan    /* we assume block size is a power of 2 in *cryptUpdate */
205169419Snyan    OPENSSL_assert(ctx->cipher->block_size == 1
206169419Snyan                   || ctx->cipher->block_size == 8
207169419Snyan                   || ctx->cipher->block_size == 16);
208169441Snyan
20968716Sru    if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
21058234Skato        switch (EVP_CIPHER_CTX_mode(ctx)) {
21158234Skato
212169419Snyan        case EVP_CIPH_STREAM_CIPHER:
213169419Snyan        case EVP_CIPH_ECB_MODE:
214169419Snyan            break;
215169419Snyan
216169419Snyan        case EVP_CIPH_CFB_MODE:
21758234Skato        case EVP_CIPH_OFB_MODE:
218169441Snyan
219169419Snyan            ctx->num = 0;
220169419Snyan            /* fall-through */
221169419Snyan
222169419Snyan        case EVP_CIPH_CBC_MODE:
223169419Snyan
224169441Snyan            OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
22558234Skato                           (int)sizeof(ctx->iv));
226169441Snyan            if (iv)
227169419Snyan                memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
228169419Snyan            memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
229169419Snyan            break;
23058234Skato
23158234Skato        case EVP_CIPH_CTR_MODE:
23258234Skato            ctx->num = 0;
233169419Snyan            /* Don't reuse IV for CTR mode */
234156032Simp            if (iv)
235169419Snyan                memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
23658234Skato            break;
237169441Snyan
238169419Snyan        default:
23958234Skato            return 0;
240169419Snyan            break;
24158234Skato        }
242169419Snyan    }
243169419Snyan
244169419Snyan    if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
245169419Snyan        if (!ctx->cipher->init(ctx, key, iv, enc))
246169419Snyan            return 0;
24799501Scharnier    }
24899501Scharnier    ctx->buf_len = 0;
249169441Snyan    ctx->final_used = 0;
25058234Skato    ctx->block_mask = ctx->cipher->block_size - 1;
25158234Skato    return 1;
252169419Snyan}
253169419Snyan
254169441Snyanint EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
25599501Scharnier                     const unsigned char *in, int inl)
256169419Snyan{
257169419Snyan    if (ctx->encrypt)
25858234Skato        return EVP_EncryptUpdate(ctx, out, outl, in, inl);
25958234Skato    else
26071895Sru        return EVP_DecryptUpdate(ctx, out, outl, in, inl);
26158234Skato}
26258234Skato
263169419Snyanint EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
26458234Skato{
265169419Snyan    if (ctx->encrypt)
26658234Skato        return EVP_EncryptFinal_ex(ctx, out, outl);
267169441Snyan    else
26858234Skato        return EVP_DecryptFinal_ex(ctx, out, outl);
269169419Snyan}
270169441Snyan
271169419Snyanint EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
272169419Snyan{
27358234Skato    if (ctx->encrypt)
27458234Skato        return EVP_EncryptFinal(ctx, out, outl);
27558234Skato    else
276169419Snyan        return EVP_DecryptFinal(ctx, out, outl);
27758234Skato}
278169419Snyan
27958234Skatoint EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
28058234Skato                    const unsigned char *key, const unsigned char *iv)
281169441Snyan{
282169419Snyan    return EVP_CipherInit(ctx, cipher, key, iv, 1);
28358234Skato}
284169419Snyan
285169419Snyanint EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
286169419Snyan                       ENGINE *impl, const unsigned char *key,
287169441Snyan                       const unsigned char *iv)
28868716Sru{
28958234Skato    return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
29058234Skato}
291131488Sru
292169419Snyanint EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
293169419Snyan                    const unsigned char *key, const unsigned char *iv)
294169419Snyan{
295169419Snyan    return EVP_CipherInit(ctx, cipher, key, iv, 0);
296169419Snyan}
297169419Snyan
298169419Snyanint EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
29958234Skato                       ENGINE *impl, const unsigned char *key,
30058234Skato                       const unsigned char *iv)
30158234Skato{
30258234Skato    return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
30368716Sru}
304169441Snyan
30558234Skatoint EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
306169441Snyan                      const unsigned char *in, int inl)
307169441Snyan{
30858234Skato    int i, j, bl;
309169419Snyan
310169419Snyan    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
311169419Snyan        i = M_do_cipher(ctx, out, in, inl);
312131488Sru        if (i < 0)
313131488Sru            return 0;
314169419Snyan        else
315169419Snyan            *outl = i;
316169419Snyan        return 1;
31758234Skato    }
31858234Skato
31958234Skato    if (inl <= 0) {
320169441Snyan        *outl = 0;
32158234Skato        return inl == 0;
32258234Skato    }
323169419Snyan
324169419Snyan    if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
325169419Snyan        if (M_do_cipher(ctx, out, in, inl)) {
326169419Snyan            *outl = inl;
327169419Snyan            return 1;
32858234Skato        } else {
329169419Snyan            *outl = 0;
330169419Snyan            return 0;
331169419Snyan        }
332131488Sru    }
33358234Skato    i = ctx->buf_len;
334169419Snyan    bl = ctx->cipher->block_size;
335169419Snyan    OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
33658234Skato    if (i != 0) {
33758234Skato        if (i + inl < bl) {
338169419Snyan            memcpy(&(ctx->buf[i]), in, inl);
33958234Skato            ctx->buf_len += inl;
34058234Skato            *outl = 0;
341169419Snyan            return 1;
34258234Skato        } else {
34358234Skato            j = bl - i;
34458234Skato            memcpy(&(ctx->buf[i]), in, j);
34558234Skato            if (!M_do_cipher(ctx, out, ctx->buf, bl))
34658234Skato                return 0;
34758234Skato            inl -= j;
34858234Skato            in += j;
349169441Snyan            out += bl;
35058234Skato            *outl = bl;
35158234Skato        }
35258234Skato    } else
35368575Sru        *outl = 0;
35468575Sru    i = inl & (bl - 1);
35568575Sru    inl -= i;
35668575Sru    if (inl > 0) {
35768575Sru        if (!M_do_cipher(ctx, out, in, inl))
35858234Skato            return 0;
35958234Skato        *outl += inl;
360169419Snyan    }
361131488Sru
36268716Sru    if (i != 0)
363169441Snyan        memcpy(ctx->buf, &(in[inl]), i);
364169419Snyan    ctx->buf_len = i;
365169419Snyan    return 1;
36658234Skato}
367169441Snyan
36858234Skatoint EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
36958234Skato{
37058234Skato    int ret;
37168575Sru    ret = EVP_EncryptFinal_ex(ctx, out, outl);
37268575Sru    return ret;
37368575Sru}
37468575Sru
37568575Sruint EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
376169441Snyan{
377169441Snyan    int n, ret;
378169441Snyan    unsigned int i, b, bl;
379169419Snyan
38058234Skato    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
38158234Skato        ret = M_do_cipher(ctx, out, NULL, 0);
38258234Skato        if (ret < 0)
38358234Skato            return 0;
38458234Skato        else
38558234Skato            *outl = ret;
38658234Skato        return 1;
387169441Snyan    }
388169441Snyan
389169419Snyan    b = ctx->cipher->block_size;
390169419Snyan    OPENSSL_assert(b <= sizeof ctx->buf);
391169441Snyan    if (b == 1) {
39258234Skato        *outl = 0;
393169441Snyan        return 1;
394169419Snyan    }
395169419Snyan    bl = ctx->buf_len;
396169419Snyan    if (ctx->flags & EVP_CIPH_NO_PADDING) {
397169441Snyan        if (bl) {
398169441Snyan            EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
399169419Snyan                   EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
400169419Snyan            return 0;
401169441Snyan        }
40258234Skato        *outl = 0;
403169441Snyan        return 1;
40458234Skato    }
40558234Skato
40658234Skato    n = b - bl;
40758234Skato    for (i = bl; i < b; i++)
40858234Skato        ctx->buf[i] = n;
40968716Sru    ret = M_do_cipher(ctx, out, ctx->buf, b);
410169441Snyan
411169441Snyan    if (ret)
412169441Snyan        *outl = b;
413169419Snyan
414169419Snyan    return ret;
415169419Snyan}
41658234Skato
41758234Skatoint EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
41858234Skato                      const unsigned char *in, int inl)
41958234Skato{
42058234Skato    int fix_len;
42158234Skato    unsigned int b;
42258234Skato
42358234Skato    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
424169441Snyan        fix_len = M_do_cipher(ctx, out, in, inl);
42558234Skato        if (fix_len < 0) {
426169419Snyan            *outl = 0;
427169419Snyan            return 0;
428169441Snyan        } else
42968716Sru            *outl = fix_len;
430169441Snyan        return 1;
43158234Skato    }
43258234Skato
433169419Snyan    if (inl <= 0) {
434169419Snyan        *outl = 0;
435169441Snyan        return inl == 0;
43658234Skato    }
437169441Snyan
438169441Snyan    if (ctx->flags & EVP_CIPH_NO_PADDING)
439131488Sru        return EVP_EncryptUpdate(ctx, out, outl, in, inl);
44058234Skato
44158234Skato    b = ctx->cipher->block_size;
442169441Snyan    OPENSSL_assert(b <= sizeof ctx->final);
443169419Snyan
444169419Snyan    if (ctx->final_used) {
44558234Skato        memcpy(out, ctx->final, b);
44658234Skato        out += b;
447169416Snyan        fix_len = 1;
448169416Snyan    } else
449227558Sae        fix_len = 0;
450169416Snyan
45158234Skato    if (!EVP_EncryptUpdate(ctx, out, outl, in, inl))
452169441Snyan        return 0;
453169419Snyan
454169419Snyan    /*
455169419Snyan     * if we have 'decrypted' a multiple of block size, make sure we have a
45658234Skato     * copy of this last block
457169419Snyan     */
45858234Skato    if (b > 1 && !ctx->buf_len) {
459169441Snyan        *outl -= b;
460169441Snyan        ctx->final_used = 1;
461169441Snyan        memcpy(ctx->final, &out[*outl], b);
462169441Snyan    } else
463169441Snyan        ctx->final_used = 0;
464169441Snyan
465169441Snyan    if (fix_len)
466169441Snyan        *outl += b;
46758234Skato
46868716Sru    return 1;
46958234Skato}
470169416Snyan
47158234Skatoint EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
472{
473    int ret;
474    ret = EVP_DecryptFinal_ex(ctx, out, outl);
475    return ret;
476}
477
478int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
479{
480    int i, n;
481    unsigned int b;
482    *outl = 0;
483
484    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
485        i = M_do_cipher(ctx, out, NULL, 0);
486        if (i < 0)
487            return 0;
488        else
489            *outl = i;
490        return 1;
491    }
492
493    b = ctx->cipher->block_size;
494    if (ctx->flags & EVP_CIPH_NO_PADDING) {
495        if (ctx->buf_len) {
496            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
497                   EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
498            return 0;
499        }
500        *outl = 0;
501        return 1;
502    }
503    if (b > 1) {
504        if (ctx->buf_len || !ctx->final_used) {
505            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
506            return (0);
507        }
508        OPENSSL_assert(b <= sizeof ctx->final);
509
510        /*
511         * The following assumes that the ciphertext has been authenticated.
512         * Otherwise it provides a padding oracle.
513         */
514        n = ctx->final[b - 1];
515        if (n == 0 || n > (int)b) {
516            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
517            return (0);
518        }
519        for (i = 0; i < n; i++) {
520            if (ctx->final[--b] != n) {
521                EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
522                return (0);
523            }
524        }
525        n = ctx->cipher->block_size - n;
526        for (i = 0; i < n; i++)
527            out[i] = ctx->final[i];
528        *outl = n;
529    } else
530        *outl = 0;
531    return (1);
532}
533
534void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
535{
536    if (ctx) {
537        EVP_CIPHER_CTX_cleanup(ctx);
538        OPENSSL_free(ctx);
539    }
540}
541
542int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
543{
544#ifndef OPENSSL_FIPS
545    if (c->cipher != NULL) {
546        if (c->cipher->cleanup && !c->cipher->cleanup(c))
547            return 0;
548        /* Cleanse cipher context data */
549        if (c->cipher_data)
550            OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
551    }
552    if (c->cipher_data)
553        OPENSSL_free(c->cipher_data);
554#endif
555#ifndef OPENSSL_NO_ENGINE
556    if (c->engine)
557        /*
558         * The EVP_CIPHER we used belongs to an ENGINE, release the
559         * functional reference we held for this reason.
560         */
561        ENGINE_finish(c->engine);
562#endif
563#ifdef OPENSSL_FIPS
564    FIPS_cipher_ctx_cleanup(c);
565#endif
566    memset(c, 0, sizeof(EVP_CIPHER_CTX));
567    return 1;
568}
569
570int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
571{
572    if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
573        return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
574    if (c->key_len == keylen)
575        return 1;
576    if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
577        c->key_len = keylen;
578        return 1;
579    }
580    EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
581    return 0;
582}
583
584int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
585{
586    if (pad)
587        ctx->flags &= ~EVP_CIPH_NO_PADDING;
588    else
589        ctx->flags |= EVP_CIPH_NO_PADDING;
590    return 1;
591}
592
593int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
594{
595    int ret;
596    if (!ctx->cipher) {
597        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
598        return 0;
599    }
600
601    if (!ctx->cipher->ctrl) {
602        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
603        return 0;
604    }
605
606    ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
607    if (ret == -1) {
608        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
609               EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
610        return 0;
611    }
612    return ret;
613}
614
615int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
616{
617    if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
618        return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
619    if (RAND_bytes(key, ctx->key_len) <= 0)
620        return 0;
621    return 1;
622}
623
624int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
625{
626    if ((in == NULL) || (in->cipher == NULL)) {
627        EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
628        return 0;
629    }
630#ifndef OPENSSL_NO_ENGINE
631    /* Make sure it's safe to copy a cipher context using an ENGINE */
632    if (in->engine && !ENGINE_init(in->engine)) {
633        EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
634        return 0;
635    }
636#endif
637
638    EVP_CIPHER_CTX_cleanup(out);
639    memcpy(out, in, sizeof *out);
640
641    if (in->cipher_data && in->cipher->ctx_size) {
642        out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
643        if (!out->cipher_data) {
644            EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
645            return 0;
646        }
647        memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
648    }
649
650    if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
651        return in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out);
652    return 1;
653}
654