155714Skris/* crypto/evp/evp_enc.c */
255714Skris/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
355714Skris * All rights reserved.
455714Skris *
555714Skris * This package is an SSL implementation written
655714Skris * by Eric Young (eay@cryptsoft.com).
755714Skris * The implementation was written so as to conform with Netscapes SSL.
8280297Sjkim *
955714Skris * This library is free for commercial and non-commercial use as long as
1055714Skris * the following conditions are aheared to.  The following conditions
1155714Skris * apply to all code found in this distribution, be it the RC4, RSA,
1255714Skris * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1355714Skris * included with this distribution is covered by the same copyright terms
1455714Skris * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15280297Sjkim *
1655714Skris * Copyright remains Eric Young's, and as such any Copyright notices in
1755714Skris * the code are not to be removed.
1855714Skris * If this package is used in a product, Eric Young should be given attribution
1955714Skris * as the author of the parts of the library used.
2055714Skris * This can be in the form of a textual message at program startup or
2155714Skris * in documentation (online or textual) provided with the package.
22280297Sjkim *
2355714Skris * Redistribution and use in source and binary forms, with or without
2455714Skris * modification, are permitted provided that the following conditions
2555714Skris * are met:
2655714Skris * 1. Redistributions of source code must retain the copyright
2755714Skris *    notice, this list of conditions and the following disclaimer.
2855714Skris * 2. Redistributions in binary form must reproduce the above copyright
2955714Skris *    notice, this list of conditions and the following disclaimer in the
3055714Skris *    documentation and/or other materials provided with the distribution.
3155714Skris * 3. All advertising materials mentioning features or use of this software
3255714Skris *    must display the following acknowledgement:
3355714Skris *    "This product includes cryptographic software written by
3455714Skris *     Eric Young (eay@cryptsoft.com)"
3555714Skris *    The word 'cryptographic' can be left out if the rouines from the library
3655714Skris *    being used are not cryptographic related :-).
37280297Sjkim * 4. If you include any Windows specific code (or a derivative thereof) from
3855714Skris *    the apps directory (application code) you must include an acknowledgement:
3955714Skris *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40280297Sjkim *
4155714Skris * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4255714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4355714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4455714Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4555714Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4655714Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4755714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4855714Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4955714Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
5055714Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
5155714Skris * SUCH DAMAGE.
52280297Sjkim *
5355714Skris * The licence and distribution terms for any publically available version or
5455714Skris * derivative of this code cannot be changed.  i.e. this code cannot simply be
5555714Skris * copied and put under another distribution licence
5655714Skris * [including the GNU Public Licence.]
5755714Skris */
5855714Skris
5955714Skris#include <stdio.h>
60369299Sjkim#include <limits.h>
6155714Skris#include "cryptlib.h"
6255714Skris#include <openssl/evp.h>
6368651Skris#include <openssl/err.h>
64160814Ssimon#include <openssl/rand.h>
65111147Snectar#ifndef OPENSSL_NO_ENGINE
66280297Sjkim# include <openssl/engine.h>
67111147Snectar#endif
68238405Sjkim#ifdef OPENSSL_FIPS
69280297Sjkim# include <openssl/fips.h>
70238405Sjkim#endif
7168651Skris#include "evp_locl.h"
7255714Skris
73194206Ssimon#ifdef OPENSSL_FIPS
74280297Sjkim# define M_do_cipher(ctx, out, in, inl) FIPS_cipher(ctx, out, in, inl)
75194206Ssimon#else
76280297Sjkim# define M_do_cipher(ctx, out, in, inl) ctx->cipher->do_cipher(ctx, out, in, inl)
77194206Ssimon#endif
78194206Ssimon
79280297Sjkimconst char EVP_version[] = "EVP" OPENSSL_VERSION_PTEXT;
80238405Sjkim
81238405Sjkimvoid EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx)
82280297Sjkim{
83280297Sjkim    memset(ctx, 0, sizeof(EVP_CIPHER_CTX));
84280297Sjkim    /* ctx->cipher=NULL; */
85280297Sjkim}
86238405Sjkim
87160814SsimonEVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void)
88280297Sjkim{
89331638Sjkim    EVP_CIPHER_CTX *ctx = OPENSSL_malloc(sizeof(*ctx));
90280297Sjkim    if (ctx)
91280297Sjkim        EVP_CIPHER_CTX_init(ctx);
92280297Sjkim    return ctx;
93280297Sjkim}
94109998Smarkm
9568651Skrisint EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
96280297Sjkim                   const unsigned char *key, const unsigned char *iv, int enc)
97280297Sjkim{
98280297Sjkim    if (cipher)
99280297Sjkim        EVP_CIPHER_CTX_init(ctx);
100280297Sjkim    return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, enc);
101280297Sjkim}
102109998Smarkm
103280297Sjkimint EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
104280297Sjkim                      ENGINE *impl, const unsigned char *key,
105280297Sjkim                      const unsigned char *iv, int enc)
106280297Sjkim{
107280297Sjkim    if (enc == -1)
108280297Sjkim        enc = ctx->encrypt;
109280297Sjkim    else {
110280297Sjkim        if (enc)
111280297Sjkim            enc = 1;
112280297Sjkim        ctx->encrypt = enc;
113280297Sjkim    }
114238405Sjkim#ifndef OPENSSL_NO_ENGINE
115280297Sjkim    /*
116280297Sjkim     * Whether it's nice or not, "Inits" can be used on "Final"'d contexts so
117280297Sjkim     * this context may already have an ENGINE! Try to avoid releasing the
118280297Sjkim     * previous handle, re-querying for an ENGINE, and having a
119280297Sjkim     * reinitialisation, when it may all be unecessary.
120280297Sjkim     */
121280297Sjkim    if (ctx->engine && ctx->cipher && (!cipher ||
122280297Sjkim                                       (cipher
123280297Sjkim                                        && (cipher->nid ==
124280297Sjkim                                            ctx->cipher->nid))))
125280297Sjkim        goto skip_to_init;
126238405Sjkim#endif
127280297Sjkim    if (cipher) {
128280297Sjkim        /*
129280297Sjkim         * Ensure a context left lying around from last time is cleared (the
130280297Sjkim         * previous check attempted to avoid this if the same ENGINE and
131280297Sjkim         * EVP_CIPHER could be used).
132280297Sjkim         */
133280297Sjkim        if (ctx->cipher) {
134280297Sjkim            unsigned long flags = ctx->flags;
135280297Sjkim            EVP_CIPHER_CTX_cleanup(ctx);
136280297Sjkim            /* Restore encrypt and flags */
137280297Sjkim            ctx->encrypt = enc;
138280297Sjkim            ctx->flags = flags;
139280297Sjkim        }
140238405Sjkim#ifndef OPENSSL_NO_ENGINE
141280297Sjkim        if (impl) {
142280297Sjkim            if (!ENGINE_init(impl)) {
143280297Sjkim                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
144280297Sjkim                return 0;
145280297Sjkim            }
146280297Sjkim        } else
147280297Sjkim            /* Ask if an ENGINE is reserved for this job */
148280297Sjkim            impl = ENGINE_get_cipher_engine(cipher->nid);
149280297Sjkim        if (impl) {
150280297Sjkim            /* There's an ENGINE for this job ... (apparently) */
151280297Sjkim            const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
152280297Sjkim            if (!c) {
153280297Sjkim                /*
154280297Sjkim                 * One positive side-effect of US's export control history,
155280297Sjkim                 * is that we should at least be able to avoid using US
156280297Sjkim                 * mispellings of "initialisation"?
157280297Sjkim                 */
158280297Sjkim                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
159280297Sjkim                return 0;
160280297Sjkim            }
161280297Sjkim            /* We'll use the ENGINE's private cipher definition */
162280297Sjkim            cipher = c;
163280297Sjkim            /*
164280297Sjkim             * Store the ENGINE functional reference so we know 'cipher' came
165280297Sjkim             * from an ENGINE and we need to release it when done.
166280297Sjkim             */
167280297Sjkim            ctx->engine = impl;
168280297Sjkim        } else
169280297Sjkim            ctx->engine = NULL;
170238405Sjkim#endif
171238405Sjkim
172238405Sjkim#ifdef OPENSSL_FIPS
173290207Sjkim        if (FIPS_mode()) {
174306195Sjkim            const EVP_CIPHER *fcipher = NULL;
175290207Sjkim            if (cipher)
176290207Sjkim                fcipher = evp_get_fips_cipher(cipher);
177290207Sjkim            if (fcipher)
178290207Sjkim                cipher = fcipher;
179280297Sjkim            return FIPS_cipherinit(ctx, cipher, key, iv, enc);
180290207Sjkim        }
181238405Sjkim#endif
182280297Sjkim        ctx->cipher = cipher;
183280297Sjkim        if (ctx->cipher->ctx_size) {
184280297Sjkim            ctx->cipher_data = OPENSSL_malloc(ctx->cipher->ctx_size);
185280297Sjkim            if (!ctx->cipher_data) {
186325335Sjkim                ctx->cipher = NULL;
187280297Sjkim                EVPerr(EVP_F_EVP_CIPHERINIT_EX, ERR_R_MALLOC_FAILURE);
188280297Sjkim                return 0;
189280297Sjkim            }
190280297Sjkim        } else {
191280297Sjkim            ctx->cipher_data = NULL;
192280297Sjkim        }
193280297Sjkim        ctx->key_len = cipher->key_len;
194290207Sjkim        /* Preserve wrap enable flag, zero everything else */
195290207Sjkim        ctx->flags &= EVP_CIPHER_CTX_FLAG_WRAP_ALLOW;
196280297Sjkim        if (ctx->cipher->flags & EVP_CIPH_CTRL_INIT) {
197280297Sjkim            if (!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL)) {
198325335Sjkim                ctx->cipher = NULL;
199280297Sjkim                EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_INITIALIZATION_ERROR);
200280297Sjkim                return 0;
201280297Sjkim            }
202280297Sjkim        }
203280297Sjkim    } else if (!ctx->cipher) {
204280297Sjkim        EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_NO_CIPHER_SET);
205280297Sjkim        return 0;
206280297Sjkim    }
207238405Sjkim#ifndef OPENSSL_NO_ENGINE
208280297Sjkim skip_to_init:
209238405Sjkim#endif
210238405Sjkim#ifdef OPENSSL_FIPS
211280297Sjkim    if (FIPS_mode())
212280297Sjkim        return FIPS_cipherinit(ctx, cipher, key, iv, enc);
213238405Sjkim#endif
214280297Sjkim    /* we assume block size is a power of 2 in *cryptUpdate */
215280297Sjkim    OPENSSL_assert(ctx->cipher->block_size == 1
216280297Sjkim                   || ctx->cipher->block_size == 8
217280297Sjkim                   || ctx->cipher->block_size == 16);
218238405Sjkim
219290207Sjkim    if (!(ctx->flags & EVP_CIPHER_CTX_FLAG_WRAP_ALLOW)
220290207Sjkim        && EVP_CIPHER_CTX_mode(ctx) == EVP_CIPH_WRAP_MODE) {
221290207Sjkim        EVPerr(EVP_F_EVP_CIPHERINIT_EX, EVP_R_WRAP_MODE_NOT_ALLOWED);
222290207Sjkim        return 0;
223290207Sjkim    }
224290207Sjkim
225280297Sjkim    if (!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
226280297Sjkim        switch (EVP_CIPHER_CTX_mode(ctx)) {
227238405Sjkim
228280297Sjkim        case EVP_CIPH_STREAM_CIPHER:
229280297Sjkim        case EVP_CIPH_ECB_MODE:
230280297Sjkim            break;
231238405Sjkim
232280297Sjkim        case EVP_CIPH_CFB_MODE:
233280297Sjkim        case EVP_CIPH_OFB_MODE:
234238405Sjkim
235280297Sjkim            ctx->num = 0;
236280297Sjkim            /* fall-through */
237238405Sjkim
238280297Sjkim        case EVP_CIPH_CBC_MODE:
239238405Sjkim
240280297Sjkim            OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) <=
241280297Sjkim                           (int)sizeof(ctx->iv));
242280297Sjkim            if (iv)
243280297Sjkim                memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
244280297Sjkim            memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
245280297Sjkim            break;
246238405Sjkim
247280297Sjkim        case EVP_CIPH_CTR_MODE:
248280297Sjkim            ctx->num = 0;
249280297Sjkim            /* Don't reuse IV for CTR mode */
250280297Sjkim            if (iv)
251280297Sjkim                memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
252280297Sjkim            break;
253238405Sjkim
254280297Sjkim        default:
255280297Sjkim            return 0;
256280297Sjkim            break;
257280297Sjkim        }
258280297Sjkim    }
259238405Sjkim
260280297Sjkim    if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
261280297Sjkim        if (!ctx->cipher->init(ctx, key, iv, enc))
262280297Sjkim            return 0;
263280297Sjkim    }
264280297Sjkim    ctx->buf_len = 0;
265280297Sjkim    ctx->final_used = 0;
266280297Sjkim    ctx->block_mask = ctx->cipher->block_size - 1;
267280297Sjkim    return 1;
268280297Sjkim}
269238405Sjkim
27068651Skrisint EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
271280297Sjkim                     const unsigned char *in, int inl)
272280297Sjkim{
273280297Sjkim    if (ctx->encrypt)
274280297Sjkim        return EVP_EncryptUpdate(ctx, out, outl, in, inl);
275280297Sjkim    else
276280297Sjkim        return EVP_DecryptUpdate(ctx, out, outl, in, inl);
277280297Sjkim}
27855714Skris
279109998Smarkmint EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
280280297Sjkim{
281280297Sjkim    if (ctx->encrypt)
282280297Sjkim        return EVP_EncryptFinal_ex(ctx, out, outl);
283280297Sjkim    else
284280297Sjkim        return EVP_DecryptFinal_ex(ctx, out, outl);
285280297Sjkim}
286109998Smarkm
28755714Skrisint EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
288280297Sjkim{
289280297Sjkim    if (ctx->encrypt)
290280297Sjkim        return EVP_EncryptFinal(ctx, out, outl);
291280297Sjkim    else
292280297Sjkim        return EVP_DecryptFinal(ctx, out, outl);
293280297Sjkim}
29455714Skris
29568651Skrisint EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
296280297Sjkim                    const unsigned char *key, const unsigned char *iv)
297280297Sjkim{
298280297Sjkim    return EVP_CipherInit(ctx, cipher, key, iv, 1);
299280297Sjkim}
30055714Skris
301280297Sjkimint EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
302280297Sjkim                       ENGINE *impl, const unsigned char *key,
303280297Sjkim                       const unsigned char *iv)
304280297Sjkim{
305280297Sjkim    return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
306280297Sjkim}
307109998Smarkm
30868651Skrisint EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
309280297Sjkim                    const unsigned char *key, const unsigned char *iv)
310280297Sjkim{
311280297Sjkim    return EVP_CipherInit(ctx, cipher, key, iv, 0);
312280297Sjkim}
31355714Skris
314280297Sjkimint EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
315280297Sjkim                       ENGINE *impl, const unsigned char *key,
316280297Sjkim                       const unsigned char *iv)
317280297Sjkim{
318280297Sjkim    return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
319280297Sjkim}
32055714Skris
321344604Sjkimstatic int evp_EncryptDecryptUpdate(EVP_CIPHER_CTX *ctx,
322344604Sjkim                                    unsigned char *out, int *outl,
323344604Sjkim                                    const unsigned char *in, int inl)
324280297Sjkim{
325280297Sjkim    int i, j, bl;
32655714Skris
327280297Sjkim    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
328280297Sjkim        i = M_do_cipher(ctx, out, in, inl);
329280297Sjkim        if (i < 0)
330280297Sjkim            return 0;
331280297Sjkim        else
332280297Sjkim            *outl = i;
333280297Sjkim        return 1;
334280297Sjkim    }
335238405Sjkim
336280297Sjkim    if (inl <= 0) {
337280297Sjkim        *outl = 0;
338280297Sjkim        return inl == 0;
339280297Sjkim    }
340194206Ssimon
341280297Sjkim    if (ctx->buf_len == 0 && (inl & (ctx->block_mask)) == 0) {
342280297Sjkim        if (M_do_cipher(ctx, out, in, inl)) {
343280297Sjkim            *outl = inl;
344280297Sjkim            return 1;
345280297Sjkim        } else {
346280297Sjkim            *outl = 0;
347280297Sjkim            return 0;
348280297Sjkim        }
349280297Sjkim    }
350280297Sjkim    i = ctx->buf_len;
351280297Sjkim    bl = ctx->cipher->block_size;
352280297Sjkim    OPENSSL_assert(bl <= (int)sizeof(ctx->buf));
353280297Sjkim    if (i != 0) {
354298998Sjkim        if (bl - i > inl) {
355280297Sjkim            memcpy(&(ctx->buf[i]), in, inl);
356280297Sjkim            ctx->buf_len += inl;
357280297Sjkim            *outl = 0;
358280297Sjkim            return 1;
359280297Sjkim        } else {
360280297Sjkim            j = bl - i;
361369299Sjkim
362369299Sjkim            /*
363369299Sjkim             * Once we've processed the first j bytes from in, the amount of
364369299Sjkim             * data left that is a multiple of the block length is:
365369299Sjkim             * (inl - j) & ~(bl - 1)
366369299Sjkim             * We must ensure that this amount of data, plus the one block that
367369299Sjkim             * we process from ctx->buf does not exceed INT_MAX
368369299Sjkim             */
369369299Sjkim            if (((inl - j) & ~(bl - 1)) > INT_MAX - bl) {
370369299Sjkim                EVPerr(EVP_F_EVP_ENCRYPTDECRYPTUPDATE,
371369299Sjkim                       EVP_R_OUTPUT_WOULD_OVERFLOW);
372369299Sjkim                return 0;
373369299Sjkim            }
374280297Sjkim            memcpy(&(ctx->buf[i]), in, j);
375280297Sjkim            if (!M_do_cipher(ctx, out, ctx->buf, bl))
376280297Sjkim                return 0;
377280297Sjkim            inl -= j;
378280297Sjkim            in += j;
379280297Sjkim            out += bl;
380280297Sjkim            *outl = bl;
381280297Sjkim        }
382280297Sjkim    } else
383280297Sjkim        *outl = 0;
384280297Sjkim    i = inl & (bl - 1);
385280297Sjkim    inl -= i;
386280297Sjkim    if (inl > 0) {
387280297Sjkim        if (!M_do_cipher(ctx, out, in, inl))
388280297Sjkim            return 0;
389280297Sjkim        *outl += inl;
390280297Sjkim    }
39155714Skris
392280297Sjkim    if (i != 0)
393280297Sjkim        memcpy(ctx->buf, &(in[inl]), i);
394280297Sjkim    ctx->buf_len = i;
395280297Sjkim    return 1;
396280297Sjkim}
39755714Skris
398344604Sjkimint EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
399344604Sjkim                      const unsigned char *in, int inl)
400344604Sjkim{
401344604Sjkim    /* Prevent accidental use of decryption context when encrypting */
402344604Sjkim    if (!ctx->encrypt) {
403344604Sjkim        EVPerr(EVP_F_EVP_ENCRYPTUPDATE, EVP_R_INVALID_OPERATION);
404344604Sjkim        return 0;
405344604Sjkim    }
406344604Sjkim
407344604Sjkim    return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
408344604Sjkim}
409344604Sjkim
41068651Skrisint EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
411280297Sjkim{
412280297Sjkim    int ret;
413280297Sjkim    ret = EVP_EncryptFinal_ex(ctx, out, outl);
414280297Sjkim    return ret;
415280297Sjkim}
41655714Skris
417109998Smarkmint EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
418280297Sjkim{
419280297Sjkim    int n, ret;
420280297Sjkim    unsigned int i, b, bl;
421109998Smarkm
422344604Sjkim    /* Prevent accidental use of decryption context when encrypting */
423344604Sjkim    if (!ctx->encrypt) {
424344604Sjkim        EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX, EVP_R_INVALID_OPERATION);
425344604Sjkim        return 0;
426344604Sjkim    }
427344604Sjkim
428280297Sjkim    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
429280297Sjkim        ret = M_do_cipher(ctx, out, NULL, 0);
430280297Sjkim        if (ret < 0)
431280297Sjkim            return 0;
432280297Sjkim        else
433280297Sjkim            *outl = ret;
434280297Sjkim        return 1;
435280297Sjkim    }
436238405Sjkim
437280297Sjkim    b = ctx->cipher->block_size;
438331638Sjkim    OPENSSL_assert(b <= sizeof(ctx->buf));
439280297Sjkim    if (b == 1) {
440280297Sjkim        *outl = 0;
441280297Sjkim        return 1;
442280297Sjkim    }
443280297Sjkim    bl = ctx->buf_len;
444280297Sjkim    if (ctx->flags & EVP_CIPH_NO_PADDING) {
445280297Sjkim        if (bl) {
446280297Sjkim            EVPerr(EVP_F_EVP_ENCRYPTFINAL_EX,
447280297Sjkim                   EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
448280297Sjkim            return 0;
449280297Sjkim        }
450280297Sjkim        *outl = 0;
451280297Sjkim        return 1;
452280297Sjkim    }
453109998Smarkm
454280297Sjkim    n = b - bl;
455280297Sjkim    for (i = bl; i < b; i++)
456280297Sjkim        ctx->buf[i] = n;
457280297Sjkim    ret = M_do_cipher(ctx, out, ctx->buf, b);
458109998Smarkm
459280297Sjkim    if (ret)
460280297Sjkim        *outl = b;
461109998Smarkm
462280297Sjkim    return ret;
463280297Sjkim}
464109998Smarkm
46568651Skrisint EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
466280297Sjkim                      const unsigned char *in, int inl)
467280297Sjkim{
468280297Sjkim    int fix_len;
469280297Sjkim    unsigned int b;
47055714Skris
471344604Sjkim    /* Prevent accidental use of encryption context when decrypting */
472344604Sjkim    if (ctx->encrypt) {
473344604Sjkim        EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_INVALID_OPERATION);
474344604Sjkim        return 0;
475344604Sjkim    }
476344604Sjkim
477280297Sjkim    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
478280297Sjkim        fix_len = M_do_cipher(ctx, out, in, inl);
479280297Sjkim        if (fix_len < 0) {
480280297Sjkim            *outl = 0;
481280297Sjkim            return 0;
482280297Sjkim        } else
483280297Sjkim            *outl = fix_len;
484280297Sjkim        return 1;
485280297Sjkim    }
486238405Sjkim
487280297Sjkim    if (inl <= 0) {
488280297Sjkim        *outl = 0;
489280297Sjkim        return inl == 0;
490280297Sjkim    }
49155714Skris
492280297Sjkim    if (ctx->flags & EVP_CIPH_NO_PADDING)
493344604Sjkim        return evp_EncryptDecryptUpdate(ctx, out, outl, in, inl);
494109998Smarkm
495280297Sjkim    b = ctx->cipher->block_size;
496331638Sjkim    OPENSSL_assert(b <= sizeof(ctx->final));
497109998Smarkm
498280297Sjkim    if (ctx->final_used) {
499369299Sjkim        /*
500369299Sjkim         * final_used is only ever set if buf_len is 0. Therefore the maximum
501369299Sjkim         * length output we will ever see from evp_EncryptDecryptUpdate is
502369299Sjkim         * the maximum multiple of the block length that is <= inl, or just:
503369299Sjkim         * inl & ~(b - 1)
504369299Sjkim         * Since final_used has been set then the final output length is:
505369299Sjkim         * (inl & ~(b - 1)) + b
506369299Sjkim         * This must never exceed INT_MAX
507369299Sjkim         */
508369299Sjkim        if ((inl & ~(b - 1)) > INT_MAX - b) {
509369299Sjkim            EVPerr(EVP_F_EVP_DECRYPTUPDATE, EVP_R_OUTPUT_WOULD_OVERFLOW);
510369299Sjkim            return 0;
511369299Sjkim        }
512280297Sjkim        memcpy(out, ctx->final, b);
513280297Sjkim        out += b;
514280297Sjkim        fix_len = 1;
515280297Sjkim    } else
516280297Sjkim        fix_len = 0;
51755714Skris
518344604Sjkim    if (!evp_EncryptDecryptUpdate(ctx, out, outl, in, inl))
519280297Sjkim        return 0;
520109998Smarkm
521280297Sjkim    /*
522280297Sjkim     * if we have 'decrypted' a multiple of block size, make sure we have a
523280297Sjkim     * copy of this last block
524280297Sjkim     */
525280297Sjkim    if (b > 1 && !ctx->buf_len) {
526280297Sjkim        *outl -= b;
527280297Sjkim        ctx->final_used = 1;
528280297Sjkim        memcpy(ctx->final, &out[*outl], b);
529280297Sjkim    } else
530280297Sjkim        ctx->final_used = 0;
531109998Smarkm
532280297Sjkim    if (fix_len)
533280297Sjkim        *outl += b;
534109998Smarkm
535280297Sjkim    return 1;
536280297Sjkim}
53755714Skris
53855714Skrisint EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
539280297Sjkim{
540280297Sjkim    int ret;
541280297Sjkim    ret = EVP_DecryptFinal_ex(ctx, out, outl);
542280297Sjkim    return ret;
543280297Sjkim}
544109998Smarkm
545109998Smarkmint EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
546280297Sjkim{
547280297Sjkim    int i, n;
548280297Sjkim    unsigned int b;
549344604Sjkim
550344604Sjkim    /* Prevent accidental use of encryption context when decrypting */
551344604Sjkim    if (ctx->encrypt) {
552344604Sjkim        EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_INVALID_OPERATION);
553344604Sjkim        return 0;
554344604Sjkim    }
555344604Sjkim
556280297Sjkim    *outl = 0;
55755714Skris
558280297Sjkim    if (ctx->cipher->flags & EVP_CIPH_FLAG_CUSTOM_CIPHER) {
559280297Sjkim        i = M_do_cipher(ctx, out, NULL, 0);
560280297Sjkim        if (i < 0)
561280297Sjkim            return 0;
562280297Sjkim        else
563280297Sjkim            *outl = i;
564280297Sjkim        return 1;
565280297Sjkim    }
566238405Sjkim
567280297Sjkim    b = ctx->cipher->block_size;
568280297Sjkim    if (ctx->flags & EVP_CIPH_NO_PADDING) {
569280297Sjkim        if (ctx->buf_len) {
570280297Sjkim            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX,
571280297Sjkim                   EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
572280297Sjkim            return 0;
573280297Sjkim        }
574280297Sjkim        *outl = 0;
575280297Sjkim        return 1;
576280297Sjkim    }
577280297Sjkim    if (b > 1) {
578280297Sjkim        if (ctx->buf_len || !ctx->final_used) {
579280297Sjkim            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_WRONG_FINAL_BLOCK_LENGTH);
580280297Sjkim            return (0);
581280297Sjkim        }
582331638Sjkim        OPENSSL_assert(b <= sizeof(ctx->final));
583273144Sjkim
584280297Sjkim        /*
585280297Sjkim         * The following assumes that the ciphertext has been authenticated.
586280297Sjkim         * Otherwise it provides a padding oracle.
587280297Sjkim         */
588280297Sjkim        n = ctx->final[b - 1];
589280297Sjkim        if (n == 0 || n > (int)b) {
590280297Sjkim            EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
591280297Sjkim            return (0);
592280297Sjkim        }
593280297Sjkim        for (i = 0; i < n; i++) {
594280297Sjkim            if (ctx->final[--b] != n) {
595280297Sjkim                EVPerr(EVP_F_EVP_DECRYPTFINAL_EX, EVP_R_BAD_DECRYPT);
596280297Sjkim                return (0);
597280297Sjkim            }
598280297Sjkim        }
599280297Sjkim        n = ctx->cipher->block_size - n;
600280297Sjkim        for (i = 0; i < n; i++)
601280297Sjkim            out[i] = ctx->final[i];
602280297Sjkim        *outl = n;
603280297Sjkim    } else
604280297Sjkim        *outl = 0;
605280297Sjkim    return (1);
606280297Sjkim}
60755714Skris
608160814Ssimonvoid EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *ctx)
609280297Sjkim{
610280297Sjkim    if (ctx) {
611280297Sjkim        EVP_CIPHER_CTX_cleanup(ctx);
612280297Sjkim        OPENSSL_free(ctx);
613280297Sjkim    }
614280297Sjkim}
615160814Ssimon
616238405Sjkimint EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
617280297Sjkim{
618238405Sjkim#ifndef OPENSSL_FIPS
619280297Sjkim    if (c->cipher != NULL) {
620280297Sjkim        if (c->cipher->cleanup && !c->cipher->cleanup(c))
621280297Sjkim            return 0;
622280297Sjkim        /* Cleanse cipher context data */
623280297Sjkim        if (c->cipher_data)
624280297Sjkim            OPENSSL_cleanse(c->cipher_data, c->cipher->ctx_size);
625280297Sjkim    }
626280297Sjkim    if (c->cipher_data)
627280297Sjkim        OPENSSL_free(c->cipher_data);
628238405Sjkim#endif
629238405Sjkim#ifndef OPENSSL_NO_ENGINE
630280297Sjkim    if (c->engine)
631280297Sjkim        /*
632280297Sjkim         * The EVP_CIPHER we used belongs to an ENGINE, release the
633280297Sjkim         * functional reference we held for this reason.
634280297Sjkim         */
635280297Sjkim        ENGINE_finish(c->engine);
636238405Sjkim#endif
637238405Sjkim#ifdef OPENSSL_FIPS
638280297Sjkim    FIPS_cipher_ctx_cleanup(c);
639238405Sjkim#endif
640280297Sjkim    memset(c, 0, sizeof(EVP_CIPHER_CTX));
641280297Sjkim    return 1;
642280297Sjkim}
643238405Sjkim
64468651Skrisint EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
645280297Sjkim{
646280297Sjkim    if (c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH)
647280297Sjkim        return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
648280297Sjkim    if (c->key_len == keylen)
649280297Sjkim        return 1;
650280297Sjkim    if ((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH)) {
651280297Sjkim        c->key_len = keylen;
652280297Sjkim        return 1;
653280297Sjkim    }
654280297Sjkim    EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH, EVP_R_INVALID_KEY_LENGTH);
655280297Sjkim    return 0;
656280297Sjkim}
65768651Skris
658109998Smarkmint EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
659280297Sjkim{
660280297Sjkim    if (pad)
661280297Sjkim        ctx->flags &= ~EVP_CIPH_NO_PADDING;
662280297Sjkim    else
663280297Sjkim        ctx->flags |= EVP_CIPH_NO_PADDING;
664280297Sjkim    return 1;
665280297Sjkim}
666109998Smarkm
667238405Sjkimint EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
668238405Sjkim{
669280297Sjkim    int ret;
670280297Sjkim    if (!ctx->cipher) {
671280297Sjkim        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
672280297Sjkim        return 0;
673280297Sjkim    }
674238405Sjkim
675280297Sjkim    if (!ctx->cipher->ctrl) {
676280297Sjkim        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
677280297Sjkim        return 0;
678280297Sjkim    }
679238405Sjkim
680280297Sjkim    ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
681280297Sjkim    if (ret == -1) {
682280297Sjkim        EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL,
683280297Sjkim               EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
684280297Sjkim        return 0;
685280297Sjkim    }
686280297Sjkim    return ret;
687238405Sjkim}
688238405Sjkim
689160814Ssimonint EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key)
690280297Sjkim{
691280297Sjkim    if (ctx->cipher->flags & EVP_CIPH_RAND_KEY)
692280297Sjkim        return EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key);
693280297Sjkim    if (RAND_bytes(key, ctx->key_len) <= 0)
694280297Sjkim        return 0;
695280297Sjkim    return 1;
696280297Sjkim}
697160814Ssimon
698238405Sjkimint EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in)
699280297Sjkim{
700280297Sjkim    if ((in == NULL) || (in->cipher == NULL)) {
701280297Sjkim        EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INPUT_NOT_INITIALIZED);
702280297Sjkim        return 0;
703280297Sjkim    }
704194206Ssimon#ifndef OPENSSL_NO_ENGINE
705280297Sjkim    /* Make sure it's safe to copy a cipher context using an ENGINE */
706280297Sjkim    if (in->engine && !ENGINE_init(in->engine)) {
707280297Sjkim        EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_ENGINE_LIB);
708280297Sjkim        return 0;
709280297Sjkim    }
710238405Sjkim#endif
711194206Ssimon
712280297Sjkim    EVP_CIPHER_CTX_cleanup(out);
713331638Sjkim    memcpy(out, in, sizeof(*out));
714194206Ssimon
715280297Sjkim    if (in->cipher_data && in->cipher->ctx_size) {
716280297Sjkim        out->cipher_data = OPENSSL_malloc(in->cipher->ctx_size);
717280297Sjkim        if (!out->cipher_data) {
718325335Sjkim            out->cipher = NULL;
719280297Sjkim            EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, ERR_R_MALLOC_FAILURE);
720280297Sjkim            return 0;
721280297Sjkim        }
722280297Sjkim        memcpy(out->cipher_data, in->cipher_data, in->cipher->ctx_size);
723280297Sjkim    }
724238405Sjkim
725280297Sjkim    if (in->cipher->flags & EVP_CIPH_CUSTOM_COPY)
726325335Sjkim        if (!in->cipher->ctrl((EVP_CIPHER_CTX *)in, EVP_CTRL_COPY, 0, out)) {
727325335Sjkim            out->cipher = NULL;
728325335Sjkim            EVPerr(EVP_F_EVP_CIPHER_CTX_COPY, EVP_R_INITIALIZATION_ERROR);
729325335Sjkim            return 0;
730325335Sjkim        }
731280297Sjkim    return 1;
732280297Sjkim}
733