449a1fe9849c9aaa2381f1880de784ad938b9c61
[openssl.git] / crypto / pem / pem_lib.c
1 /* crypto/pem/pem_lib.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/buffer.h>
62 #include <openssl/objects.h>
63 #include <openssl/evp.h>
64 #include <openssl/rand.h>
65 #include <openssl/x509.h>
66 #include <openssl/pem.h>
67 #include <openssl/pkcs12.h>
68 #ifndef NO_DES
69 #include <openssl/des.h>
70 #endif
71
72 const char *PEM_version="PEM" OPENSSL_VERSION_PTEXT;
73
74 #define MIN_LENGTH      4
75
76 static int def_callback(char *buf, int num, int w, void *userdata);
77 static int load_iv(unsigned char **fromp,unsigned char *to, int num);
78 static int check_pem(const char *nm, const char *name);
79 static int do_pk8pkey(BIO *bp, EVP_PKEY *x, int isder,
80                                 int nid, const EVP_CIPHER *enc,
81                                 char *kstr, int klen,
82                                 pem_password_cb *cb, void *u);
83 static int do_pk8pkey_fp(FILE *bp, EVP_PKEY *x, int isder,
84                                 int nid, const EVP_CIPHER *enc,
85                                 char *kstr, int klen,
86                                 pem_password_cb *cb, void *u);
87
88 static int def_callback(char *buf, int num, int w, void *userdata)
89         {
90 #ifdef NO_FP_API
91         /* We should not ever call the default callback routine from
92          * windows. */
93         PEMerr(PEM_F_DEF_CALLBACK,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
94         return(-1);
95 #else
96         int i,j;
97         const char *prompt;
98
99         prompt=EVP_get_pw_prompt();
100         if (prompt == NULL)
101                 prompt="Enter PEM pass phrase:";
102
103         for (;;)
104                 {
105                 i=EVP_read_pw_string(buf,num,prompt,w);
106                 if (i != 0)
107                         {
108                         PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
109                         memset(buf,0,(unsigned int)num);
110                         return(-1);
111                         }
112                 j=strlen(buf);
113                 if (j < MIN_LENGTH)
114                         {
115                         fprintf(stderr,"phrase is too short, needs to be at least %d chars\n",MIN_LENGTH);
116                         }
117                 else
118                         break;
119                 }
120         return(j);
121 #endif
122         }
123
124 /* This is a generic callback. If the user data is not NULL it is assumed 
125  * to be a null terminated password. Otherwise the default password callback
126  * is called.
127  */
128
129
130 int MS_CALLBACK PEM_cb(char *buf, int len, int verify, void *key)
131 {
132         int i;
133         if (key == NULL) return def_callback(buf, len, verify, key);
134         i=strlen(key);
135         i=(i > len)?len:i;
136         memcpy(buf,key,i);
137         return(i);
138 }
139
140 void PEM_proc_type(char *buf, int type)
141         {
142         const char *str;
143
144         if (type == PEM_TYPE_ENCRYPTED)
145                 str="ENCRYPTED";
146         else if (type == PEM_TYPE_MIC_CLEAR)
147                 str="MIC-CLEAR";
148         else if (type == PEM_TYPE_MIC_ONLY)
149                 str="MIC-ONLY";
150         else
151                 str="BAD-TYPE";
152                 
153         strcat(buf,"Proc-Type: 4,");
154         strcat(buf,str);
155         strcat(buf,"\n");
156         }
157
158 void PEM_dek_info(char *buf, const char *type, int len, char *str)
159         {
160         static unsigned char map[17]="0123456789ABCDEF";
161         long i;
162         int j;
163
164         strcat(buf,"DEK-Info: ");
165         strcat(buf,type);
166         strcat(buf,",");
167         j=strlen(buf);
168         for (i=0; i<len; i++)
169                 {
170                 buf[j+i*2]  =map[(str[i]>>4)&0x0f];
171                 buf[j+i*2+1]=map[(str[i]   )&0x0f];
172                 }
173         buf[j+i*2]='\n';
174         buf[j+i*2+1]='\0';
175         }
176
177 #ifndef NO_FP_API
178 char *PEM_ASN1_read(char *(*d2i)(), const char *name, FILE *fp, char **x,
179              pem_password_cb *cb, void *u)
180         {
181         BIO *b;
182         char *ret;
183
184         if ((b=BIO_new(BIO_s_file())) == NULL)
185                 {
186                 PEMerr(PEM_F_PEM_ASN1_READ,ERR_R_BUF_LIB);
187                 return(0);
188                 }
189         BIO_set_fp(b,fp,BIO_NOCLOSE);
190         ret=PEM_ASN1_read_bio(d2i,name,b,x,cb,u);
191         BIO_free(b);
192         return(ret);
193         }
194 #endif
195
196 static int check_pem(const char *nm, const char *name)
197 {
198         /* Normal matching nm and name */
199         if (!strcmp(nm,name)) return 1;
200
201         /* Make PEM_STRING_EVP_PKEY match any private key */
202
203         if(!strcmp(nm,PEM_STRING_PKCS8) &&
204                 !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
205
206         if(!strcmp(nm,PEM_STRING_PKCS8INF) &&
207                  !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
208
209         if(!strcmp(nm,PEM_STRING_RSA) &&
210                 !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
211
212         if(!strcmp(nm,PEM_STRING_DSA) &&
213                  !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
214
215         /* Permit older strings */
216
217         if(!strcmp(nm,PEM_STRING_X509_OLD) &&
218                 !strcmp(name,PEM_STRING_X509)) return 1;
219
220         if(!strcmp(nm,PEM_STRING_X509_REQ_OLD) &&
221                 !strcmp(name,PEM_STRING_X509_REQ)) return 1;
222
223         /* Allow normal certs to be read as trusted certs */
224         if(!strcmp(nm,PEM_STRING_X509) &&
225                 !strcmp(name,PEM_STRING_X509_TRUSTED)) return 1;
226
227         if(!strcmp(nm,PEM_STRING_X509_OLD) &&
228                 !strcmp(name,PEM_STRING_X509_TRUSTED)) return 1;
229
230         return 0;
231 }
232
233 char *PEM_ASN1_read_bio(char *(*d2i)(), const char *name, BIO *bp, char **x,
234              pem_password_cb *cb, void *u)
235         {
236         EVP_CIPHER_INFO cipher;
237         char *nm=NULL,*header=NULL;
238         unsigned char *p=NULL,*data=NULL;
239         long len;
240         char *ret=NULL;
241
242         for (;;)
243                 {
244                 if (!PEM_read_bio(bp,&nm,&header,&data,&len)) {
245                         if(ERR_GET_REASON(ERR_peek_error()) ==
246                                 PEM_R_NO_START_LINE)
247                                 ERR_add_error_data(2, "Expecting: ", name);
248                         return(NULL);
249                 }
250                 if(check_pem(nm, name)) break;
251                 Free(nm);
252                 Free(header);
253                 Free(data);
254                 }
255         if (!PEM_get_EVP_CIPHER_INFO(header,&cipher)) goto err;
256         if (!PEM_do_header(&cipher,data,&len,cb,u)) goto err;
257         p=data;
258         if (strcmp(name,PEM_STRING_EVP_PKEY) == 0) {
259                 if (strcmp(nm,PEM_STRING_RSA) == 0)
260                         ret=d2i(EVP_PKEY_RSA,x,&p,len);
261                 else if (strcmp(nm,PEM_STRING_DSA) == 0)
262                         ret=d2i(EVP_PKEY_DSA,x,&p,len);
263                 else if (strcmp(nm,PEM_STRING_PKCS8INF) == 0) {
264                         PKCS8_PRIV_KEY_INFO *p8inf;
265                         p8inf=d2i_PKCS8_PRIV_KEY_INFO(
266                                         (PKCS8_PRIV_KEY_INFO **) x, &p, len);
267                         ret = (char *)EVP_PKCS82PKEY(p8inf);
268                         PKCS8_PRIV_KEY_INFO_free(p8inf);
269                 } else if (strcmp(nm,PEM_STRING_PKCS8) == 0) {
270                         PKCS8_PRIV_KEY_INFO *p8inf;
271                         X509_SIG *p8;
272                         int klen;
273                         char psbuf[PEM_BUFSIZE];
274                         p8 = d2i_X509_SIG(NULL, &p, len);
275                         if(!p8) goto p8err;
276                         if (cb) klen=cb(psbuf,PEM_BUFSIZE,0,u);
277                         else klen=def_callback(psbuf,PEM_BUFSIZE,0,u);
278                         if (klen <= 0) {
279                                 PEMerr(PEM_F_PEM_ASN1_READ_BIO,
280                                                 PEM_R_BAD_PASSWORD_READ);
281                                 goto err;
282                         }
283                         p8inf = M_PKCS8_decrypt(p8, psbuf, klen);
284                         X509_SIG_free(p8);
285                         if(!p8inf) goto p8err;
286                         ret = (char *)EVP_PKCS82PKEY(p8inf);
287                         if(x) {
288                                 if(*x) EVP_PKEY_free((EVP_PKEY *)*x);
289                                 *x = ret;
290                         }
291                         PKCS8_PRIV_KEY_INFO_free(p8inf);
292                 }
293         } else  ret=d2i(x,&p,len);
294 p8err:
295         if (ret == NULL)
296                 PEMerr(PEM_F_PEM_ASN1_READ_BIO,ERR_R_ASN1_LIB);
297 err:
298         Free(nm);
299         Free(header);
300         Free(data);
301         return(ret);
302         }
303
304 #ifndef NO_FP_API
305 int PEM_ASN1_write(int (*i2d)(), const char *name, FILE *fp, char *x,
306              const EVP_CIPHER *enc, unsigned char *kstr, int klen,
307              pem_password_cb *callback, void *u)
308         {
309         BIO *b;
310         int ret;
311
312         if ((b=BIO_new(BIO_s_file())) == NULL)
313                 {
314                 PEMerr(PEM_F_PEM_ASN1_WRITE,ERR_R_BUF_LIB);
315                 return(0);
316                 }
317         BIO_set_fp(b,fp,BIO_NOCLOSE);
318         ret=PEM_ASN1_write_bio(i2d,name,b,x,enc,kstr,klen,callback,u);
319         BIO_free(b);
320         return(ret);
321         }
322 #endif
323
324 int PEM_ASN1_write_bio(int (*i2d)(), const char *name, BIO *bp, char *x,
325              const EVP_CIPHER *enc, unsigned char *kstr, int klen,
326              pem_password_cb *callback, void *u)
327         {
328         EVP_CIPHER_CTX ctx;
329         int dsize=0,i,j,ret=0;
330         unsigned char *p,*data=NULL;
331         const char *objstr=NULL;
332         char buf[PEM_BUFSIZE];
333         unsigned char key[EVP_MAX_KEY_LENGTH];
334         unsigned char iv[EVP_MAX_IV_LENGTH];
335         
336         if (enc != NULL)
337                 {
338                 objstr=OBJ_nid2sn(EVP_CIPHER_nid(enc));
339                 if (objstr == NULL)
340                         {
341                         PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,PEM_R_UNSUPPORTED_CIPHER);
342                         goto err;
343                         }
344                 }
345
346         if ((dsize=i2d(x,NULL)) < 0)
347                 {
348                 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,ERR_R_MALLOC_FAILURE);
349                 dsize=0;
350                 goto err;
351                 }
352         /* dzise + 8 bytes are needed */
353         data=(unsigned char *)Malloc((unsigned int)dsize+20);
354         if (data == NULL)
355                 {
356                 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,ERR_R_MALLOC_FAILURE);
357                 goto err;
358                 }
359         p=data;
360         i=i2d(x,&p);
361
362         if (enc != NULL)
363                 {
364                 if (kstr == NULL)
365                         {
366                         if (callback == NULL)
367                                 klen=def_callback(buf,PEM_BUFSIZE,1,u);
368                         else
369                                 klen=(*callback)(buf,PEM_BUFSIZE,1,u);
370                         if (klen <= 0)
371                                 {
372                                 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,PEM_R_READ_KEY);
373                                 goto err;
374                                 }
375 #ifdef CHARSET_EBCDIC
376                         /* Convert the pass phrase from EBCDIC */
377                         ebcdic2ascii(buf, buf, klen);
378 #endif
379                         kstr=(unsigned char *)buf;
380                         }
381                 RAND_add(data,i,0);/* put in the RSA key. */
382                 RAND_bytes(iv,8);       /* Generate a salt */
383                 /* The 'iv' is used as the iv and as a salt.  It is
384                  * NOT taken from the BytesToKey function */
385                 EVP_BytesToKey(enc,EVP_md5(),iv,kstr,klen,1,key,NULL);
386
387                 if (kstr == (unsigned char *)buf) memset(buf,0,PEM_BUFSIZE);
388
389                 buf[0]='\0';
390                 PEM_proc_type(buf,PEM_TYPE_ENCRYPTED);
391                 PEM_dek_info(buf,objstr,8,(char *)iv);
392                 /* k=strlen(buf); */
393         
394                 EVP_EncryptInit(&ctx,enc,key,iv);
395                 EVP_EncryptUpdate(&ctx,data,&j,data,i);
396                 EVP_EncryptFinal(&ctx,&(data[j]),&i);
397                 i+=j;
398                 ret=1;
399                 }
400         else
401                 {
402                 ret=1;
403                 buf[0]='\0';
404                 }
405         i=PEM_write_bio(bp,name,buf,data,i);
406         if (i <= 0) ret=0;
407 err:
408         memset(key,0,sizeof(key));
409         memset(iv,0,sizeof(iv));
410         memset((char *)&ctx,0,sizeof(ctx));
411         memset(buf,0,PEM_BUFSIZE);
412         memset(data,0,(unsigned int)dsize);
413         Free(data);
414         return(ret);
415         }
416
417 int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
418              pem_password_cb *callback,void *u)
419         {
420         int i,j,o,klen;
421         long len;
422         EVP_CIPHER_CTX ctx;
423         unsigned char key[EVP_MAX_KEY_LENGTH];
424         char buf[PEM_BUFSIZE];
425
426         len= *plen;
427
428         if (cipher->cipher == NULL) return(1);
429         if (callback == NULL)
430                 klen=def_callback(buf,PEM_BUFSIZE,0,u);
431         else
432                 klen=callback(buf,PEM_BUFSIZE,0,u);
433         if (klen <= 0)
434                 {
435                 PEMerr(PEM_F_PEM_DO_HEADER,PEM_R_BAD_PASSWORD_READ);
436                 return(0);
437                 }
438 #ifdef CHARSET_EBCDIC
439         /* Convert the pass phrase from EBCDIC */
440         ebcdic2ascii(buf, buf, klen);
441 #endif
442
443         EVP_BytesToKey(cipher->cipher,EVP_md5(),&(cipher->iv[0]),
444                 (unsigned char *)buf,klen,1,key,NULL);
445
446         j=(int)len;
447         EVP_DecryptInit(&ctx,cipher->cipher,key,&(cipher->iv[0]));
448         EVP_DecryptUpdate(&ctx,data,&i,data,j);
449         o=EVP_DecryptFinal(&ctx,&(data[i]),&j);
450         EVP_CIPHER_CTX_cleanup(&ctx);
451         memset((char *)buf,0,sizeof(buf));
452         memset((char *)key,0,sizeof(key));
453         j+=i;
454         if (!o)
455                 {
456                 PEMerr(PEM_F_PEM_DO_HEADER,PEM_R_BAD_DECRYPT);
457                 return(0);
458                 }
459         *plen=j;
460         return(1);
461         }
462
463 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
464         {
465         int o;
466         const EVP_CIPHER *enc=NULL;
467         char *p,c;
468
469         cipher->cipher=NULL;
470         if ((header == NULL) || (*header == '\0') || (*header == '\n'))
471                 return(1);
472         if (strncmp(header,"Proc-Type: ",11) != 0)
473                 { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_NOT_PROC_TYPE); return(0); }
474         header+=11;
475         if (*header != '4') return(0); header++;
476         if (*header != ',') return(0); header++;
477         if (strncmp(header,"ENCRYPTED",9) != 0)
478                 { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_NOT_ENCRYPTED); return(0); }
479         for (; (*header != '\n') && (*header != '\0'); header++)
480                 ;
481         if (*header == '\0')
482                 { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_SHORT_HEADER); return(0); }
483         header++;
484         if (strncmp(header,"DEK-Info: ",10) != 0)
485                 { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_NOT_DEK_INFO); return(0); }
486         header+=10;
487
488         p=header;
489         for (;;)
490                 {
491                 c= *header;
492 #ifndef CHARSET_EBCDIC
493                 if (!(  ((c >= 'A') && (c <= 'Z')) || (c == '-') ||
494                         ((c >= '0') && (c <= '9'))))
495                         break;
496 #else
497                 if (!(  isupper(c) || (c == '-') ||
498                         isdigit(c)))
499                         break;
500 #endif
501                 header++;
502                 }
503         *header='\0';
504         o=OBJ_sn2nid(p);
505         cipher->cipher=enc=EVP_get_cipherbyname(p);
506         *header=c;
507         header++;
508
509         if (enc == NULL)
510                 {
511                 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_UNSUPPORTED_ENCRYPTION);
512                 return(0);
513                 }
514         if (!load_iv((unsigned char **)&header,&(cipher->iv[0]),8)) return(0);
515
516         return(1);
517         }
518
519 static int load_iv(unsigned char **fromp, unsigned char *to, int num)
520         {
521         int v,i;
522         unsigned char *from;
523
524         from= *fromp;
525         for (i=0; i<num; i++) to[i]=0;
526         num*=2;
527         for (i=0; i<num; i++)
528                 {
529                 if ((*from >= '0') && (*from <= '9'))
530                         v= *from-'0';
531                 else if ((*from >= 'A') && (*from <= 'F'))
532                         v= *from-'A'+10;
533                 else if ((*from >= 'a') && (*from <= 'f'))
534                         v= *from-'a'+10;
535                 else
536                         {
537                         PEMerr(PEM_F_LOAD_IV,PEM_R_BAD_IV_CHARS);
538                         return(0);
539                         }
540                 from++;
541                 to[i/2]|=v<<(long)((!(i&1))*4);
542                 }
543
544         *fromp=from;
545         return(1);
546         }
547
548 #ifndef NO_FP_API
549 int PEM_write(FILE *fp, char *name, char *header, unsigned char *data,
550              long len)
551         {
552         BIO *b;
553         int ret;
554
555         if ((b=BIO_new(BIO_s_file())) == NULL)
556                 {
557                 PEMerr(PEM_F_PEM_WRITE,ERR_R_BUF_LIB);
558                 return(0);
559                 }
560         BIO_set_fp(b,fp,BIO_NOCLOSE);
561         ret=PEM_write_bio(b, name, header, data,len);
562         BIO_free(b);
563         return(ret);
564         }
565 #endif
566
567 int PEM_write_bio(BIO *bp, const char *name, char *header, unsigned char *data,
568              long len)
569         {
570         int nlen,n,i,j,outl;
571         unsigned char *buf;
572         EVP_ENCODE_CTX ctx;
573         int reason=ERR_R_BUF_LIB;
574         
575         EVP_EncodeInit(&ctx);
576         nlen=strlen(name);
577
578         if (    (BIO_write(bp,"-----BEGIN ",11) != 11) ||
579                 (BIO_write(bp,name,nlen) != nlen) ||
580                 (BIO_write(bp,"-----\n",6) != 6))
581                 goto err;
582                 
583         i=strlen(header);
584         if (i > 0)
585                 {
586                 if (    (BIO_write(bp,header,i) != i) ||
587                         (BIO_write(bp,"\n",1) != 1))
588                         goto err;
589                 }
590
591         buf=(unsigned char *)Malloc(PEM_BUFSIZE*8);
592         if (buf == NULL)
593                 {
594                 reason=ERR_R_MALLOC_FAILURE;
595                 goto err;
596                 }
597
598         i=j=0;
599         while (len > 0)
600                 {
601                 n=(int)((len>(PEM_BUFSIZE*5))?(PEM_BUFSIZE*5):len);
602                 EVP_EncodeUpdate(&ctx,buf,&outl,&(data[j]),n);
603                 if ((outl) && (BIO_write(bp,(char *)buf,outl) != outl))
604                         goto err;
605                 i+=outl;
606                 len-=n;
607                 j+=n;
608                 }
609         EVP_EncodeFinal(&ctx,buf,&outl);
610         if ((outl > 0) && (BIO_write(bp,(char *)buf,outl) != outl)) goto err;
611         Free(buf);
612         if (    (BIO_write(bp,"-----END ",9) != 9) ||
613                 (BIO_write(bp,name,nlen) != nlen) ||
614                 (BIO_write(bp,"-----\n",6) != 6))
615                 goto err;
616         return(i+outl);
617 err:
618         PEMerr(PEM_F_PEM_WRITE_BIO,reason);
619         return(0);
620         }
621
622 #ifndef NO_FP_API
623 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
624              long *len)
625         {
626         BIO *b;
627         int ret;
628
629         if ((b=BIO_new(BIO_s_file())) == NULL)
630                 {
631                 PEMerr(PEM_F_PEM_READ,ERR_R_BUF_LIB);
632                 return(0);
633                 }
634         BIO_set_fp(b,fp,BIO_NOCLOSE);
635         ret=PEM_read_bio(b, name, header, data,len);
636         BIO_free(b);
637         return(ret);
638         }
639 #endif
640
641 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
642              long *len)
643         {
644         EVP_ENCODE_CTX ctx;
645         int end=0,i,k,bl=0,hl=0,nohead=0;
646         char buf[256];
647         BUF_MEM *nameB;
648         BUF_MEM *headerB;
649         BUF_MEM *dataB,*tmpB;
650         
651         nameB=BUF_MEM_new();
652         headerB=BUF_MEM_new();
653         dataB=BUF_MEM_new();
654         if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL))
655                 {
656                 PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE);
657                 return(0);
658                 }
659
660         buf[254]='\0';
661         for (;;)
662                 {
663                 i=BIO_gets(bp,buf,254);
664
665                 if (i <= 0)
666                         {
667                         PEMerr(PEM_F_PEM_READ_BIO,PEM_R_NO_START_LINE);
668                         goto err;
669                         }
670
671                 while ((i >= 0) && (buf[i] <= ' ')) i--;
672                 buf[++i]='\n'; buf[++i]='\0';
673
674                 if (strncmp(buf,"-----BEGIN ",11) == 0)
675                         {
676                         i=strlen(&(buf[11]));
677
678                         if (strncmp(&(buf[11+i-6]),"-----\n",6) != 0)
679                                 continue;
680                         if (!BUF_MEM_grow(nameB,i+9))
681                                 {
682                                 PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE);
683                                 goto err;
684                                 }
685                         memcpy(nameB->data,&(buf[11]),i-6);
686                         nameB->data[i-6]='\0';
687                         break;
688                         }
689                 }
690         hl=0;
691         if (!BUF_MEM_grow(headerB,256))
692                 { PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE); goto err; }
693         headerB->data[0]='\0';
694         for (;;)
695                 {
696                 i=BIO_gets(bp,buf,254);
697                 if (i <= 0) break;
698
699                 while ((i >= 0) && (buf[i] <= ' ')) i--;
700                 buf[++i]='\n'; buf[++i]='\0';
701
702                 if (buf[0] == '\n') break;
703                 if (!BUF_MEM_grow(headerB,hl+i+9))
704                         { PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE); goto err; }
705                 if (strncmp(buf,"-----END ",9) == 0)
706                         {
707                         nohead=1;
708                         break;
709                         }
710                 memcpy(&(headerB->data[hl]),buf,i);
711                 headerB->data[hl+i]='\0';
712                 hl+=i;
713                 }
714
715         bl=0;
716         if (!BUF_MEM_grow(dataB,1024))
717                 { PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE); goto err; }
718         dataB->data[0]='\0';
719         if (!nohead)
720                 {
721                 for (;;)
722                         {
723                         i=BIO_gets(bp,buf,254);
724                         if (i <= 0) break;
725
726                         while ((i >= 0) && (buf[i] <= ' ')) i--;
727                         buf[++i]='\n'; buf[++i]='\0';
728
729                         if (i != 65) end=1;
730                         if (strncmp(buf,"-----END ",9) == 0)
731                                 break;
732                         if (i > 65) break;
733                         if (!BUF_MEM_grow(dataB,i+bl+9))
734                                 {
735                                 PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE);
736                                 goto err;
737                                 }
738                         memcpy(&(dataB->data[bl]),buf,i);
739                         dataB->data[bl+i]='\0';
740                         bl+=i;
741                         if (end)
742                                 {
743                                 buf[0]='\0';
744                                 i=BIO_gets(bp,buf,254);
745                                 if (i <= 0) break;
746
747                                 while ((i >= 0) && (buf[i] <= ' ')) i--;
748                                 buf[++i]='\n'; buf[++i]='\0';
749
750                                 break;
751                                 }
752                         }
753                 }
754         else
755                 {
756                 tmpB=headerB;
757                 headerB=dataB;
758                 dataB=tmpB;
759                 bl=hl;
760                 }
761         i=strlen(nameB->data);
762         if (    (strncmp(buf,"-----END ",9) != 0) ||
763                 (strncmp(nameB->data,&(buf[9]),i) != 0) ||
764                 (strncmp(&(buf[9+i]),"-----\n",6) != 0))
765                 {
766                 PEMerr(PEM_F_PEM_READ_BIO,PEM_R_BAD_END_LINE);
767                 goto err;
768                 }
769
770         EVP_DecodeInit(&ctx);
771         i=EVP_DecodeUpdate(&ctx,
772                 (unsigned char *)dataB->data,&bl,
773                 (unsigned char *)dataB->data,bl);
774         if (i < 0)
775                 {
776                 PEMerr(PEM_F_PEM_READ_BIO,PEM_R_BAD_BASE64_DECODE);
777                 goto err;
778                 }
779         i=EVP_DecodeFinal(&ctx,(unsigned char *)&(dataB->data[bl]),&k);
780         if (i < 0)
781                 {
782                 PEMerr(PEM_F_PEM_READ_BIO,PEM_R_BAD_BASE64_DECODE);
783                 goto err;
784                 }
785         bl+=k;
786
787         if (bl == 0) goto err;
788         *name=nameB->data;
789         *header=headerB->data;
790         *data=(unsigned char *)dataB->data;
791         *len=bl;
792         Free(nameB);
793         Free(headerB);
794         Free(dataB);
795         return(1);
796 err:
797         BUF_MEM_free(nameB);
798         BUF_MEM_free(headerB);
799         BUF_MEM_free(dataB);
800         return(0);
801         }
802
803 /* These functions write a private key in PKCS#8 format: it is a "drop in"
804  * replacement for PEM_write_bio_PrivateKey() and friends. As usual if 'enc'
805  * is NULL then it uses the unencrypted private key form. The 'nid' versions
806  * uses PKCS#5 v1.5 PBE algorithms whereas the others use PKCS#5 v2.0.
807  */
808
809 int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, EVP_PKEY *x, int nid,
810                                   char *kstr, int klen,
811                                   pem_password_cb *cb, void *u)
812 {
813         return do_pk8pkey(bp, x, 0, nid, NULL, kstr, klen, cb, u);
814 }
815
816 int PEM_write_bio_PKCS8PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc,
817                                   char *kstr, int klen,
818                                   pem_password_cb *cb, void *u)
819 {
820         return do_pk8pkey(bp, x, 0, -1, enc, kstr, klen, cb, u);
821 }
822
823 int i2d_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc,
824                                   char *kstr, int klen,
825                                   pem_password_cb *cb, void *u)
826 {
827         return do_pk8pkey(bp, x, 1, -1, enc, kstr, klen, cb, u);
828 }
829
830 int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, EVP_PKEY *x, int nid,
831                                   char *kstr, int klen,
832                                   pem_password_cb *cb, void *u)
833 {
834         return do_pk8pkey(bp, x, 1, nid, NULL, kstr, klen, cb, u);
835 }
836
837 static int do_pk8pkey(BIO *bp, EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc,
838                                   char *kstr, int klen,
839                                   pem_password_cb *cb, void *u)
840 {
841         X509_SIG *p8;
842         PKCS8_PRIV_KEY_INFO *p8inf;
843         char buf[PEM_BUFSIZE];
844         int ret;
845         if(!(p8inf = EVP_PKEY2PKCS8(x))) {
846                 PEMerr(PEM_F_PEM_WRITE_BIO_PKCS8PRIVATEKEY,
847                                         PEM_R_ERROR_CONVERTING_PRIVATE_KEY);
848                 return 0;
849         }
850         if(enc || (nid != -1)) {
851                 if(!kstr) {
852                         if(!cb) klen = def_callback(buf, PEM_BUFSIZE, 1, u);
853                         else klen = cb(buf, PEM_BUFSIZE, 1, u);
854                         if(klen <= 0) {
855                                 PEMerr(PEM_F_PEM_WRITE_BIO_PKCS8PRIVATEKEY,
856                                                                 PEM_R_READ_KEY);
857                                 PKCS8_PRIV_KEY_INFO_free(p8inf);
858                                 return 0;
859                         }
860                                 
861                         kstr = buf;
862                 }
863                 p8 = PKCS8_encrypt(nid, enc, kstr, klen, NULL, 0, 0, p8inf);
864                 if(kstr == buf) memset(buf, 0, klen);
865                 PKCS8_PRIV_KEY_INFO_free(p8inf);
866                 if(isder) ret = i2d_PKCS8_bio(bp, p8);
867                 else ret = PEM_write_bio_PKCS8(bp, p8);
868                 X509_SIG_free(p8);
869                 return ret;
870         } else {
871                 if(isder) ret = i2d_PKCS8_PRIV_KEY_INFO_bio(bp, p8inf);
872                 else ret = PEM_write_bio_PKCS8_PRIV_KEY_INFO(bp, p8inf);
873                 PKCS8_PRIV_KEY_INFO_free(p8inf);
874                 return ret;
875         }
876 }
877
878 /* Finally the DER version to read PKCS#8 encrypted private keys. It has to be
879  * here to access the default callback.
880  */
881
882 EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u)
883 {
884         PKCS8_PRIV_KEY_INFO *p8inf = NULL;
885         X509_SIG *p8 = NULL;
886         int klen;
887         EVP_PKEY *ret;
888         char psbuf[PEM_BUFSIZE];
889         p8 = d2i_PKCS8_bio(bp, NULL);
890         if(!p8) return NULL;
891         if (cb) klen=cb(psbuf,PEM_BUFSIZE,0,u);
892         else klen=def_callback(psbuf,PEM_BUFSIZE,0,u);
893         if (klen <= 0) {
894                 PEMerr(PEM_F_D2I_PKCS8PRIVATEKEY_BIO, PEM_R_BAD_PASSWORD_READ);
895                 X509_SIG_free(p8);
896                 return NULL;    
897         }
898         p8inf = M_PKCS8_decrypt(p8, psbuf, klen);
899         X509_SIG_free(p8);
900         if(!p8inf) return NULL;
901         ret = EVP_PKCS82PKEY(p8inf);
902         PKCS8_PRIV_KEY_INFO_free(p8inf);
903         if(!ret) return NULL;
904         if(x) {
905                 if(*x) EVP_PKEY_free(*x);
906                 *x = ret;
907         }
908         return ret;
909 }
910
911 #ifndef NO_FP_API
912
913 int i2d_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
914                                   char *kstr, int klen,
915                                   pem_password_cb *cb, void *u)
916 {
917         return do_pk8pkey_fp(fp, x, 1, -1, enc, kstr, klen, cb, u);
918 }
919
920 int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, EVP_PKEY *x, int nid,
921                                   char *kstr, int klen,
922                                   pem_password_cb *cb, void *u)
923 {
924         return do_pk8pkey_fp(fp, x, 1, nid, NULL, kstr, klen, cb, u);
925 }
926
927 int PEM_write_PKCS8PrivateKey_nid(FILE *fp, EVP_PKEY *x, int nid,
928                                   char *kstr, int klen,
929                                   pem_password_cb *cb, void *u)
930 {
931         return do_pk8pkey_fp(fp, x, 0, nid, NULL, kstr, klen, cb, u);
932 }
933
934 int PEM_write_PKCS8PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
935                               char *kstr, int klen, pem_password_cb *cb, void *u)
936 {
937         return do_pk8pkey_fp(fp, x, 0, -1, enc, kstr, klen, cb, u);
938 }
939
940 static int do_pk8pkey_fp(FILE *fp, EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc,
941                                   char *kstr, int klen,
942                                   pem_password_cb *cb, void *u)
943 {
944         BIO *bp;
945         int ret;
946         if(!(bp = BIO_new_fp(fp, BIO_NOCLOSE))) {
947                 PEMerr(PEM_F_PEM_F_DO_PK8KEY_FP,ERR_R_BUF_LIB);
948                 return(0);
949         }
950         ret = do_pk8pkey(bp, x, isder, nid, enc, kstr, klen, cb, u);
951         BIO_free(bp);
952         return ret;
953 }
954
955 EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u)
956 {
957         BIO *bp;
958         EVP_PKEY *ret;
959         if(!(bp = BIO_new_fp(fp, BIO_NOCLOSE))) {
960                 PEMerr(PEM_F_D2I_PKCS8PRIVATEKEY_FP,ERR_R_BUF_LIB);
961                 return NULL;
962         }
963         ret = d2i_PKCS8PrivateKey_bio(bp, x, cb, u);
964         BIO_free(bp);
965         return ret;
966 }
967
968 #endif