pem_lib.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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. #include <stdio.h>
  59. #include "cryptlib.h"
  60. #include <openssl/buffer.h>
  61. #include <openssl/objects.h>
  62. #include <openssl/evp.h>
  63. #include <openssl/rand.h>
  64. #include <openssl/x509.h>
  65. #include <openssl/pem.h>
  66. #include <openssl/pkcs12.h>
  67. #ifndef OPENSSL_NO_DES
  68. #include <openssl/des.h>
  69. #endif
  70. const char *PEM_version="PEM" OPENSSL_VERSION_PTEXT;
  71. #define MIN_LENGTH 4
  72. static int load_iv(unsigned char **fromp,unsigned char *to, int num);
  73. static int check_pem(const char *nm, const char *name);
  74. int PEM_def_callback(char *buf, int num, int w, void *key)
  75. {
  76. #ifdef OPENSSL_NO_FP_API
  77. /* We should not ever call the default callback routine from
  78. * windows. */
  79. PEMerr(PEM_F_DEF_CALLBACK,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  80. return(-1);
  81. #else
  82. int i,j;
  83. const char *prompt;
  84. if(key) {
  85. i=strlen(key);
  86. i=(i > num)?num:i;
  87. memcpy(buf,key,i);
  88. return(i);
  89. }
  90. prompt=EVP_get_pw_prompt();
  91. if (prompt == NULL)
  92. prompt="Enter PEM pass phrase:";
  93. for (;;)
  94. {
  95. i=EVP_read_pw_string(buf,num,prompt,w);
  96. if (i != 0)
  97. {
  98. PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
  99. memset(buf,0,(unsigned int)num);
  100. return(-1);
  101. }
  102. j=strlen(buf);
  103. if (j < MIN_LENGTH)
  104. {
  105. fprintf(stderr,"phrase is too short, needs to be at least %d chars\n",MIN_LENGTH);
  106. }
  107. else
  108. break;
  109. }
  110. return(j);
  111. #endif
  112. }
  113. void PEM_proc_type(char *buf, int type)
  114. {
  115. const char *str;
  116. if (type == PEM_TYPE_ENCRYPTED)
  117. str="ENCRYPTED";
  118. else if (type == PEM_TYPE_MIC_CLEAR)
  119. str="MIC-CLEAR";
  120. else if (type == PEM_TYPE_MIC_ONLY)
  121. str="MIC-ONLY";
  122. else
  123. str="BAD-TYPE";
  124. strcat(buf,"Proc-Type: 4,");
  125. strcat(buf,str);
  126. strcat(buf,"\n");
  127. }
  128. void PEM_dek_info(char *buf, const char *type, int len, char *str)
  129. {
  130. static const unsigned char map[17]="0123456789ABCDEF";
  131. long i;
  132. int j;
  133. strcat(buf,"DEK-Info: ");
  134. strcat(buf,type);
  135. strcat(buf,",");
  136. j=strlen(buf);
  137. for (i=0; i<len; i++)
  138. {
  139. buf[j+i*2] =map[(str[i]>>4)&0x0f];
  140. buf[j+i*2+1]=map[(str[i] )&0x0f];
  141. }
  142. buf[j+i*2]='\n';
  143. buf[j+i*2+1]='\0';
  144. }
  145. #ifndef OPENSSL_NO_FP_API
  146. char *PEM_ASN1_read(char *(*d2i)(), const char *name, FILE *fp, char **x,
  147. pem_password_cb *cb, void *u)
  148. {
  149. BIO *b;
  150. char *ret;
  151. if ((b=BIO_new(BIO_s_file())) == NULL)
  152. {
  153. PEMerr(PEM_F_PEM_ASN1_READ,ERR_R_BUF_LIB);
  154. return(0);
  155. }
  156. BIO_set_fp(b,fp,BIO_NOCLOSE);
  157. ret=PEM_ASN1_read_bio(d2i,name,b,x,cb,u);
  158. BIO_free(b);
  159. return(ret);
  160. }
  161. #endif
  162. static int check_pem(const char *nm, const char *name)
  163. {
  164. /* Normal matching nm and name */
  165. if (!strcmp(nm,name)) return 1;
  166. /* Make PEM_STRING_EVP_PKEY match any private key */
  167. if(!strcmp(nm,PEM_STRING_PKCS8) &&
  168. !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
  169. if(!strcmp(nm,PEM_STRING_PKCS8INF) &&
  170. !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
  171. if(!strcmp(nm,PEM_STRING_RSA) &&
  172. !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
  173. if(!strcmp(nm,PEM_STRING_DSA) &&
  174. !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
  175. if(!strcmp(nm,PEM_STRING_ECPRIVATEKEY) &&
  176. !strcmp(name,PEM_STRING_EVP_PKEY)) return 1;
  177. /* Permit older strings */
  178. if(!strcmp(nm,PEM_STRING_X509_OLD) &&
  179. !strcmp(name,PEM_STRING_X509)) return 1;
  180. if(!strcmp(nm,PEM_STRING_X509_REQ_OLD) &&
  181. !strcmp(name,PEM_STRING_X509_REQ)) return 1;
  182. /* Allow normal certs to be read as trusted certs */
  183. if(!strcmp(nm,PEM_STRING_X509) &&
  184. !strcmp(name,PEM_STRING_X509_TRUSTED)) return 1;
  185. if(!strcmp(nm,PEM_STRING_X509_OLD) &&
  186. !strcmp(name,PEM_STRING_X509_TRUSTED)) return 1;
  187. /* Some CAs use PKCS#7 with CERTIFICATE headers */
  188. if(!strcmp(nm, PEM_STRING_X509) &&
  189. !strcmp(name, PEM_STRING_PKCS7)) return 1;
  190. return 0;
  191. }
  192. int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm, const char *name, BIO *bp,
  193. pem_password_cb *cb, void *u)
  194. {
  195. EVP_CIPHER_INFO cipher;
  196. char *nm=NULL,*header=NULL;
  197. unsigned char *data=NULL;
  198. long len;
  199. int ret = 0;
  200. for (;;)
  201. {
  202. if (!PEM_read_bio(bp,&nm,&header,&data,&len)) {
  203. if(ERR_GET_REASON(ERR_peek_error()) ==
  204. PEM_R_NO_START_LINE)
  205. ERR_add_error_data(2, "Expecting: ", name);
  206. return 0;
  207. }
  208. if(check_pem(nm, name)) break;
  209. OPENSSL_free(nm);
  210. OPENSSL_free(header);
  211. OPENSSL_free(data);
  212. }
  213. if (!PEM_get_EVP_CIPHER_INFO(header,&cipher)) goto err;
  214. if (!PEM_do_header(&cipher,data,&len,cb,u)) goto err;
  215. *pdata = data;
  216. *plen = len;
  217. if (pnm)
  218. *pnm = nm;
  219. ret = 1;
  220. err:
  221. if (!ret || !pnm) OPENSSL_free(nm);
  222. OPENSSL_free(header);
  223. if (!ret) OPENSSL_free(data);
  224. return ret;
  225. }
  226. #ifndef OPENSSL_NO_FP_API
  227. int PEM_ASN1_write(int (*i2d)(), const char *name, FILE *fp, char *x,
  228. const EVP_CIPHER *enc, unsigned char *kstr, int klen,
  229. pem_password_cb *callback, void *u)
  230. {
  231. BIO *b;
  232. int ret;
  233. if ((b=BIO_new(BIO_s_file())) == NULL)
  234. {
  235. PEMerr(PEM_F_PEM_ASN1_WRITE,ERR_R_BUF_LIB);
  236. return(0);
  237. }
  238. BIO_set_fp(b,fp,BIO_NOCLOSE);
  239. ret=PEM_ASN1_write_bio(i2d,name,b,x,enc,kstr,klen,callback,u);
  240. BIO_free(b);
  241. return(ret);
  242. }
  243. #endif
  244. int PEM_ASN1_write_bio(int (*i2d)(), const char *name, BIO *bp, char *x,
  245. const EVP_CIPHER *enc, unsigned char *kstr, int klen,
  246. pem_password_cb *callback, void *u)
  247. {
  248. EVP_CIPHER_CTX ctx;
  249. int dsize=0,i,j,ret=0;
  250. unsigned char *p,*data=NULL;
  251. const char *objstr=NULL;
  252. char buf[PEM_BUFSIZE];
  253. unsigned char key[EVP_MAX_KEY_LENGTH];
  254. unsigned char iv[EVP_MAX_IV_LENGTH];
  255. if (enc != NULL)
  256. {
  257. objstr=OBJ_nid2sn(EVP_CIPHER_nid(enc));
  258. if (objstr == NULL)
  259. {
  260. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,PEM_R_UNSUPPORTED_CIPHER);
  261. goto err;
  262. }
  263. }
  264. if ((dsize=i2d(x,NULL)) < 0)
  265. {
  266. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,ERR_R_MALLOC_FAILURE);
  267. dsize=0;
  268. goto err;
  269. }
  270. /* dzise + 8 bytes are needed */
  271. /* actually it needs the cipher block size extra... */
  272. data=(unsigned char *)OPENSSL_malloc((unsigned int)dsize+20);
  273. if (data == NULL)
  274. {
  275. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,ERR_R_MALLOC_FAILURE);
  276. goto err;
  277. }
  278. p=data;
  279. i=i2d(x,&p);
  280. if (enc != NULL)
  281. {
  282. if (kstr == NULL)
  283. {
  284. if (callback == NULL)
  285. klen=PEM_def_callback(buf,PEM_BUFSIZE,1,u);
  286. else
  287. klen=(*callback)(buf,PEM_BUFSIZE,1,u);
  288. if (klen <= 0)
  289. {
  290. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,PEM_R_READ_KEY);
  291. goto err;
  292. }
  293. #ifdef CHARSET_EBCDIC
  294. /* Convert the pass phrase from EBCDIC */
  295. ebcdic2ascii(buf, buf, klen);
  296. #endif
  297. kstr=(unsigned char *)buf;
  298. }
  299. RAND_add(data,i,0);/* put in the RSA key. */
  300. OPENSSL_assert(enc->iv_len <= sizeof iv);
  301. if (RAND_pseudo_bytes(iv,enc->iv_len) < 0) /* Generate a salt */
  302. goto err;
  303. /* The 'iv' is used as the iv and as a salt. It is
  304. * NOT taken from the BytesToKey function */
  305. EVP_BytesToKey(enc,EVP_md5(),iv,kstr,klen,1,key,NULL);
  306. if (kstr == (unsigned char *)buf) memset(buf,0,PEM_BUFSIZE);
  307. OPENSSL_assert(strlen(objstr)+23+2*enc->iv_len+13 <= sizeof buf);
  308. buf[0]='\0';
  309. PEM_proc_type(buf,PEM_TYPE_ENCRYPTED);
  310. PEM_dek_info(buf,objstr,enc->iv_len,(char *)iv);
  311. /* k=strlen(buf); */
  312. EVP_CIPHER_CTX_init(&ctx);
  313. EVP_EncryptInit_ex(&ctx,enc,NULL,key,iv);
  314. EVP_EncryptUpdate(&ctx,data,&j,data,i);
  315. EVP_EncryptFinal_ex(&ctx,&(data[j]),&i);
  316. EVP_CIPHER_CTX_cleanup(&ctx);
  317. i+=j;
  318. ret=1;
  319. }
  320. else
  321. {
  322. ret=1;
  323. buf[0]='\0';
  324. }
  325. i=PEM_write_bio(bp,name,buf,data,i);
  326. if (i <= 0) ret=0;
  327. err:
  328. OPENSSL_cleanse(key,sizeof(key));
  329. OPENSSL_cleanse(iv,sizeof(iv));
  330. OPENSSL_cleanse((char *)&ctx,sizeof(ctx));
  331. OPENSSL_cleanse(buf,PEM_BUFSIZE);
  332. if (data != NULL)
  333. {
  334. OPENSSL_cleanse(data,(unsigned int)dsize);
  335. OPENSSL_free(data);
  336. }
  337. return(ret);
  338. }
  339. int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
  340. pem_password_cb *callback,void *u)
  341. {
  342. int i,j,o,klen;
  343. long len;
  344. EVP_CIPHER_CTX ctx;
  345. unsigned char key[EVP_MAX_KEY_LENGTH];
  346. char buf[PEM_BUFSIZE];
  347. len= *plen;
  348. if (cipher->cipher == NULL) return(1);
  349. if (callback == NULL)
  350. klen=PEM_def_callback(buf,PEM_BUFSIZE,0,u);
  351. else
  352. klen=callback(buf,PEM_BUFSIZE,0,u);
  353. if (klen <= 0)
  354. {
  355. PEMerr(PEM_F_PEM_DO_HEADER,PEM_R_BAD_PASSWORD_READ);
  356. return(0);
  357. }
  358. #ifdef CHARSET_EBCDIC
  359. /* Convert the pass phrase from EBCDIC */
  360. ebcdic2ascii(buf, buf, klen);
  361. #endif
  362. EVP_BytesToKey(cipher->cipher,EVP_md5(),&(cipher->iv[0]),
  363. (unsigned char *)buf,klen,1,key,NULL);
  364. j=(int)len;
  365. EVP_CIPHER_CTX_init(&ctx);
  366. EVP_DecryptInit_ex(&ctx,cipher->cipher,NULL, key,&(cipher->iv[0]));
  367. EVP_DecryptUpdate(&ctx,data,&i,data,j);
  368. o=EVP_DecryptFinal_ex(&ctx,&(data[i]),&j);
  369. EVP_CIPHER_CTX_cleanup(&ctx);
  370. OPENSSL_cleanse((char *)buf,sizeof(buf));
  371. OPENSSL_cleanse((char *)key,sizeof(key));
  372. j+=i;
  373. if (!o)
  374. {
  375. PEMerr(PEM_F_PEM_DO_HEADER,PEM_R_BAD_DECRYPT);
  376. return(0);
  377. }
  378. *plen=j;
  379. return(1);
  380. }
  381. int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
  382. {
  383. int o;
  384. const EVP_CIPHER *enc=NULL;
  385. char *p,c;
  386. cipher->cipher=NULL;
  387. if ((header == NULL) || (*header == '\0') || (*header == '\n'))
  388. return(1);
  389. if (strncmp(header,"Proc-Type: ",11) != 0)
  390. { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_NOT_PROC_TYPE); return(0); }
  391. header+=11;
  392. if (*header != '4') return(0); header++;
  393. if (*header != ',') return(0); header++;
  394. if (strncmp(header,"ENCRYPTED",9) != 0)
  395. { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_NOT_ENCRYPTED); return(0); }
  396. for (; (*header != '\n') && (*header != '\0'); header++)
  397. ;
  398. if (*header == '\0')
  399. { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_SHORT_HEADER); return(0); }
  400. header++;
  401. if (strncmp(header,"DEK-Info: ",10) != 0)
  402. { PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_NOT_DEK_INFO); return(0); }
  403. header+=10;
  404. p=header;
  405. for (;;)
  406. {
  407. c= *header;
  408. #ifndef CHARSET_EBCDIC
  409. if (!( ((c >= 'A') && (c <= 'Z')) || (c == '-') ||
  410. ((c >= '0') && (c <= '9'))))
  411. break;
  412. #else
  413. if (!( isupper(c) || (c == '-') ||
  414. isdigit(c)))
  415. break;
  416. #endif
  417. header++;
  418. }
  419. *header='\0';
  420. o=OBJ_sn2nid(p);
  421. cipher->cipher=enc=EVP_get_cipherbyname(p);
  422. *header=c;
  423. header++;
  424. if (enc == NULL)
  425. {
  426. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,PEM_R_UNSUPPORTED_ENCRYPTION);
  427. return(0);
  428. }
  429. if (!load_iv((unsigned char **)&header,&(cipher->iv[0]),enc->iv_len)) return(0);
  430. return(1);
  431. }
  432. static int load_iv(unsigned char **fromp, unsigned char *to, int num)
  433. {
  434. int v,i;
  435. unsigned char *from;
  436. from= *fromp;
  437. for (i=0; i<num; i++) to[i]=0;
  438. num*=2;
  439. for (i=0; i<num; i++)
  440. {
  441. if ((*from >= '0') && (*from <= '9'))
  442. v= *from-'0';
  443. else if ((*from >= 'A') && (*from <= 'F'))
  444. v= *from-'A'+10;
  445. else if ((*from >= 'a') && (*from <= 'f'))
  446. v= *from-'a'+10;
  447. else
  448. {
  449. PEMerr(PEM_F_LOAD_IV,PEM_R_BAD_IV_CHARS);
  450. return(0);
  451. }
  452. from++;
  453. to[i/2]|=v<<(long)((!(i&1))*4);
  454. }
  455. *fromp=from;
  456. return(1);
  457. }
  458. #ifndef OPENSSL_NO_FP_API
  459. int PEM_write(FILE *fp, char *name, char *header, unsigned char *data,
  460. long len)
  461. {
  462. BIO *b;
  463. int ret;
  464. if ((b=BIO_new(BIO_s_file())) == NULL)
  465. {
  466. PEMerr(PEM_F_PEM_WRITE,ERR_R_BUF_LIB);
  467. return(0);
  468. }
  469. BIO_set_fp(b,fp,BIO_NOCLOSE);
  470. ret=PEM_write_bio(b, name, header, data,len);
  471. BIO_free(b);
  472. return(ret);
  473. }
  474. #endif
  475. int PEM_write_bio(BIO *bp, const char *name, char *header, unsigned char *data,
  476. long len)
  477. {
  478. int nlen,n,i,j,outl;
  479. unsigned char *buf;
  480. EVP_ENCODE_CTX ctx;
  481. int reason=ERR_R_BUF_LIB;
  482. EVP_EncodeInit(&ctx);
  483. nlen=strlen(name);
  484. if ( (BIO_write(bp,"-----BEGIN ",11) != 11) ||
  485. (BIO_write(bp,name,nlen) != nlen) ||
  486. (BIO_write(bp,"-----\n",6) != 6))
  487. goto err;
  488. i=strlen(header);
  489. if (i > 0)
  490. {
  491. if ( (BIO_write(bp,header,i) != i) ||
  492. (BIO_write(bp,"\n",1) != 1))
  493. goto err;
  494. }
  495. buf=(unsigned char *)OPENSSL_malloc(PEM_BUFSIZE*8);
  496. if (buf == NULL)
  497. {
  498. reason=ERR_R_MALLOC_FAILURE;
  499. goto err;
  500. }
  501. i=j=0;
  502. while (len > 0)
  503. {
  504. n=(int)((len>(PEM_BUFSIZE*5))?(PEM_BUFSIZE*5):len);
  505. EVP_EncodeUpdate(&ctx,buf,&outl,&(data[j]),n);
  506. if ((outl) && (BIO_write(bp,(char *)buf,outl) != outl))
  507. goto err;
  508. i+=outl;
  509. len-=n;
  510. j+=n;
  511. }
  512. EVP_EncodeFinal(&ctx,buf,&outl);
  513. if ((outl > 0) && (BIO_write(bp,(char *)buf,outl) != outl)) goto err;
  514. OPENSSL_free(buf);
  515. if ( (BIO_write(bp,"-----END ",9) != 9) ||
  516. (BIO_write(bp,name,nlen) != nlen) ||
  517. (BIO_write(bp,"-----\n",6) != 6))
  518. goto err;
  519. return(i+outl);
  520. err:
  521. PEMerr(PEM_F_PEM_WRITE_BIO,reason);
  522. return(0);
  523. }
  524. #ifndef OPENSSL_NO_FP_API
  525. int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
  526. long *len)
  527. {
  528. BIO *b;
  529. int ret;
  530. if ((b=BIO_new(BIO_s_file())) == NULL)
  531. {
  532. PEMerr(PEM_F_PEM_READ,ERR_R_BUF_LIB);
  533. return(0);
  534. }
  535. BIO_set_fp(b,fp,BIO_NOCLOSE);
  536. ret=PEM_read_bio(b, name, header, data,len);
  537. BIO_free(b);
  538. return(ret);
  539. }
  540. #endif
  541. int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
  542. long *len)
  543. {
  544. EVP_ENCODE_CTX ctx;
  545. int end=0,i,k,bl=0,hl=0,nohead=0;
  546. char buf[256];
  547. BUF_MEM *nameB;
  548. BUF_MEM *headerB;
  549. BUF_MEM *dataB,*tmpB;
  550. nameB=BUF_MEM_new();
  551. headerB=BUF_MEM_new();
  552. dataB=BUF_MEM_new();
  553. if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL))
  554. {
  555. PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE);
  556. return(0);
  557. }
  558. buf[254]='\0';
  559. for (;;)
  560. {
  561. i=BIO_gets(bp,buf,254);
  562. if (i <= 0)
  563. {
  564. PEMerr(PEM_F_PEM_READ_BIO,PEM_R_NO_START_LINE);
  565. goto err;
  566. }
  567. while ((i >= 0) && (buf[i] <= ' ')) i--;
  568. buf[++i]='\n'; buf[++i]='\0';
  569. if (strncmp(buf,"-----BEGIN ",11) == 0)
  570. {
  571. i=strlen(&(buf[11]));
  572. if (strncmp(&(buf[11+i-6]),"-----\n",6) != 0)
  573. continue;
  574. if (!BUF_MEM_grow(nameB,i+9))
  575. {
  576. PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE);
  577. goto err;
  578. }
  579. memcpy(nameB->data,&(buf[11]),i-6);
  580. nameB->data[i-6]='\0';
  581. break;
  582. }
  583. }
  584. hl=0;
  585. if (!BUF_MEM_grow(headerB,256))
  586. { PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE); goto err; }
  587. headerB->data[0]='\0';
  588. for (;;)
  589. {
  590. i=BIO_gets(bp,buf,254);
  591. if (i <= 0) break;
  592. while ((i >= 0) && (buf[i] <= ' ')) i--;
  593. buf[++i]='\n'; buf[++i]='\0';
  594. if (buf[0] == '\n') break;
  595. if (!BUF_MEM_grow(headerB,hl+i+9))
  596. { PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE); goto err; }
  597. if (strncmp(buf,"-----END ",9) == 0)
  598. {
  599. nohead=1;
  600. break;
  601. }
  602. memcpy(&(headerB->data[hl]),buf,i);
  603. headerB->data[hl+i]='\0';
  604. hl+=i;
  605. }
  606. bl=0;
  607. if (!BUF_MEM_grow(dataB,1024))
  608. { PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE); goto err; }
  609. dataB->data[0]='\0';
  610. if (!nohead)
  611. {
  612. for (;;)
  613. {
  614. i=BIO_gets(bp,buf,254);
  615. if (i <= 0) break;
  616. while ((i >= 0) && (buf[i] <= ' ')) i--;
  617. buf[++i]='\n'; buf[++i]='\0';
  618. if (i != 65) end=1;
  619. if (strncmp(buf,"-----END ",9) == 0)
  620. break;
  621. if (i > 65) break;
  622. if (!BUF_MEM_grow_clean(dataB,i+bl+9))
  623. {
  624. PEMerr(PEM_F_PEM_READ_BIO,ERR_R_MALLOC_FAILURE);
  625. goto err;
  626. }
  627. memcpy(&(dataB->data[bl]),buf,i);
  628. dataB->data[bl+i]='\0';
  629. bl+=i;
  630. if (end)
  631. {
  632. buf[0]='\0';
  633. i=BIO_gets(bp,buf,254);
  634. if (i <= 0) break;
  635. while ((i >= 0) && (buf[i] <= ' ')) i--;
  636. buf[++i]='\n'; buf[++i]='\0';
  637. break;
  638. }
  639. }
  640. }
  641. else
  642. {
  643. tmpB=headerB;
  644. headerB=dataB;
  645. dataB=tmpB;
  646. bl=hl;
  647. }
  648. i=strlen(nameB->data);
  649. if ( (strncmp(buf,"-----END ",9) != 0) ||
  650. (strncmp(nameB->data,&(buf[9]),i) != 0) ||
  651. (strncmp(&(buf[9+i]),"-----\n",6) != 0))
  652. {
  653. PEMerr(PEM_F_PEM_READ_BIO,PEM_R_BAD_END_LINE);
  654. goto err;
  655. }
  656. EVP_DecodeInit(&ctx);
  657. i=EVP_DecodeUpdate(&ctx,
  658. (unsigned char *)dataB->data,&bl,
  659. (unsigned char *)dataB->data,bl);
  660. if (i < 0)
  661. {
  662. PEMerr(PEM_F_PEM_READ_BIO,PEM_R_BAD_BASE64_DECODE);
  663. goto err;
  664. }
  665. i=EVP_DecodeFinal(&ctx,(unsigned char *)&(dataB->data[bl]),&k);
  666. if (i < 0)
  667. {
  668. PEMerr(PEM_F_PEM_READ_BIO,PEM_R_BAD_BASE64_DECODE);
  669. goto err;
  670. }
  671. bl+=k;
  672. if (bl == 0) goto err;
  673. *name=nameB->data;
  674. *header=headerB->data;
  675. *data=(unsigned char *)dataB->data;
  676. *len=bl;
  677. OPENSSL_free(nameB);
  678. OPENSSL_free(headerB);
  679. OPENSSL_free(dataB);
  680. return(1);
  681. err:
  682. BUF_MEM_free(nameB);
  683. BUF_MEM_free(headerB);
  684. BUF_MEM_free(dataB);
  685. return(0);
  686. }