2
0

pem_lib.c 19 KB

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