pem_lib.c 20 KB

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