eb39539ca63a34570716328fa624cb83e2dd0a46
[openssl.git] / crypto / evp / evp_enc.c
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 "cryptlib.h"
61 #include <openssl/evp.h>
62 #include <openssl/err.h>
63 #include <openssl/engine.h>
64 #include "evp_locl.h"
65
66 #include <assert.h>
67
68 const char *EVP_version="EVP" OPENSSL_VERSION_PTEXT;
69
70 void EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *ctx)
71         {
72         memset(ctx,0,sizeof(EVP_CIPHER_CTX));
73         /* ctx->cipher=NULL; */
74         }
75
76
77 int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
78              const unsigned char *key, const unsigned char *iv, int enc)
79         {
80         EVP_CIPHER_CTX_init(ctx);
81         return EVP_CipherInit_ex(ctx,cipher,NULL,key,iv,enc);
82         }
83
84 int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl,
85              const unsigned char *key, const unsigned char *iv, int enc)
86         {
87         if(enc && (enc != -1)) enc = 1;
88         /* Whether it's nice or not, "Inits" can be used on "Final"'d contexts
89          * so this context may already have an ENGINE! Try to avoid releasing
90          * the previous handle, re-querying for an ENGINE, and having a
91          * reinitialisation, when it may all be unecessary. */
92         if (ctx->engine && ctx->cipher && (!cipher ||
93                         (cipher && (cipher->nid == ctx->cipher->nid))))
94                 goto skip_to_init;
95         if (cipher)
96                 {
97                 /* Ensure an ENGINE left lying around from last time is cleared
98                  * (the previous check attempted to avoid this if the same
99                  * ENGINE and EVP_CIPHER could be used). */
100                 if(ctx->engine)
101                         ENGINE_finish(ctx->engine);
102                 if(!impl)
103                         /* Ask if an ENGINE is reserved for this job */
104                         impl = ENGINE_get_cipher_engine(cipher->nid);
105                 if(impl)
106                         {
107                         /* There's an ENGINE for this job ... (apparently) */
108                         const EVP_CIPHER *c = ENGINE_get_cipher(impl, cipher->nid);
109                         if(!c)
110                                 {
111                                 /* One positive side-effect of US's export
112                                  * control history, is that we should at least
113                                  * be able to avoid using US mispellings of
114                                  * "initialisation"? */
115                                 EVPerr(EVP_F_EVP_CIPHERINIT, EVP_R_INITIALIZATION_ERROR);
116                                 return 0;
117                                 }
118                         /* We'll use the ENGINE's private cipher definition */
119                         cipher = c;
120                         /* Store the ENGINE functional reference so we know
121                          * 'cipher' came from an ENGINE and we need to release
122                          * it when done. */
123                         ctx->engine = impl;
124                         }
125                 else
126                         ctx->engine = NULL;
127                 ctx->cipher=cipher;
128                 ctx->cipher_data=OPENSSL_malloc(ctx->cipher->ctx_size);
129                 ctx->key_len = cipher->key_len;
130                 ctx->flags = 0;
131                 if(ctx->cipher->flags & EVP_CIPH_CTRL_INIT)
132                         {
133                         if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_INIT, 0, NULL))
134                                 {
135                                 EVPerr(EVP_F_EVP_CIPHERINIT, EVP_R_INITIALIZATION_ERROR);
136                                 return 0;
137                                 }
138                         }
139                 }
140         else if(!ctx->cipher)
141                 {
142                 EVPerr(EVP_F_EVP_CIPHERINIT, EVP_R_NO_CIPHER_SET);
143                 return 0;
144                 }
145 skip_to_init:
146         /* we assume block size is a power of 2 in *cryptUpdate */
147         assert(ctx->cipher->block_size == 1
148                || ctx->cipher->block_size == 8
149                || ctx->cipher->block_size == 16);
150
151         if(!(EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_CUSTOM_IV)) {
152                 switch(EVP_CIPHER_CTX_mode(ctx)) {
153
154                         case EVP_CIPH_STREAM_CIPHER:
155                         case EVP_CIPH_ECB_MODE:
156                         break;
157
158                         case EVP_CIPH_CFB_MODE:
159                         case EVP_CIPH_OFB_MODE:
160
161                         ctx->num = 0;
162
163                         case EVP_CIPH_CBC_MODE:
164
165                         if(iv) memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
166                         memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
167                         break;
168
169                         default:
170                         return 0;
171                         break;
172                 }
173         }
174
175         if(key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
176                 if(!ctx->cipher->init(ctx,key,iv,enc)) return 0;
177         }
178         if(enc != -1) ctx->encrypt=enc;
179         ctx->buf_len=0;
180         ctx->final_used=0;
181         ctx->block_mask=ctx->cipher->block_size-1;
182         return 1;
183         }
184
185 int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
186              const unsigned char *in, int inl)
187         {
188         if (ctx->encrypt)
189                 return EVP_EncryptUpdate(ctx,out,outl,in,inl);
190         else    return EVP_DecryptUpdate(ctx,out,outl,in,inl);
191         }
192
193 int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
194         {
195         if (ctx->encrypt)
196                 return EVP_EncryptFinal_ex(ctx,out,outl);
197         else    return EVP_DecryptFinal_ex(ctx,out,outl);
198         }
199
200 int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
201         {
202         if (ctx->encrypt)
203                 return EVP_EncryptFinal(ctx,out,outl);
204         else    return EVP_DecryptFinal(ctx,out,outl);
205         }
206
207 int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
208              const unsigned char *key, const unsigned char *iv)
209         {
210         return EVP_CipherInit(ctx, cipher, key, iv, 1);
211         }
212
213 int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx,const EVP_CIPHER *cipher, ENGINE *impl,
214                 const unsigned char *key, const unsigned char *iv)
215         {
216         return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 1);
217         }
218
219 int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
220              const unsigned char *key, const unsigned char *iv)
221         {
222         return EVP_CipherInit_ex(ctx, cipher, NULL, key, iv, 0);
223         }
224
225 int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, ENGINE *impl,
226              const unsigned char *key, const unsigned char *iv)
227         {
228         return EVP_CipherInit_ex(ctx, cipher, impl, key, iv, 0);
229         }
230
231 int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
232              const unsigned char *in, int inl)
233         {
234         int i,j,bl;
235
236         if(ctx->buf_len == 0 && (inl&(ctx->block_mask)) == 0)
237                 {
238                 if(ctx->cipher->do_cipher(ctx,out,in,inl))
239                         {
240                         *outl=inl;
241                         return 1;
242                         }
243                 else
244                         {
245                         *outl=0;
246                         return 0;
247                         }
248                 }
249         i=ctx->buf_len;
250         bl=ctx->cipher->block_size;
251         if (i != 0)
252                 {
253                 if (i+inl < bl)
254                         {
255                         memcpy(&(ctx->buf[i]),in,inl);
256                         ctx->buf_len+=inl;
257                         *outl=0;
258                         return 1;
259                         }
260                 else
261                         {
262                         j=bl-i;
263                         memcpy(&(ctx->buf[i]),in,j);
264                         if(!ctx->cipher->do_cipher(ctx,out,ctx->buf,bl)) return 0;
265                         inl-=j;
266                         in+=j;
267                         out+=bl;
268                         *outl=bl;
269                         }
270                 }
271         else
272                 *outl = 0;
273         i=inl&(bl-1);
274         inl-=i;
275         if (inl > 0)
276                 {
277                 if(!ctx->cipher->do_cipher(ctx,out,in,inl)) return 0;
278                 *outl+=inl;
279                 }
280
281         if (i != 0)
282                 memcpy(ctx->buf,&(in[inl]),i);
283         ctx->buf_len=i;
284         return 1;
285         }
286
287 int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
288         {
289         int ret;
290         ret = EVP_EncryptFinal_ex(ctx, out, outl);
291         EVP_CIPHER_CTX_cleanup(ctx);
292         return ret;
293         }
294
295 int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
296         {
297         int i,n,b,bl,ret;
298
299         b=ctx->cipher->block_size;
300         if (b == 1)
301                 {
302                 EVP_CIPHER_CTX_cleanup(ctx);
303                 *outl=0;
304                 return 1;
305                 }
306         bl=ctx->buf_len;
307         if (ctx->flags & EVP_CIPH_NO_PADDING)
308                 {
309                 EVP_CIPHER_CTX_cleanup(ctx);
310                 if(bl)
311                         {
312                         EVPerr(EVP_F_EVP_ENCRYPTFINAL,EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
313                         return 0;
314                         }
315                 *outl = 0;
316                 return 1;
317                 }
318
319         n=b-bl;
320         for (i=bl; i<b; i++)
321                 ctx->buf[i]=n;
322         ret=ctx->cipher->do_cipher(ctx,out,ctx->buf,b);
323
324         EVP_CIPHER_CTX_cleanup(ctx);
325
326         if(ret)
327                 *outl=b;
328
329         return ret;
330         }
331
332 int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl,
333              const unsigned char *in, int inl)
334         {
335         int b, fix_len;
336
337         if (inl == 0)
338                 {
339                 *outl=0;
340                 return 1;
341                 }
342
343         if (ctx->flags & EVP_CIPH_NO_PADDING)
344                 return EVP_EncryptUpdate(ctx, out, outl, in, inl);
345
346         b=ctx->cipher->block_size;
347
348         if(ctx->final_used)
349                 {
350                 memcpy(out,ctx->final,b);
351                 out+=b;
352                 fix_len = 1;
353                 }
354         else
355                 fix_len = 0;
356
357
358         if(!EVP_EncryptUpdate(ctx,out,outl,in,inl))
359                 return 0;
360
361         /* if we have 'decrypted' a multiple of block size, make sure
362          * we have a copy of this last block */
363         if (b > 1 && !ctx->buf_len)
364                 {
365                 *outl-=b;
366                 ctx->final_used=1;
367                 memcpy(ctx->final,&out[*outl],b);
368                 }
369         else
370                 ctx->final_used = 0;
371
372         if (fix_len)
373                 *outl += b;
374                 
375         return 1;
376         }
377
378 int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
379         {
380         int ret;
381         ret = EVP_DecryptFinal_ex(ctx, out, outl);
382         EVP_CIPHER_CTX_cleanup(ctx);
383         return ret;
384         }
385
386 int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl)
387         {
388         int i,b;
389         int n;
390
391         *outl=0;
392         b=ctx->cipher->block_size;
393         if (ctx->flags & EVP_CIPH_NO_PADDING)
394                 {
395                 EVP_CIPHER_CTX_cleanup(ctx);
396                 if(ctx->buf_len)
397                         {
398                         EVPerr(EVP_F_EVP_DECRYPTFINAL,EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH);
399                         return 0;
400                         }
401                 *outl = 0;
402                 return 1;
403                 }
404         if (b > 1)
405                 {
406                 if (ctx->buf_len || !ctx->final_used)
407                         {
408                         EVP_CIPHER_CTX_cleanup(ctx);
409                         EVPerr(EVP_F_EVP_DECRYPTFINAL,EVP_R_WRONG_FINAL_BLOCK_LENGTH);
410                         return(0);
411                         }
412                 n=ctx->final[b-1];
413                 if (n > b)
414                         {
415                         EVP_CIPHER_CTX_cleanup(ctx);
416                         EVPerr(EVP_F_EVP_DECRYPTFINAL,EVP_R_BAD_DECRYPT);
417                         return(0);
418                         }
419                 for (i=0; i<n; i++)
420                         {
421                         if (ctx->final[--b] != n)
422                                 {
423                                 EVP_CIPHER_CTX_cleanup(ctx);
424                                 EVPerr(EVP_F_EVP_DECRYPTFINAL,EVP_R_BAD_DECRYPT);
425                                 return(0);
426                                 }
427                         }
428                 n=ctx->cipher->block_size-n;
429                 for (i=0; i<n; i++)
430                         out[i]=ctx->final[i];
431                 *outl=n;
432                 }
433         else
434                 *outl=0;
435         EVP_CIPHER_CTX_cleanup(ctx);
436         return(1);
437         }
438
439 int EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
440         {
441         if ((c->cipher != NULL) && (c->cipher->cleanup != NULL))
442                 {
443                 if(!c->cipher->cleanup(c)) return 0;
444                 }
445         OPENSSL_free(c->cipher_data);
446         if (c->engine)
447                 /* The EVP_CIPHER we used belongs to an ENGINE, release the
448                  * functional reference we held for this reason. */
449                 ENGINE_finish(c->engine);
450         memset(c,0,sizeof(EVP_CIPHER_CTX));
451         return 1;
452         }
453
454 int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int keylen)
455         {
456         if(c->cipher->flags & EVP_CIPH_CUSTOM_KEY_LENGTH) 
457                 return EVP_CIPHER_CTX_ctrl(c, EVP_CTRL_SET_KEY_LENGTH, keylen, NULL);
458         if(c->key_len == keylen) return 1;
459         if((keylen > 0) && (c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH))
460                 {
461                 c->key_len = keylen;
462                 return 1;
463                 }
464         EVPerr(EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH,EVP_R_INVALID_KEY_LENGTH);
465         return 0;
466         }
467
468 int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *ctx, int pad)
469         {
470         if (pad) ctx->flags &= ~EVP_CIPH_NO_PADDING;
471         else ctx->flags |= EVP_CIPH_NO_PADDING;
472         return 1;
473         }
474
475 int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
476 {
477         int ret;
478         if(!ctx->cipher) {
479                 EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_NO_CIPHER_SET);
480                 return 0;
481         }
482
483         if(!ctx->cipher->ctrl) {
484                 EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_NOT_IMPLEMENTED);
485                 return 0;
486         }
487
488         ret = ctx->cipher->ctrl(ctx, type, arg, ptr);
489         if(ret == -1) {
490                 EVPerr(EVP_F_EVP_CIPHER_CTX_CTRL, EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED);
491                 return 0;
492         }
493         return ret;
494 }