1/*
2 * Copyright (c) 2011-12 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24/*
25 * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
26 * (Royal Institute of Technology, Stockholm, Sweden).
27 * All rights reserved.
28 *
29 * Redistribution and use in source and binary forms, with or without
30 * modification, are permitted provided that the following conditions
31 * are met:
32 *
33 * 1. Redistributions of source code must retain the above copyright
34 *    notice, this list of conditions and the following disclaimer.
35 *
36 * 2. Redistributions in binary form must reproduce the above copyright
37 *    notice, this list of conditions and the following disclaimer in the
38 *    documentation and/or other materials provided with the distribution.
39 *
40 * 3. Neither the name of the Institute nor the names of its contributors
41 *    may be used to endorse or promote products derived from this software
42 *    without specific prior written permission.
43 *
44 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
45 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
47 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
48 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
49 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
50 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
52 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
53 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * SUCH DAMAGE.
55 */
56
57#include "ossl-config.h"
58
59#include <sys/types.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <assert.h>
64
65#include "ossl-evp.h"
66#include "ossl-objects.h"
67#include "ossl-evp-cc.h"
68#include "ossl-ui.h"
69
70#ifdef HAVE_COMMONCRYPTO_COMMONRANDOMSPI_H
71#include <CommonCrypto/CommonRandomSPI.h>
72#endif
73
74#include "krb5-types.h"
75
76#ifndef OSSL_DEF_PROVIDER
77#define OSSL_DEF_PROVIDER    cc
78#endif
79
80#define OSSL_CONCAT4(x, y, z, aa)	x ## y ## z ## aa
81
82
83#define EVP_DEF_OP(_prov, _op)		OSSL_CONCAT4(EVP_, _prov, _, _op) ()
84
85/**
86 * @page page_evp EVP - generic crypto interface
87 *
88 * @section evp_cipher EVP Cipher
89 *
90 * The use of EVP_CipherInit_ex() and EVP_Cipher() is pretty easy to
91 * understand forward, then EVP_CipherUpdate() and
92 * EVP_CipherFinal_ex() really needs an example to explain @ref
93 * example_evp_cipher.c .
94 *
95 * @example example_evp_cipher.c
96 *
97 * This is an example how to use EVP_CipherInit_ex(),
98 * EVP_CipherUpdate() and EVP_CipherFinal_ex().
99 */
100
101
102/**
103 * Return the output size of the message digest function.
104 *
105 * @param md the evp message
106 *
107 * @return size output size of the message digest function.
108 */
109size_t
110EVP_MD_size(const EVP_MD *md)
111{
112	return (md->hash_size);
113}
114
115
116/**
117 * Return the blocksize of the message digest function.
118 *
119 * @param md the evp message
120 *
121 * @return size size of the message digest block size
122 */
123size_t
124EVP_MD_block_size(const EVP_MD *md)
125{
126	return (md->block_size);
127}
128
129
130/**
131 * Allocate a messsage digest context object. Free with
132 * EVP_MD_CTX_destroy().
133 *
134 * @return a newly allocated message digest context object.
135 */
136EVP_MD_CTX *
137EVP_MD_CTX_create(void)
138{
139	return (calloc(1, sizeof(EVP_MD_CTX)));
140}
141
142
143/**
144 * Initiate a messsage digest context object. Deallocate with
145 * EVP_MD_CTX_cleanup(). Please use EVP_MD_CTX_create() instead.
146 *
147 * @param ctx variable to initiate.
148 */
149void
150EVP_MD_CTX_init(EVP_MD_CTX *ctx)
151{
152	memset(ctx, 0, sizeof(*ctx));
153}
154
155
156/**
157 * Free a messsage digest context object.
158 *
159 * @param ctx context to free.
160 */
161void
162EVP_MD_CTX_destroy(EVP_MD_CTX *ctx)
163{
164	EVP_MD_CTX_cleanup(ctx);
165	free(ctx);
166}
167
168
169/**
170 * Free the resources used by the EVP_MD context.
171 *
172 * @param ctx the context to free the resources from.
173 *
174 * @return 1 on success.
175 */
176int
177EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
178{
179	if (ctx->md && ctx->md->cleanup) {
180		(ctx->md->cleanup)(ctx);
181	} else if (ctx->md) {
182		memset(ctx->ptr, 0, ctx->md->ctx_size);
183	}
184	ctx->md = NULL;
185	ctx->engine = NULL;
186	free(ctx->ptr);
187	memset(ctx, 0, sizeof(*ctx));
188	return (1);
189}
190
191
192/**
193 * Get the EVP_MD use for a specified context.
194 *
195 * @param ctx the EVP_MD context to get the EVP_MD for.
196 *
197 * @return the EVP_MD used for the context.
198 */
199const EVP_MD *
200EVP_MD_CTX_md(EVP_MD_CTX *ctx)
201{
202	return (ctx->md);
203}
204
205
206/**
207 * Return the output size of the message digest function.
208 *
209 * @param ctx the evp message digest context
210 *
211 * @return size output size of the message digest function.
212 */
213size_t
214EVP_MD_CTX_size(EVP_MD_CTX *ctx)
215{
216	return (EVP_MD_size(ctx->md));
217}
218
219
220/**
221 * Return the blocksize of the message digest function.
222 *
223 * @param ctx the evp message digest context
224 *
225 * @return size size of the message digest block size
226 */
227size_t
228EVP_MD_CTX_block_size(EVP_MD_CTX *ctx)
229{
230	return (EVP_MD_block_size(ctx->md));
231}
232
233
234int
235EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in)
236{
237	if ((NULL == in) || (NULL == in->md)) {
238		/* EVPerr */
239		return (0);
240	}
241
242	EVP_MD_CTX_cleanup(out);
243	memcpy(out, in, sizeof(*out));
244
245	if (out->md->ctx_size) {
246		out->ptr = malloc(in->md->ctx_size);
247		if (!out->ptr) {
248			/* EVPerr */
249			return (0);
250		}
251		memcpy(out->ptr, in->ptr, out->md->ctx_size);
252	}
253
254	if (out->engine) {
255		ENGINE_up_ref(out->engine);
256	}
257
258	/*
259	 * if (out->md->copy)
260	 *      return out->md->copy(out, in);
261	 */
262
263	return (1);
264}
265
266
267/**
268 * Init a EVP_MD_CTX for use a specific message digest and engine.
269 *
270 * @param ctx the message digest context to init.
271 * @param md the message digest to use.
272 * @param engine the engine to use, NULL to use the default engine.
273 *
274 * @return 1 on success.
275 */
276int
277EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *md, ENGINE *engine)
278{
279	if (NULL == ctx)
280		return (0);
281	if ((ctx->md != md) || (ctx->engine != engine)) {
282		EVP_MD_CTX_cleanup(ctx);
283		ctx->md = md;
284		ctx->engine = engine;
285
286		ctx->ptr = calloc(1, md->ctx_size);
287		if (ctx->ptr == NULL) {
288			return (0);
289		}
290	}
291	(ctx->md->init)(ctx->ptr);
292	return (1);
293}
294
295
296int
297EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *md)
298{
299	if (ctx) {
300		EVP_MD_CTX_init(ctx);
301	}
302	return (EVP_DigestInit_ex(ctx, md, NULL));
303}
304
305
306/**
307 * Update the digest with some data.
308 *
309 * @param ctx the context to update
310 * @param data the data to update the context with
311 * @param size length of data
312 *
313 * @return 1 on success.
314 */
315int
316EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *data, size_t size)
317{
318	(ctx->md->update)(ctx->ptr, data, size);
319	return (1);
320}
321
322
323/**
324 * Complete the message digest.
325 *
326 * @param ctx the context to complete.
327 * @param hash the output of the message digest function. At least
328 * EVP_MD_size().
329 * @param size the output size of hash.
330 *
331 * @return 1 on success.
332 */
333int
334EVP_DigestFinal_ex(EVP_MD_CTX *ctx, void *hash, unsigned int *size)
335{
336	(ctx->md->final)(hash, ctx->ptr);
337	if (size) {
338		*size = ctx->md->hash_size;
339	}
340	return (1);
341}
342
343
344int
345EVP_DigestFinal(EVP_MD_CTX *ctx, void *hash, unsigned int *size)
346{
347	int rv = EVP_DigestFinal_ex(ctx, hash, size);
348
349	EVP_MD_CTX_cleanup(ctx);
350	return (rv);
351}
352
353
354/**
355 * Do the whole EVP_MD_CTX_create(), EVP_DigestInit_ex(),
356 * EVP_DigestUpdate(), EVP_DigestFinal_ex(), EVP_MD_CTX_destroy()
357 * dance in one call.
358 *
359 * @param data the data to update the context with
360 * @param dsize length of data
361 * @param hash output data of at least EVP_MD_size() length.
362 * @param hsize output length of hash.
363 * @param md message digest to use
364 * @param engine engine to use, NULL for default engine.
365 *
366 * @return 1 on success.
367 */
368int
369EVP_Digest(const void *data, size_t dsize, void *hash, unsigned int *hsize,
370    const EVP_MD *md, ENGINE *engine)
371{
372	EVP_MD_CTX ctx;
373	int ret;
374
375	EVP_MD_CTX_init(&ctx);
376	ret = EVP_DigestInit_ex(&ctx, md, engine) &&
377	    EVP_DigestUpdate(&ctx, data, dsize) &&
378	    EVP_DigestFinal_ex(&ctx, hash, hsize);
379	EVP_MD_CTX_cleanup(&ctx);
380
381	return (ret);
382}
383
384
385/**
386 * The message digest rmd128
387 *
388 * @return the message digest type.
389 */
390const EVP_MD *
391EVP_rmd128(void)
392{
393	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rmd128));
394}
395
396
397const EVP_MD *
398EVP_ripemd128(void)
399{
400	return (EVP_rmd128());
401}
402
403
404/**
405 * The message digest rmd160
406 *
407 * @return the message digest type.
408 */
409const EVP_MD *
410EVP_rmd160(void)
411{
412	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rmd160));
413}
414
415
416const EVP_MD *
417EVP_ripemd160(void)
418{
419	return (EVP_rmd160());
420}
421
422
423/**
424 * The message digest rmd256
425 *
426 * @return the message digest type.
427 */
428const EVP_MD *
429EVP_rmd256(void)
430{
431	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rmd256));
432}
433
434
435const EVP_MD *
436EVP_ripemd256(void)
437{
438	return (EVP_rmd256());
439}
440
441
442/**
443 * The message digest rmd320
444 *
445 * @return the message digest type.
446 */
447const EVP_MD *
448EVP_rmd320(void)
449{
450	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rmd320));
451}
452
453
454const EVP_MD *
455EVP_ripemd320(void)
456{
457	return (EVP_rmd320());
458}
459
460
461/**
462 * The message digest sha224
463 *
464 * @return the message digest type.
465 */
466const EVP_MD *
467EVP_sha224(void)
468{
469	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, sha224));
470}
471
472
473/**
474 * The message digest SHA256
475 *
476 * @return the message digest type.
477 */
478const EVP_MD *
479EVP_sha256(void)
480{
481	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, sha256));
482}
483
484
485/**
486 * The message digest SHA384
487 *
488 * @return the message digest type.
489 */
490const EVP_MD *
491EVP_sha384(void)
492{
493	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, sha384));
494}
495
496
497/**
498 * The message digest SHA512
499 *
500 * @return the message digest type.
501 */
502const EVP_MD *
503EVP_sha512(void)
504{
505	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, sha512));
506}
507
508
509/**
510 * The message digest SHA1
511 *
512 * @return the message digest type.
513 */
514const EVP_MD *
515EVP_sha1(void)
516{
517	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, sha1));
518}
519
520
521/**
522 * The message digest SHA1
523 *
524 * @return the message digest type.
525 */
526const EVP_MD *
527EVP_sha(void)
528
529{
530	return (EVP_sha1());
531}
532
533
534/**
535 * The message digest MD5
536 *
537 * @return the message digest type.
538 */
539const EVP_MD *
540EVP_md5(void)
541{
542	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, md5));
543}
544
545
546/**
547 * The message digest MD4
548 *
549 * @return the message digest type.
550 */
551const EVP_MD *
552EVP_md4(void)
553{
554	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, md4));
555}
556
557
558/**
559 * The message digest MD2
560 *
561 * @return the message digest type.
562 */
563const EVP_MD *
564EVP_md2(void)
565{
566	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, md2));
567}
568
569
570/*
571 * Null MD
572 */
573static void
574null_Init(void *m)
575{
576}
577
578
579static void
580null_Update(void *m, const void *data, size_t size)
581{
582}
583
584
585static void
586null_Final(void *res, void *m)
587{
588}
589
590
591/**
592 * The null message digest
593 *
594 * @return the message digest type.
595 *
596 * @ingroup hcrypto_evp
597 */
598const EVP_MD *
599EVP_md_null(void)
600{
601	static const struct ossl_evp_md null =
602	{
603		.hash_size	=			    0,
604		.block_size	=			    0,
605		.ctx_size	=			    0,
606		.init		= (ossl_evp_md_init)null_Init,
607		.update		= (ossl_evp_md_update)null_Update,
608		.final		= (ossl_evp_md_final)null_Final,
609		.cleanup	= NULL
610	};
611
612	return (&null);
613}
614
615
616const EVP_MD *
617EVP_get_digestbynid(int nid)
618{
619	switch (nid) {
620	case NID_md2:
621		return (EVP_md2());
622
623	case NID_md4:
624		return (EVP_md4());
625
626	case NID_md5:
627		return (EVP_md5());
628
629	case NID_sha1:
630		return (EVP_sha1());
631
632	case NID_sha256:
633		return (EVP_sha256());
634
635	case NID_sha384:
636		return (EVP_sha384());
637
638	case NID_sha512:
639		return (EVP_sha512());
640
641	default:
642		return (NULL);
643	}
644}
645
646
647int
648EVP_CIPHER_nid(const EVP_CIPHER *c)
649{
650	return (c->nid);
651}
652
653
654/**
655 * Return the block size of the cipher.
656 *
657 * @param c cipher to get the block size from.
658 *
659 * @return the block size of the cipher.
660 */
661size_t
662EVP_CIPHER_block_size(const EVP_CIPHER *c)
663{
664	return (c->block_size);
665}
666
667
668/**
669 * Return the key size of the cipher.
670 *
671 * @param c cipher to get the key size from.
672 *
673 * @return the key size of the cipher.
674 */
675size_t
676EVP_CIPHER_key_length(const EVP_CIPHER *c)
677{
678	return (c->key_len);
679}
680
681
682/**
683 * Return the IV size of the cipher.
684 *
685 * @param c cipher to get the IV size from.
686 *
687 * @return the IV size of the cipher.
688 */
689size_t
690EVP_CIPHER_iv_length(const EVP_CIPHER *c)
691{
692	return (c->iv_len);
693}
694
695
696/**
697 * Initiate a EVP_CIPHER_CTX context. Clean up with
698 * EVP_CIPHER_CTX_cleanup().
699 *
700 * @param c the cipher initiate.
701 */
702void
703EVP_CIPHER_CTX_init(EVP_CIPHER_CTX *c)
704{
705	memset(c, 0, sizeof(*c));
706}
707
708
709/**
710 * Clean up the EVP_CIPHER_CTX context.
711 *
712 * @param c the cipher to clean up.
713 *
714 * @return 1 on success.
715 */
716int
717EVP_CIPHER_CTX_cleanup(EVP_CIPHER_CTX *c)
718{
719	if (c->cipher) {
720		if (c->cipher->cleanup) {
721			c->cipher->cleanup(c);
722		}
723
724		if (c->cipher_data) {
725			memset(c->cipher_data, 0, c->cipher->ctx_size);
726			free(c->cipher_data);
727			c->cipher_data = NULL;
728		}
729		EVP_CIPHER_CTX_init(c);
730	}
731	return (1);
732}
733
734
735/**
736 * If the cipher type supports it, change the key length
737 *
738 * @param c the cipher context to change the key length for
739 * @param length new key length
740 *
741 * @return 1 on success.
742 */
743int
744EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *c, int length)
745{
746	if ((c->cipher->flags & EVP_CIPH_VARIABLE_LENGTH) && (length > 0)) {
747		c->key_len = length;
748		return (1);
749	}
750	return (0);
751}
752
753
754#if 0
755int
756EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad)
757{
758	return (0);
759}
760
761
762#endif
763
764/**
765 * Return the EVP_CIPHER for a EVP_CIPHER_CTX context.
766 *
767 * @param ctx the context to get the cipher type from.
768 *
769 * @return the EVP_CIPHER pointer.
770 */
771const EVP_CIPHER *
772EVP_CIPHER_CTX_cipher(EVP_CIPHER_CTX *ctx)
773{
774	return (ctx->cipher);
775}
776
777
778/**
779 * Return the block size of the cipher context.
780 *
781 * @param ctx cipher context to get the block size from.
782 *
783 * @return the block size of the cipher context.
784 */
785size_t
786EVP_CIPHER_CTX_block_size(const EVP_CIPHER_CTX *ctx)
787{
788	return (EVP_CIPHER_block_size(ctx->cipher));
789}
790
791
792/**
793 * Return the key size of the cipher context.
794 *
795 * @param ctx cipher context to get the key size from.
796 *
797 * @return the key size of the cipher context.
798 */
799size_t
800EVP_CIPHER_CTX_key_length(const EVP_CIPHER_CTX *ctx)
801{
802	/* return EVP_CIPHER_key_length(ctx->cipher); */
803	return (ctx->key_len);
804}
805
806
807/**
808 * Return the IV size of the cipher context.
809 *
810 * @param ctx cipher context to get the IV size from.
811 *
812 * @return the IV size of the cipher context.
813 */
814size_t
815EVP_CIPHER_CTX_iv_length(const EVP_CIPHER_CTX *ctx)
816{
817	return (EVP_CIPHER_iv_length(ctx->cipher));
818}
819
820
821/**
822 * Get the flags for an EVP_CIPHER_CTX context.
823 *
824 * @param ctx the EVP_CIPHER_CTX to get the flags from
825 *
826 * @return the flags for an EVP_CIPHER_CTX.
827 */
828unsigned long
829EVP_CIPHER_CTX_flags(const EVP_CIPHER_CTX *ctx)
830{
831	return (ctx->cipher->flags);
832}
833
834
835/**
836 * Get the mode for an EVP_CIPHER_CTX context.
837 *
838 * @param ctx the EVP_CIPHER_CTX to get the mode from
839 *
840 * @return the mode for an EVP_CIPHER_CTX.
841 */
842int
843EVP_CIPHER_CTX_mode(const EVP_CIPHER_CTX *ctx)
844{
845	return (EVP_CIPHER_CTX_flags(ctx) & EVP_CIPH_MODE);
846}
847
848
849/**
850 * Get the app data for an EVP_CIPHER_CTX context.
851 *
852 * @param ctx the EVP_CIPHER_CTX to get the app data from
853 *
854 * @return the app data for an EVP_CIPHER_CTX.
855 */
856void *
857EVP_CIPHER_CTX_get_app_data(EVP_CIPHER_CTX *ctx)
858{
859	return (ctx->app_data);
860}
861
862
863/**
864 * Set the app data for an EVP_CIPHER_CTX context.
865 *
866 * @param ctx the EVP_CIPHER_CTX to set the app data for
867 * @param data the app data to set for an EVP_CIPHER_CTX.
868 */
869void
870EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data)
871{
872	ctx->app_data = data;
873}
874
875
876/**
877 * Initiate the EVP_CIPHER_CTX context to encrypt or decrypt data.
878 * Clean up with EVP_CIPHER_CTX_cleanup().
879 *
880 * @param ctx context to initiate
881 * @param c cipher to use.
882 * @param engine crypto engine to use, NULL to select default.
883 * @param key the crypto key to use, NULL will use the previous value.
884 * @param iv the IV to use, NULL will use the previous value.
885 * @param encp non zero will encrypt, -1 use the previous value.
886 *
887 * @return 1 on success.
888 */
889int
890EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *c, ENGINE *engine,
891    const void *key, const void *iv, int encp)
892{
893	ctx->buf_len = 0;
894
895	if (encp == -1) {
896		encp = ctx->encrypt;
897	} else{
898		ctx->encrypt = (encp ? 1 : 0);
899	}
900
901	if (c && (c != ctx->cipher)) {
902		EVP_CIPHER_CTX_cleanup(ctx);
903		ctx->cipher = c;
904		ctx->key_len = c->key_len;
905
906		ctx->cipher_data = calloc(1, c->ctx_size);
907		if ((ctx->cipher_data == NULL) && (c->ctx_size != 0)) {
908			return (0);
909		}
910
911		/* assume block size is a multiple of 2 */
912		ctx->block_mask = EVP_CIPHER_block_size(c) - 1;
913	} else if (ctx->cipher == NULL) {
914		/* reuse of cipher, but not any cipher ever set! */
915		return (0);
916	}
917
918	switch (EVP_CIPHER_CTX_mode(ctx)) {
919	case EVP_CIPH_CBC_MODE:
920
921		assert(EVP_CIPHER_CTX_iv_length(ctx) <= sizeof(ctx->iv));
922
923		if (iv) {
924			memcpy(ctx->oiv, iv, EVP_CIPHER_CTX_iv_length(ctx));
925		}
926		memcpy(ctx->iv, ctx->oiv, EVP_CIPHER_CTX_iv_length(ctx));
927		break;
928
929	case EVP_CIPH_ECB_MODE:
930	case EVP_CIPH_STREAM_CIPHER:
931	case EVP_CIPH_CFB8_MODE:
932		if (iv) {
933			memcpy(ctx->iv, iv, EVP_CIPHER_CTX_iv_length(ctx));
934		}
935		break;
936
937	default:
938		return (0);
939	}
940
941	if (key || (ctx->cipher->flags & EVP_CIPH_ALWAYS_CALL_INIT)) {
942		ctx->cipher->init(ctx, key, iv, encp);
943	}
944
945	return (1);
946}
947
948
949int
950EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *c, const void *key,
951    const void *iv, int encp)
952{
953	return (EVP_CipherInit_ex(ctx, c, NULL, key, iv, encp));
954}
955
956
957/**
958 * Encipher/decipher partial data
959 *
960 * @param ctx the cipher context.
961 * @param out output data from the operation.
962 * @param outlen output length
963 * @param in input data to the operation.
964 * @param inlen length of data.
965 *
966 * The output buffer length should at least be EVP_CIPHER_block_size()
967 * byte longer then the input length.
968 *
969 * See @ref evp_cipher for an example how to use this function.
970 *
971 * @return 1 on success.
972 */
973int
974EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, void *out, int *outlen,
975    void *in, size_t inlen)
976{
977	int ret, left, blocksize;
978
979	*outlen = 0;
980
981	/**
982	 * If there in no spare bytes in the left from last Update and the
983	 * input length is on the block boundery, the EVP_CipherUpdate()
984	 * function can take a shortcut (and preformance gain) and
985	 * directly encrypt the data, otherwise we hav to fix it up and
986	 * store extra it the EVP_CIPHER_CTX.
987	 */
988	if ((ctx->buf_len == 0) && ((inlen & ctx->block_mask) == 0)) {
989		ret = (*ctx->cipher->do_cipher)(ctx, out, in, inlen);
990		if (ret == 1) {
991			*outlen = inlen;
992		} else{
993			*outlen = 0;
994		}
995		return (ret);
996	}
997
998
999	blocksize = EVP_CIPHER_CTX_block_size(ctx);
1000	left = blocksize - ctx->buf_len;
1001	assert(left > 0);
1002
1003	if (ctx->buf_len) {
1004		/* if total buffer is smaller then input, store locally */
1005		if (inlen < left) {
1006			memcpy(ctx->buf + ctx->buf_len, in, inlen);
1007			ctx->buf_len += inlen;
1008			return (1);
1009		}
1010
1011		/* fill in local buffer and encrypt */
1012		memcpy(ctx->buf + ctx->buf_len, in, left);
1013		ret = (*ctx->cipher->do_cipher)(ctx, out, ctx->buf, blocksize);
1014		memset(ctx->buf, 0, blocksize);
1015		if (ret != 1) {
1016			return (ret);
1017		}
1018
1019		*outlen += blocksize;
1020		inlen -= left;
1021		in = ((unsigned char *)in) + left;
1022		out = ((unsigned char *)out) + blocksize;
1023		ctx->buf_len = 0;
1024	}
1025
1026	if (inlen) {
1027		ctx->buf_len = (inlen & ctx->block_mask);
1028		inlen &= ~ctx->block_mask;
1029
1030		ret = (*ctx->cipher->do_cipher)(ctx, out, in, inlen);
1031		if (ret != 1) {
1032			return (ret);
1033		}
1034
1035		*outlen += inlen;
1036
1037		in = ((unsigned char *)in) + inlen;
1038		memcpy(ctx->buf, in, ctx->buf_len);
1039	}
1040
1041	return (1);
1042}
1043
1044
1045/**
1046 * Encipher/decipher final data
1047 *
1048 * @param ctx the cipher context.
1049 * @param out output data from the operation.
1050 * @param outlen output length
1051 *
1052 * The input length needs to be at least EVP_CIPHER_block_size() bytes
1053 * long.
1054 *
1055 * See @ref evp_cipher for an example how to use this function.
1056 *
1057 * @return 1 on success.
1058 */
1059int
1060EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, void *out, int *outlen)
1061{
1062	*outlen = 0;
1063
1064	// Love say to always output a block even if we have ctx->buf_len is 0... that is a whole block of pad bytes.
1065	int ret, left, blocksize;
1066
1067	blocksize = EVP_CIPHER_CTX_block_size(ctx);
1068
1069	if (blocksize == 1) {
1070		*outlen = 0;
1071		return (1);
1072	}
1073
1074	left = blocksize - ctx->buf_len;
1075	assert(left > 0);
1076
1077	/* zero fill local buffer */
1078	// <rdar://problem/13110768> ssh key created on cab can't be used on zin
1079	// use PKCS11 padding with pad value of number of pad byes.
1080	memset(ctx->buf + ctx->buf_len, left, left);
1081
1082	ret = (*ctx->cipher->do_cipher)(ctx, out, ctx->buf, blocksize);
1083	memset(ctx->buf, 0, blocksize);
1084
1085	if (ret != 1) {
1086		return (ret);
1087	}
1088
1089	*outlen += blocksize;
1090
1091	return (1);
1092}
1093
1094
1095/**
1096 * Encipher/decipher data
1097 *
1098 * @param ctx the cipher context.
1099 * @param out out data from the operation.
1100 * @param in in data to the operation.
1101 * @param size length of data.
1102 */
1103int
1104EVP_Cipher(EVP_CIPHER_CTX *ctx, void *out, const void *in, size_t size)
1105{
1106	return (ctx->cipher->do_cipher(ctx, out, in, size));
1107}
1108
1109
1110/*
1111 *
1112 */
1113static int
1114enc_null_init(EVP_CIPHER_CTX *ctx,
1115    const unsigned char *key,
1116    const unsigned char *iv,
1117    int encp)
1118{
1119	return (1);
1120}
1121
1122
1123static int
1124enc_null_do_cipher(EVP_CIPHER_CTX *ctx,
1125    unsigned char *out,
1126    const unsigned char *in,
1127    unsigned int size)
1128{
1129	memmove(out, in, size);
1130	return (1);
1131}
1132
1133
1134static int
1135enc_null_cleanup(EVP_CIPHER_CTX *ctx)
1136{
1137	return (1);
1138}
1139
1140
1141/**
1142 * The NULL cipher type, does no encryption/decryption.
1143 *
1144 * @return the null EVP_CIPHER pointer.
1145 *
1146 * @ingroup hcrypto_evp
1147 */
1148const EVP_CIPHER *
1149EVP_enc_null(void)
1150{
1151	static const EVP_CIPHER enc_null =
1152	{
1153		.nid			=		0,
1154		.block_size		=		0,
1155		.key_len		=		0,
1156		.iv_len			=		0,
1157		.flags			= EVP_CIPH_CBC_MODE,
1158		.init			= enc_null_init,
1159		.do_cipher		= enc_null_do_cipher,
1160		.cleanup		= enc_null_cleanup,
1161		.ctx_size		=		0,
1162		.set_asn1_parameters	= NULL,
1163		.get_asn1_parameters	= NULL,
1164		.ctrl			= NULL,
1165		.app_data		= NULL
1166	};
1167
1168	return (&enc_null);
1169}
1170
1171
1172/**
1173 * The RC2 cipher type
1174 *
1175 * @return the RC2 EVP_CIPHER pointer.
1176 */
1177const EVP_CIPHER *
1178EVP_rc2_cbc(void)
1179{
1180	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rc2_cbc));
1181}
1182
1183
1184/**
1185 * The RC2 cipher type
1186 *
1187 * @return the RC2 EVP_CIPHER pointer.
1188 */
1189const EVP_CIPHER *
1190EVP_rc2_40_cbc(void)
1191{
1192	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rc2_40_cbc));
1193}
1194
1195
1196/**
1197 * The RC2 cipher type
1198 *
1199 * @return the RC2 EVP_CIPHER pointer.
1200 */
1201const EVP_CIPHER *
1202EVP_rc2_64_cbc(void)
1203{
1204	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rc2_64_cbc));
1205}
1206
1207
1208/**
1209 * The RC4 cipher type
1210 *
1211 * @return the RC4 EVP_CIPHER pointer.
1212 */
1213const EVP_CIPHER *
1214EVP_rc4(void)
1215{
1216	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rc4));
1217}
1218
1219
1220/**
1221 * The RC4-40 cipher type
1222 *
1223 * @return the RC4-40 EVP_CIPHER pointer.
1224 */
1225const EVP_CIPHER *
1226EVP_rc4_40(void)
1227{
1228	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, rc4_40));
1229}
1230
1231
1232/**
1233 * The DES cipher type
1234 *
1235 * @return the DES-ECB EVP_CIPHER pointer.
1236 */
1237const EVP_CIPHER *
1238EVP_des_ecb(void)
1239{
1240	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, des_ecb));
1241}
1242
1243
1244/**
1245 * The DES cipher type
1246 *
1247 * @return the DES-CBC EVP_CIPHER pointer.
1248 */
1249const EVP_CIPHER *
1250EVP_des_cbc(void)
1251{
1252	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, des_cbc));
1253}
1254
1255
1256/**
1257 * The tripple DES cipher type
1258 *
1259 * @return the DES-EDE3-CBC EVP_CIPHER pointer.
1260 */
1261const EVP_CIPHER *
1262EVP_des_ede3_cbc(void)
1263{
1264	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, des_ede3_cbc));
1265}
1266
1267
1268/**
1269 * The tripple DES cipher type
1270 *
1271 * @return the DES-EDE3-ECB EVP_CIPHER pointer.
1272 */
1273const EVP_CIPHER *
1274EVP_des_ede3_ecb(void)
1275{
1276	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, des_ede3_ecb));
1277}
1278
1279
1280/**
1281 * The AES-128 cipher type
1282 *
1283 * @return the AES-128 EVP_CIPHER pointer.
1284 */
1285const EVP_CIPHER *
1286EVP_aes_128_cbc(void)
1287{
1288	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_128_cbc));
1289}
1290
1291
1292/**
1293 * The AES-128 cipher type
1294 *
1295 * @return the AES-128 EVP_CIPHER pointer.
1296 */
1297const EVP_CIPHER *
1298EVP_aes_128_ecb(void)
1299{
1300	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_128_ecb));
1301}
1302
1303
1304/**
1305 * The AES-192 cipher type
1306 *
1307 * @return the AES-192 EVP_CIPHER pointer.
1308 */
1309const EVP_CIPHER *
1310EVP_aes_192_cbc(void)
1311{
1312	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_192_cbc));
1313}
1314
1315
1316/**
1317 * The AES-192 cipher type
1318 *
1319 * @return the AES-192 EVP_CIPHER pointer.
1320 */
1321const EVP_CIPHER *
1322EVP_aes_192_ecb(void)
1323{
1324	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_192_ecb));
1325}
1326
1327
1328/**
1329 * The AES-256 cipher type
1330 *
1331 * @return the AES-256 EVP_CIPHER pointer.
1332 */
1333const EVP_CIPHER *
1334EVP_aes_256_cbc(void)
1335{
1336	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_256_cbc));
1337}
1338
1339
1340/**
1341 * The AES-256 cipher type
1342 *
1343 * @return the AES-256 EVP_CIPHER pointer.
1344 */
1345const EVP_CIPHER *
1346EVP_aes_256_ecb(void)
1347{
1348	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_256_ecb));
1349}
1350
1351
1352/**
1353 * The AES-128 CFB8 cipher type
1354 *
1355 * @return the AES-128 EVP_CIPHER pointer.
1356 */
1357const EVP_CIPHER *
1358EVP_aes_128_cfb8(void)
1359{
1360#ifndef __APPLE_TARGET_EMBEDDED__
1361	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_128_cfb8));
1362
1363#else
1364	return (NULL);
1365#endif
1366}
1367
1368
1369/**
1370 * The AES-192 CFB8 cipher type
1371 *
1372 * @return the AES-192 EVP_CIPHER pointer.
1373 *
1374 * @ingroup hcrypto_evp
1375 */
1376const EVP_CIPHER *
1377EVP_aes_192_cfb8(void)
1378{
1379#ifndef __APPLE_TARGET_EMBEDDED__
1380	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_192_cfb8));
1381
1382#else
1383	return (NULL);
1384#endif
1385}
1386
1387
1388/**
1389 * The AES-256 CFB8 cipher type
1390 *
1391 * @return the AES-256 EVP_CIPHER pointer.
1392 *
1393 * @ingroup hcrypto_evp
1394 */
1395const EVP_CIPHER *
1396EVP_aes_256_cfb8(void)
1397{
1398#ifndef __APPLE_TARGET_EMBEDDED__
1399	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, aes_256_cfb8));
1400
1401#else
1402	return (NULL);
1403#endif
1404}
1405
1406
1407/**
1408 * The Camellia-128 cipher type
1409 *
1410 * @return the Camellia-128 EVP_CIPHER pointer.
1411 */
1412const EVP_CIPHER *
1413EVP_camellia_128_cbc(void)
1414{
1415	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, camellia_128_cbc));
1416}
1417
1418
1419/**
1420 * The Camellia-198 cipher type
1421 *
1422 * @return the Camellia-198 EVP_CIPHER pointer.
1423 */
1424const EVP_CIPHER *
1425EVP_camellia_192_cbc(void)
1426{
1427	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, camellia_192_cbc));
1428}
1429
1430
1431/**
1432 * The Camellia-256 cipher type
1433 *
1434 * @return the Camellia-256 EVP_CIPHER pointer.
1435 */
1436const EVP_CIPHER *
1437EVP_camellia_256_cbc(void)
1438{
1439	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, camellia_256_cbc));
1440}
1441
1442
1443/**
1444 * The blowfish ecb cipher type
1445 *
1446 * @return the bf_ecb EVP_CIPHER pointer.
1447 */
1448const EVP_CIPHER *
1449EVP_bf_ecb(void)
1450{
1451	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, bf_ecb));
1452}
1453
1454
1455/**
1456 * The blowfish cbc cipher type
1457 *
1458 * @return the bf_ecb EVP_CIPHER pointer.
1459 */
1460const EVP_CIPHER *
1461EVP_bf_cbc(void)
1462{
1463	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, bf_cbc));
1464}
1465
1466
1467/**
1468 * The cast5 ecb cipher type
1469 *
1470 * @return the bf_ecb EVP_CIPHER pointer.
1471 */
1472const EVP_CIPHER *
1473EVP_cast5_ecb(void)
1474{
1475	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, cast5_ecb));
1476}
1477
1478
1479/**
1480 * The cast5 cbc cipher type
1481 *
1482 * @return the bf_ecb EVP_CIPHER pointer.
1483 */
1484const EVP_CIPHER *
1485EVP_cast5_cbc(void)
1486{
1487	return (EVP_DEF_OP(OSSL_DEF_PROVIDER, cast5_cbc));
1488}
1489
1490
1491/*
1492 *
1493 */
1494
1495static const struct cipher_name {
1496	const char *		name;
1497	const EVP_CIPHER *	(*func)(void);
1498}
1499cipher_name[] =
1500{
1501	{ "des-ecb",	      EVP_des_ecb	   },
1502	{ "des-cbc",	      EVP_des_cbc	   },
1503	{ "des-ede3-ecb",     EVP_des_ede3_ecb	   },
1504	{ "des-ede3-cbc",     EVP_des_ede3_cbc	   },
1505	{ "aes-128-ecb",      EVP_aes_128_ecb	   },
1506	{ "aes-192-ecb",      EVP_aes_192_ecb	   },
1507	{ "aes-256-ecb",      EVP_aes_256_ecb	   },
1508	{ "aes-128-cbc",      EVP_aes_128_cbc	   },
1509	{ "aes-192-cbc",      EVP_aes_192_cbc	   },
1510	{ "aes-256-cbc",      EVP_aes_256_cbc	   },
1511	{ "aes-128-cfb8",     EVP_aes_128_cfb8	   },
1512	{ "aes-192-cfb8",     EVP_aes_192_cfb8	   },
1513	{ "aes-256-cfb8",     EVP_aes_256_cfb8	   },
1514	{ "camellia-128-cbc", EVP_camellia_128_cbc },
1515	{ "camellia-192-cbc", EVP_camellia_192_cbc },
1516	{ "camellia-256-cbc", EVP_camellia_256_cbc },
1517	{ "bf-ecb",	      EVP_bf_ecb	   },
1518	{ "bf-cbc",	      EVP_bf_cbc	   },
1519	{ "cast5-ecb",	      EVP_cast5_ecb	   },
1520	{ "cast5-cbc",	      EVP_cast5_cbc	   },
1521};
1522
1523/**
1524 * Get the cipher type using their name.
1525 *
1526 * @param name the name of the cipher.
1527 *
1528 * @return the selected EVP_CIPHER pointer or NULL if not found.
1529 *
1530 * @ingroup hcrypto_evp
1531 */
1532const EVP_CIPHER *
1533EVP_get_cipherbyname(const char *name)
1534{
1535	int i;
1536
1537	for (i = 0; i < sizeof(cipher_name)/sizeof(cipher_name[0]); i++) {
1538		if (strcasecmp(cipher_name[i].name, name) == 0) {
1539			return ((*cipher_name[i].func)());
1540		}
1541	}
1542	return (NULL);
1543}
1544
1545
1546/*
1547 *
1548 */
1549
1550#ifndef min
1551#define min(a, b)    (((a) > (b)) ? (b) : (a))
1552#endif
1553
1554/**
1555 * Provides a legancy string to key function, used in PEM files.
1556 *
1557 * New protocols should use new string to key functions like NIST
1558 * SP56-800A or PKCS#5 v2.0 (see PKCS5_PBKDF2_HMAC_SHA1()).
1559 *
1560 * @param type type of cipher to use
1561 * @param md message digest to use
1562 * @param salt salt salt string, should be an binary 8 byte buffer.
1563 * @param data the password/input key string.
1564 * @param datalen length of data parameter.
1565 * @param count iteration counter.
1566 * @param keydata output keydata, needs to of the size EVP_CIPHER_key_length().
1567 * @param ivdata output ivdata, needs to of the size EVP_CIPHER_block_size().
1568 *
1569 * @return the size of derived key.
1570 */
1571int
1572EVP_BytesToKey(const EVP_CIPHER *type,
1573    const EVP_MD *md,
1574    const void *salt,
1575    const void *data, size_t datalen,
1576    unsigned int count,
1577    void *keydata,
1578    void *ivdata)
1579{
1580	unsigned int ivlen, keylen;
1581	int first = 0;
1582	unsigned int mds = 0, i;
1583	unsigned char *key = keydata;
1584	unsigned char *iv = ivdata;
1585	unsigned char *buf;
1586	EVP_MD_CTX c;
1587
1588	keylen = EVP_CIPHER_key_length(type);
1589	ivlen = EVP_CIPHER_iv_length(type);
1590
1591	if (data == NULL) {
1592		return (keylen);
1593	}
1594
1595	buf = malloc(EVP_MD_size(md));
1596	if (buf == NULL) {
1597		return (-1);
1598	}
1599
1600	EVP_MD_CTX_init(&c);
1601
1602	first = 1;
1603	while (1) {
1604		EVP_DigestInit_ex(&c, md, NULL);
1605		if (!first) {
1606			EVP_DigestUpdate(&c, buf, mds);
1607		}
1608		first = 0;
1609		EVP_DigestUpdate(&c, data, datalen);
1610
1611#define PKCS5_SALT_LEN    8
1612
1613		if (salt) {
1614			EVP_DigestUpdate(&c, salt, PKCS5_SALT_LEN);
1615		}
1616
1617		EVP_DigestFinal_ex(&c, buf, &mds);
1618		assert(mds == EVP_MD_size(md));
1619
1620		for (i = 1; i < count; i++) {
1621			EVP_DigestInit_ex(&c, md, NULL);
1622			EVP_DigestUpdate(&c, buf, mds);
1623			EVP_DigestFinal_ex(&c, buf, &mds);
1624			assert(mds == EVP_MD_size(md));
1625		}
1626
1627		i = 0;
1628		if (keylen) {
1629			size_t sz = min(keylen, mds);
1630			if (key) {
1631				memcpy(key, buf, sz);
1632				key += sz;
1633			}
1634			keylen -= sz;
1635			i += sz;
1636		}
1637		if (ivlen && (mds > i)) {
1638			size_t sz = min(ivlen, (mds - i));
1639			if (iv) {
1640				memcpy(iv, &buf[i], sz);
1641				iv += sz;
1642			}
1643			ivlen -= sz;
1644		}
1645		if ((keylen == 0) && (ivlen == 0)) {
1646			break;
1647		}
1648	}
1649
1650	EVP_MD_CTX_cleanup(&c);
1651	free(buf);
1652
1653	return (EVP_CIPHER_key_length(type));
1654}
1655
1656
1657static char prompt_string[80];
1658
1659void
1660EVP_set_pw_prompt(const char *prompt)
1661{
1662	if (prompt == NULL) {
1663		prompt_string[0] = '\0';
1664	} else {
1665		strncpy(prompt_string, prompt, 79);
1666		prompt_string[79] = '\0';
1667	}
1668}
1669
1670
1671char *
1672EVP_get_pw_prompt(void)
1673{
1674	if (prompt_string[0] == '\0') {
1675		return (NULL);
1676	} else{
1677		return (prompt_string);
1678	}
1679}
1680
1681
1682int
1683EVP_read_pw_string(char *buf, int len, const char *prompt, int verify)
1684{
1685	if ((prompt == NULL) && (prompt_string[0] != '\0')) {
1686		prompt = prompt_string;
1687	}
1688
1689	return (UI_UTIL_read_pw_string(buf, len, prompt, verify));
1690}
1691
1692
1693/**
1694 * Generate a random key for the specificed EVP_CIPHER.
1695 *
1696 * @param ctx EVP_CIPHER_CTX type to build the key for.
1697 * @param key return key, must be at least EVP_CIPHER_key_length() byte long.
1698 *
1699 * @return 1 for success, 0 for failure.
1700 */
1701int
1702EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, void *key)
1703{
1704	if (ctx->cipher->flags & EVP_CIPH_RAND_KEY) {
1705		return (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_RAND_KEY, 0, key));
1706	}
1707	if (CCRandomCopyBytes(kCCRandomDefault, key, ctx->key_len) != 0) {
1708		return (0);
1709	}
1710	return (1);
1711}
1712
1713
1714/**
1715 * Perform a operation on a ctx
1716 *
1717 * @param ctx context to perform operation on.
1718 * @param type type of operation.
1719 * @param arg argument to operation.
1720 * @param data addition data to operation.
1721 *
1722 * @return 1 for success, 0 for failure.
1723 */
1724int
1725EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *data)
1726{
1727	if ((ctx->cipher == NULL) || (ctx->cipher->ctrl == NULL)) {
1728		return (0);
1729	}
1730	return ((*ctx->cipher->ctrl)(ctx, type, arg, data));
1731}
1732
1733
1734static void ossl_EVP_PKEY_free_it(EVP_PKEY *x);
1735
1736#define EVP_PKEY_assign_RSA(pkey, rsa)		EVP_PKEY_assign((pkey), EVP_PKEY_RSA, (char *)(rsa))
1737#define EVP_PKEY_assign_DSA(pkey, dsa)		EVP_PKEY_assign((pkey), EVP_PKEY_DSA, (char *)(dsa))
1738#define EVP_PKEY_assign_DH(pkey, dh)		EVP_PKEY_assign((pkey), EVP_PKEY_DH, (char *)(dh))
1739
1740int
1741EVP_PKEY_assign(EVP_PKEY *pkey, int type, char *key)
1742{
1743	if (pkey == NULL) {
1744		return (0);
1745	}
1746	if (pkey->pkey.ptr != NULL) {
1747		ossl_EVP_PKEY_free_it(pkey);
1748	}
1749	pkey->type = EVP_PKEY_type(type);
1750	pkey->save_type = type;
1751	pkey->pkey.ptr = key;
1752	return (key != NULL);
1753}
1754
1755
1756RSA *
1757EVP_PKEY_get1_RSA(EVP_PKEY *pkey)
1758{
1759	if (pkey->type != EVP_PKEY_RSA) {
1760		return (NULL);
1761	}
1762
1763	RSA_up_ref(pkey->pkey.rsa);
1764	return (pkey->pkey.rsa);
1765}
1766
1767
1768int
1769EVP_PKEY_set1_RSA(EVP_PKEY *pkey, RSA *key)
1770{
1771	int ret = EVP_PKEY_assign_RSA(pkey, key);
1772
1773	if (ret) {
1774		RSA_up_ref(key);
1775	}
1776
1777	return (ret);
1778}
1779
1780
1781DSA *
1782EVP_PKEY_get1_DSA(EVP_PKEY *pkey)
1783{
1784	if (pkey->type != EVP_PKEY_DSA) {
1785		return (NULL);
1786	}
1787
1788	DSA_up_ref(pkey->pkey.dsa);
1789	return (pkey->pkey.dsa);
1790}
1791
1792
1793int
1794EVP_PKEY_set1_DSA(EVP_PKEY *pkey, DSA *key)
1795{
1796	int ret = EVP_PKEY_assign_DSA(pkey, key);
1797
1798	if (ret) {
1799		DSA_up_ref(key);
1800	}
1801
1802	return (ret);
1803}
1804
1805
1806int EVP_PKEY_type(int type)
1807{
1808	switch (type) {
1809	case EVP_PKEY_RSA:
1810	case EVP_PKEY_RSA2:
1811		return (EVP_PKEY_RSA);
1812
1813	case EVP_PKEY_DSA:
1814	case EVP_PKEY_DSA1:
1815	case EVP_PKEY_DSA2:
1816	case EVP_PKEY_DSA3:
1817	case EVP_PKEY_DSA4:
1818		return (EVP_PKEY_DSA);
1819
1820	case EVP_PKEY_DH:
1821		return (EVP_PKEY_DH);
1822
1823	default:
1824		return (NID_undef);
1825	}
1826}
1827
1828
1829EVP_PKEY *
1830EVP_PKEY_new(void)
1831{
1832	EVP_PKEY *ret = (EVP_PKEY *)malloc(sizeof(EVP_PKEY));
1833
1834	if (ret == NULL) {
1835		/* EVPerr(EVP_F_EVP_PKEY_NEW,ERR_R_MALLOC_FAILURE); */
1836		return (NULL);
1837	}
1838	ret->type = EVP_PKEY_NONE;
1839	ret->references = 1;
1840	ret->pkey.ptr = NULL;
1841#if 0
1842	ret->attributes = NULL;
1843#endif
1844	ret->save_parameters = 1;
1845	return (ret);
1846}
1847
1848
1849static void
1850ossl_EVP_PKEY_free_it(EVP_PKEY *x)
1851{
1852	switch (x->type) {
1853	case EVP_PKEY_RSA:
1854	case EVP_PKEY_RSA2:
1855		if (x->pkey.rsa) {
1856			RSA_free(x->pkey.rsa);
1857		}
1858		break;
1859
1860	case EVP_PKEY_DSA:
1861	case EVP_PKEY_DSA2:
1862	case EVP_PKEY_DSA3:
1863	case EVP_PKEY_DSA4:
1864		if (x->pkey.dsa) {
1865			DSA_free(x->pkey.dsa);
1866		}
1867		break;
1868
1869	case EVP_PKEY_DH:
1870		if (x->pkey.dh) {
1871			DH_free(x->pkey.dh);
1872		}
1873		break;
1874	}
1875}
1876
1877
1878void
1879EVP_PKEY_free(EVP_PKEY *x)
1880{
1881	int i;
1882
1883	if (x == NULL) {
1884		return;
1885	}
1886
1887	/* XXX not thread safe. */
1888	x->references--;
1889	if (i > 0) {
1890		return;
1891	}
1892	ossl_EVP_PKEY_free_it(x);
1893#if 0
1894	if (x->attributes) {
1895		sk_X509_ATTRIBUTE_pop_free(x->attributes, X509_ATTRIBUTE_free);
1896	}
1897#endif
1898	free(x);
1899}
1900
1901
1902/*
1903 *
1904 */
1905
1906#define conv_bin2ascii(a)	(data_bin2ascii[(a) & 0x3f])
1907#define conv_ascii2bin(a)	(data_ascii2bin[(a) & 0x7f])
1908
1909/* 64 char lines
1910 * pad input with 0
1911 * left over chars are set to =
1912 * 1 byte  => xx==
1913 * 2 bytes => xxx=
1914 * 3 bytes => xxxx
1915 */
1916#define BIN_PER_LINE		(64 / 4 * 3)
1917#define CHUNKS_PER_LINE		(64 / 4)
1918#define CHAR_PER_LINE		(64 + 1)
1919
1920static unsigned char data_bin2ascii[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\
1921abcdefghijklmnopqrstuvwxyz0123456789+/";
1922
1923/* 0xF0 is a EOLN
1924 * 0xF1 is ignore but next needs to be 0xF0 (for \r\n processing).
1925 * 0xF2 is EOF
1926 * 0xE0 is ignore at start of line.
1927 * 0xFF is error
1928 */
1929
1930#define B64_EOLN	0xF0
1931#define B64_CR		0xF1
1932#define B64_EOF		0xF2
1933#define B64_WS		0xE0
1934#define B64_ERROR	0xFF
1935#define B64_NOT_BASE64(a)    (((a)|0x13) == 0xF3)
1936
1937static unsigned char data_ascii2bin[128] =
1938{
1939	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1940	0xFF, 0xE0, 0xF0, 0xFF, 0xFF, 0xF1, 0xFF, 0xFF,
1941	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1942	0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1943	0xE0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1944	0xFF, 0xFF, 0xFF, 0x3E, 0xFF, 0xF2, 0xFF, 0x3F,
1945	0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B,
1946	0x3C, 0x3D, 0xFF, 0xFF, 0xFF, 0x00, 0xFF, 0xFF,
1947	0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
1948	0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
1949	0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
1950	0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1951	0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20,
1952	0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
1953	0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30,
1954	0x31, 0x32, 0x33, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
1955};
1956
1957void
1958EVP_EncodeInit(EVP_ENCODE_CTX *ctx)
1959{
1960	ctx->length = 48;
1961	ctx->num = 0;
1962	ctx->line_num = 0;
1963}
1964
1965
1966void
1967EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
1968    const unsigned char *in, int inl)
1969{
1970	int i, j;
1971	unsigned int total = 0;
1972
1973	*outl = 0;
1974	if (inl == 0) {
1975		return;
1976	}
1977	/* assert(ctx->length <= (int)sizeof(ctx->enc_data)); */
1978	if ((ctx->num+inl) < ctx->length) {
1979		memcpy(&(ctx->enc_data[ctx->num]), in, inl);
1980		ctx->num += inl;
1981		return;
1982	}
1983	if (ctx->num != 0) {
1984		i = ctx->length-ctx->num;
1985		memcpy(&(ctx->enc_data[ctx->num]), in, i);
1986		in += i;
1987		inl -= i;
1988		j = EVP_EncodeBlock(out, ctx->enc_data, ctx->length);
1989		ctx->num = 0;
1990		out += j;
1991		*(out++) = '\n';
1992		*out = '\0';
1993		total = j + 1;
1994	}
1995	while (inl >= ctx->length) {
1996		j = EVP_EncodeBlock(out, in, ctx->length);
1997		in += ctx->length;
1998		inl -= ctx->length;
1999		out += j;
2000		*(out++) = '\n';
2001		*out = '\0';
2002		total += j + 1;
2003	}
2004	if (inl != 0) {
2005		memcpy(&(ctx->enc_data[0]), in, inl);
2006	}
2007	ctx->num = inl;
2008	*outl = total;
2009}
2010
2011
2012void
2013EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl)
2014{
2015	unsigned int ret = 0;
2016
2017	if (ctx->num != 0) {
2018		ret = EVP_EncodeBlock(out, ctx->enc_data, ctx->num);
2019		out[ret++] = '\n';
2020		out[ret] = '\0';
2021		ctx->num = 0;
2022	}
2023	*outl = ret;
2024}
2025
2026
2027int
2028EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int dlen)
2029{
2030	int i, ret = 0;
2031	unsigned long l;
2032
2033	for (i = dlen; i > 0; i -= 3) {
2034		if (i >= 3) {
2035			l = (((unsigned long)f[0])<<16L) |
2036			    (((unsigned long)f[1])<< 8L)|f[2];
2037			*(t++) = conv_bin2ascii(l>>18L);
2038			*(t++) = conv_bin2ascii(l>>12L);
2039			*(t++) = conv_bin2ascii(l>> 6L);
2040			*(t++) = conv_bin2ascii(l);
2041		} else {
2042			l = ((unsigned long)f[0])<<16L;
2043			if (i == 2) {
2044				l |= ((unsigned long)f[1] << 8L);
2045			}
2046
2047			*(t++) = conv_bin2ascii(l>>18L);
2048			*(t++) = conv_bin2ascii(l>>12L);
2049			*(t++) = (i == 1) ? '=' : conv_bin2ascii(l>>6L);
2050			*(t++) = '=';
2051		}
2052		ret += 4;
2053		f += 3;
2054	}
2055
2056	*t = '\0';
2057	return (ret);
2058}
2059
2060
2061void
2062EVP_DecodeInit(EVP_ENCODE_CTX *ctx)
2063{
2064	ctx->length = 30;
2065	ctx->num = 0;
2066	ctx->line_num = 0;
2067	ctx->expect_nl = 0;
2068}
2069
2070
2071/* -1 for error
2072 *  0 for last line
2073 *  1 for full line
2074 */
2075int
2076EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
2077    const unsigned char *in, int inl)
2078{
2079	int seof = -1, eof = 0, rv = -1, ret = 0, i, v, tmp, n, ln, exp_nl;
2080	unsigned char *d;
2081
2082	n = ctx->num;
2083	d = ctx->enc_data;
2084	ln = ctx->line_num;
2085	exp_nl = ctx->expect_nl;
2086
2087	/* last line of input. */
2088	if ((inl == 0) || ((n == 0) && (conv_ascii2bin(in[0]) == B64_EOF))) {
2089		rv = 0;
2090		goto end;
2091	}
2092
2093	/* We parse the input data */
2094	for (i = 0; i < inl; i++) {
2095		/* If the current line is > 80 characters, scream alot */
2096		if (ln >= 80) {
2097			rv = -1;
2098			goto end;
2099		}
2100
2101		/* Get char and put it into the buffer */
2102		tmp = *(in++);
2103		v = conv_ascii2bin(tmp);
2104		/* only save the good data :-) */
2105		if (!B64_NOT_BASE64(v)) {
2106			/* assert(n < (int)sizeof(ctx->enc_data)); */
2107			d[n++] = tmp;
2108			ln++;
2109		} else if (v == B64_ERROR) {
2110			rv = -1;
2111			goto end;
2112		}
2113
2114		/* have we seen a '=' which is 'definitly' the last
2115		 * input line.  seof will point to the character that
2116		 * holds it. and eof will hold how many characters to
2117		 * chop off. */
2118		if (tmp == '=') {
2119			if (seof == -1) {
2120				seof = n;
2121			}
2122			eof++;
2123		}
2124
2125		if (v == B64_CR) {
2126			ln = 0;
2127			if (exp_nl) {
2128				continue;
2129			}
2130		}
2131
2132		/* eoln */
2133		if (v == B64_EOLN) {
2134			ln = 0;
2135			if (exp_nl) {
2136				exp_nl = 0;
2137				continue;
2138			}
2139		}
2140		exp_nl = 0;
2141
2142		/* If we are at the end of input and it looks like a
2143		 * line, process it. */
2144		if (((i+1) == inl) && (((n&3) == 0) || eof)) {
2145			v = B64_EOF;
2146
2147			/* In case things were given us in really small
2148			 * records (so two '=' were given in separate
2149			 * updates), eof may contain the incorrect number
2150			 * of ending bytes to skip, so let's redo the count */
2151			eof = 0;
2152			if (d[n-1] == '=') {
2153				eof++;
2154			}
2155			if (d[n-2] == '=') {
2156				eof++;
2157			}
2158			/* There will never be more than two '=' */
2159		}
2160
2161		if (((v == B64_EOF) && ((n&3) == 0)) || (n >= 64)) {
2162			/* This is needed to work correctly on 64 byte input
2163			 * lines.  We process the line and then need to
2164			 * accept the '\n' */
2165			if ((v != B64_EOF) && (n >= 64)) {
2166				exp_nl = 1;
2167			}
2168			if (n > 0) {
2169				v = EVP_DecodeBlock(out, d, n);
2170				n = 0;
2171				if (v < 0) {
2172					rv = 0;
2173					goto end;
2174				}
2175				ret += (v-eof);
2176			} else {
2177				eof = 1;
2178				v = 0;
2179			}
2180
2181			/* This is the case where we have had a short
2182			 * but valid input line */
2183			if ((v < ctx->length) && eof) {
2184				rv = 0;
2185				goto end;
2186			} else{
2187				ctx->length = v;
2188			}
2189
2190			if (seof >= 0) {
2191				rv = 0;
2192				goto end;
2193			}
2194			out += v;
2195		}
2196	}
2197	rv = 1;
2198end:
2199	*outl = ret;
2200	ctx->num = n;
2201	ctx->line_num = ln;
2202	ctx->expect_nl = exp_nl;
2203	return (rv);
2204}
2205
2206
2207int
2208EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n)
2209{
2210	int i, ret = 0, a, b, c, d;
2211	unsigned long l;
2212
2213	/* trim white space from the start of the line. */
2214	while ((conv_ascii2bin(*f) == B64_WS) && (n > 0)) {
2215		f++;
2216		n--;
2217	}
2218
2219	/* strip off stuff at the end of the line
2220	 * ascii2bin values B64_WS, B64_EOLN, B64_EOLN and B64_EOF */
2221	while ((n > 3) && (B64_NOT_BASE64(conv_ascii2bin(f[n-1])))) {
2222		n--;
2223	}
2224
2225	if (n % 4 != 0) {
2226		return (-1);
2227	}
2228
2229	for (i = 0; i < n; i += 4) {
2230		a = conv_ascii2bin(*(f++));
2231		b = conv_ascii2bin(*(f++));
2232		c = conv_ascii2bin(*(f++));
2233		d = conv_ascii2bin(*(f++));
2234		if ((a & 0x80) || (b & 0x80) || (c & 0x80) || (d & 0x80)) {
2235			return (-1);
2236		}
2237		l = ((((unsigned long)a) << 18L) |
2238		    (((unsigned long)b) << 12L) |
2239		    (((unsigned long)c) << 6L)  |
2240		    (((unsigned long)d)));
2241		*(t++) = (unsigned char)(l >> 16L) & 0xff;
2242		*(t++) = (unsigned char)(l >> 8L) & 0xff;
2243		*(t++) = (unsigned char)(l) & 0xff;
2244		ret += 3;
2245	}
2246	return (ret);
2247}
2248
2249
2250int
2251EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl)
2252{
2253	int i;
2254
2255	*outl = 0;
2256	if (ctx->num != 0) {
2257		i = EVP_DecodeBlock(out, ctx->enc_data, ctx->num);
2258		if (i < 0) {
2259			return (-1);
2260		}
2261		ctx->num = 0;
2262		*outl = i;
2263		return (1);
2264	} else{
2265		return (1);
2266	}
2267}
2268