pem_lib.c 19 KB

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