crypto_rsa.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. /* Copyright (c) 2001, Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2019, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file crypto_rsa.c
  8. * \brief Block of functions related with RSA utilities and operations.
  9. **/
  10. #include "lib/crypt_ops/crypto_cipher.h"
  11. #include "lib/crypt_ops/crypto_curve25519.h"
  12. #include "lib/crypt_ops/crypto_digest.h"
  13. #include "lib/crypt_ops/crypto_format.h"
  14. #include "lib/crypt_ops/compat_openssl.h"
  15. #include "lib/crypt_ops/crypto_rand.h"
  16. #include "lib/crypt_ops/crypto_rsa.h"
  17. #include "lib/crypt_ops/crypto_util.h"
  18. #include "lib/ctime/di_ops.h"
  19. #include "lib/log/util_bug.h"
  20. #include "lib/fs/files.h"
  21. #include "lib/log/escape.h"
  22. #include "lib/log/log.h"
  23. #include "lib/encoding/binascii.h"
  24. #include "lib/encoding/pem.h"
  25. #include <string.h>
  26. #ifdef HAVE_SYS_STAT_H
  27. #include <sys/stat.h>
  28. #endif
  29. /** Return the number of bytes added by padding method <b>padding</b>.
  30. */
  31. int
  32. crypto_get_rsa_padding_overhead(int padding)
  33. {
  34. switch (padding)
  35. {
  36. case PK_PKCS1_OAEP_PADDING: return PKCS1_OAEP_PADDING_OVERHEAD;
  37. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  38. }
  39. }
  40. #ifdef ENABLE_OPENSSL
  41. /** Given a padding method <b>padding</b>, return the correct OpenSSL constant.
  42. */
  43. int
  44. crypto_get_rsa_padding(int padding)
  45. {
  46. switch (padding)
  47. {
  48. case PK_PKCS1_OAEP_PADDING: return RSA_PKCS1_OAEP_PADDING;
  49. default: tor_assert(0); return -1; // LCOV_EXCL_LINE
  50. }
  51. }
  52. #endif
  53. /** Compare the public-key components of a and b. Return non-zero iff
  54. * a==b. A NULL key is considered to be distinct from all non-NULL
  55. * keys, and equal to itself.
  56. *
  57. * Note that this may leak information about the keys through timing.
  58. */
  59. int
  60. crypto_pk_eq_keys(const crypto_pk_t *a, const crypto_pk_t *b)
  61. {
  62. return (crypto_pk_cmp_keys(a, b) == 0);
  63. }
  64. /** Perform a hybrid (public/secret) encryption on <b>fromlen</b>
  65. * bytes of data from <b>from</b>, with padding type 'padding',
  66. * storing the results on <b>to</b>.
  67. *
  68. * Returns the number of bytes written on success, -1 on failure.
  69. *
  70. * The encrypted data consists of:
  71. * - The source data, padded and encrypted with the public key, if the
  72. * padded source data is no longer than the public key, and <b>force</b>
  73. * is false, OR
  74. * - The beginning of the source data prefixed with a 16-byte symmetric key,
  75. * padded and encrypted with the public key; followed by the rest of
  76. * the source data encrypted in AES-CTR mode with the symmetric key.
  77. *
  78. * NOTE that this format does not authenticate the symmetrically encrypted
  79. * part of the data, and SHOULD NOT BE USED for new protocols.
  80. */
  81. int
  82. crypto_pk_obsolete_public_hybrid_encrypt(crypto_pk_t *env,
  83. char *to, size_t tolen,
  84. const char *from,
  85. size_t fromlen,
  86. int padding, int force)
  87. {
  88. int overhead, outlen, r;
  89. size_t pkeylen, symlen;
  90. crypto_cipher_t *cipher = NULL;
  91. char *buf = NULL;
  92. tor_assert(env);
  93. tor_assert(from);
  94. tor_assert(to);
  95. tor_assert(fromlen < SIZE_T_CEILING);
  96. overhead = crypto_get_rsa_padding_overhead(padding);
  97. pkeylen = crypto_pk_keysize(env);
  98. if (!force && fromlen+overhead <= pkeylen) {
  99. /* It all fits in a single encrypt. */
  100. return crypto_pk_public_encrypt(env,to,
  101. tolen,
  102. from,fromlen,padding);
  103. }
  104. tor_assert(tolen >= fromlen + overhead + CIPHER_KEY_LEN);
  105. tor_assert(tolen >= pkeylen);
  106. char key[CIPHER_KEY_LEN];
  107. crypto_rand(key, sizeof(key)); /* generate a new key. */
  108. cipher = crypto_cipher_new(key);
  109. buf = tor_malloc(pkeylen+1);
  110. memcpy(buf, key, CIPHER_KEY_LEN);
  111. memcpy(buf+CIPHER_KEY_LEN, from, pkeylen-overhead-CIPHER_KEY_LEN);
  112. /* Length of symmetrically encrypted data. */
  113. symlen = fromlen-(pkeylen-overhead-CIPHER_KEY_LEN);
  114. outlen = crypto_pk_public_encrypt(env,to,tolen,buf,pkeylen-overhead,padding);
  115. if (outlen!=(int)pkeylen) {
  116. goto err;
  117. }
  118. r = crypto_cipher_encrypt(cipher, to+outlen,
  119. from+pkeylen-overhead-CIPHER_KEY_LEN, symlen);
  120. if (r<0) goto err;
  121. memwipe(buf, 0, pkeylen);
  122. memwipe(key, 0, sizeof(key));
  123. tor_free(buf);
  124. crypto_cipher_free(cipher);
  125. tor_assert(outlen+symlen < INT_MAX);
  126. return (int)(outlen + symlen);
  127. err:
  128. memwipe(buf, 0, pkeylen);
  129. memwipe(key, 0, sizeof(key));
  130. tor_free(buf);
  131. crypto_cipher_free(cipher);
  132. return -1;
  133. }
  134. /** Invert crypto_pk_obsolete_public_hybrid_encrypt. Returns the number of
  135. * bytes written on success, -1 on failure.
  136. *
  137. * NOTE that this format does not authenticate the symmetrically encrypted
  138. * part of the data, and SHOULD NOT BE USED for new protocols.
  139. */
  140. int
  141. crypto_pk_obsolete_private_hybrid_decrypt(crypto_pk_t *env,
  142. char *to,
  143. size_t tolen,
  144. const char *from,
  145. size_t fromlen,
  146. int padding, int warnOnFailure)
  147. {
  148. int outlen, r;
  149. size_t pkeylen;
  150. crypto_cipher_t *cipher = NULL;
  151. char *buf = NULL;
  152. tor_assert(fromlen < SIZE_T_CEILING);
  153. pkeylen = crypto_pk_keysize(env);
  154. if (fromlen <= pkeylen) {
  155. return crypto_pk_private_decrypt(env,to,tolen,from,fromlen,padding,
  156. warnOnFailure);
  157. }
  158. buf = tor_malloc(pkeylen);
  159. outlen = crypto_pk_private_decrypt(env,buf,pkeylen,from,pkeylen,padding,
  160. warnOnFailure);
  161. if (outlen<0) {
  162. log_fn(warnOnFailure?LOG_WARN:LOG_DEBUG, LD_CRYPTO,
  163. "Error decrypting public-key data");
  164. goto err;
  165. }
  166. if (outlen < CIPHER_KEY_LEN) {
  167. log_fn(warnOnFailure?LOG_WARN:LOG_INFO, LD_CRYPTO,
  168. "No room for a symmetric key");
  169. goto err;
  170. }
  171. cipher = crypto_cipher_new(buf);
  172. if (!cipher) {
  173. goto err;
  174. }
  175. memcpy(to,buf+CIPHER_KEY_LEN,outlen-CIPHER_KEY_LEN);
  176. outlen -= CIPHER_KEY_LEN;
  177. tor_assert(tolen - outlen >= fromlen - pkeylen);
  178. r = crypto_cipher_decrypt(cipher, to+outlen, from+pkeylen, fromlen-pkeylen);
  179. if (r<0)
  180. goto err;
  181. memwipe(buf,0,pkeylen);
  182. tor_free(buf);
  183. crypto_cipher_free(cipher);
  184. tor_assert(outlen + fromlen < INT_MAX);
  185. return (int)(outlen + (fromlen-pkeylen));
  186. err:
  187. memwipe(buf,0,pkeylen);
  188. tor_free(buf);
  189. crypto_cipher_free(cipher);
  190. return -1;
  191. }
  192. /** Given a private or public key <b>pk</b>, put a fingerprint of the
  193. * public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1 bytes of
  194. * space). Return 0 on success, -1 on failure.
  195. *
  196. * Fingerprints are computed as the SHA1 digest of the ASN.1 encoding
  197. * of the public key, converted to hexadecimal, in upper case, with a
  198. * space after every four digits.
  199. *
  200. * If <b>add_space</b> is false, omit the spaces.
  201. */
  202. int
  203. crypto_pk_get_fingerprint(crypto_pk_t *pk, char *fp_out, int add_space)
  204. {
  205. char digest[DIGEST_LEN];
  206. char hexdigest[HEX_DIGEST_LEN+1];
  207. if (crypto_pk_get_digest(pk, digest)) {
  208. return -1;
  209. }
  210. base16_encode(hexdigest,sizeof(hexdigest),digest,DIGEST_LEN);
  211. if (add_space) {
  212. crypto_add_spaces_to_fp(fp_out, FINGERPRINT_LEN+1, hexdigest);
  213. } else {
  214. strncpy(fp_out, hexdigest, HEX_DIGEST_LEN+1);
  215. }
  216. return 0;
  217. }
  218. /** Given a private or public key <b>pk</b>, put a hashed fingerprint of
  219. * the public key into <b>fp_out</b> (must have at least FINGERPRINT_LEN+1
  220. * bytes of space). Return 0 on success, -1 on failure.
  221. *
  222. * Hashed fingerprints are computed as the SHA1 digest of the SHA1 digest
  223. * of the ASN.1 encoding of the public key, converted to hexadecimal, in
  224. * upper case.
  225. */
  226. int
  227. crypto_pk_get_hashed_fingerprint(crypto_pk_t *pk, char *fp_out)
  228. {
  229. char digest[DIGEST_LEN], hashed_digest[DIGEST_LEN];
  230. if (crypto_pk_get_digest(pk, digest)) {
  231. return -1;
  232. }
  233. if (crypto_digest(hashed_digest, digest, DIGEST_LEN) < 0) {
  234. return -1;
  235. }
  236. base16_encode(fp_out, FINGERPRINT_LEN + 1, hashed_digest, DIGEST_LEN);
  237. return 0;
  238. }
  239. /** Copy <b>in</b> to the <b>outlen</b>-byte buffer <b>out</b>, adding spaces
  240. * every four characters. */
  241. void
  242. crypto_add_spaces_to_fp(char *out, size_t outlen, const char *in)
  243. {
  244. int n = 0;
  245. char *end = out+outlen;
  246. tor_assert(outlen < SIZE_T_CEILING);
  247. while (*in && out<end) {
  248. *out++ = *in++;
  249. if (++n == 4 && *in && out<end) {
  250. n = 0;
  251. *out++ = ' ';
  252. }
  253. }
  254. tor_assert(out<end);
  255. *out = '\0';
  256. }
  257. /** Check a siglen-byte long signature at <b>sig</b> against
  258. * <b>datalen</b> bytes of data at <b>data</b>, using the public key
  259. * in <b>env</b>. Return 0 if <b>sig</b> is a correct signature for
  260. * SHA1(data). Else return -1.
  261. */
  262. MOCK_IMPL(int,
  263. crypto_pk_public_checksig_digest,(crypto_pk_t *env, const char *data,
  264. size_t datalen, const char *sig,
  265. size_t siglen))
  266. {
  267. char digest[DIGEST_LEN];
  268. char *buf;
  269. size_t buflen;
  270. int r;
  271. tor_assert(env);
  272. tor_assert(data);
  273. tor_assert(sig);
  274. tor_assert(datalen < SIZE_T_CEILING);
  275. tor_assert(siglen < SIZE_T_CEILING);
  276. if (crypto_digest(digest,data,datalen)<0) {
  277. log_warn(LD_BUG, "couldn't compute digest");
  278. return -1;
  279. }
  280. buflen = crypto_pk_keysize(env);
  281. buf = tor_malloc(buflen);
  282. r = crypto_pk_public_checksig(env,buf,buflen,sig,siglen);
  283. if (r != DIGEST_LEN) {
  284. log_warn(LD_CRYPTO, "Invalid signature");
  285. tor_free(buf);
  286. return -1;
  287. }
  288. if (tor_memneq(buf, digest, DIGEST_LEN)) {
  289. log_warn(LD_CRYPTO, "Signature mismatched with digest.");
  290. tor_free(buf);
  291. return -1;
  292. }
  293. tor_free(buf);
  294. return 0;
  295. }
  296. /** Compute a SHA1 digest of <b>fromlen</b> bytes of data stored at
  297. * <b>from</b>; sign the data with the private key in <b>env</b>, and
  298. * store it in <b>to</b>. Return the number of bytes written on
  299. * success, and -1 on failure.
  300. *
  301. * <b>tolen</b> is the number of writable bytes in <b>to</b>, and must be
  302. * at least the length of the modulus of <b>env</b>.
  303. */
  304. int
  305. crypto_pk_private_sign_digest(crypto_pk_t *env, char *to, size_t tolen,
  306. const char *from, size_t fromlen)
  307. {
  308. int r;
  309. char digest[DIGEST_LEN];
  310. if (crypto_digest(digest,from,fromlen)<0)
  311. return -1;
  312. r = crypto_pk_private_sign(env,to,tolen,digest,DIGEST_LEN);
  313. memwipe(digest, 0, sizeof(digest));
  314. return r;
  315. }
  316. /** Given a private or public key <b>pk</b>, put a SHA1 hash of the
  317. * public key into <b>digest_out</b> (must have DIGEST_LEN bytes of space).
  318. * Return 0 on success, -1 on failure.
  319. */
  320. int
  321. crypto_pk_get_digest(const crypto_pk_t *pk, char *digest_out)
  322. {
  323. char *buf;
  324. size_t buflen;
  325. int len;
  326. int rv = -1;
  327. buflen = crypto_pk_keysize(pk)*2;
  328. buf = tor_malloc(buflen);
  329. len = crypto_pk_asn1_encode(pk, buf, buflen);
  330. if (len < 0)
  331. goto done;
  332. if (crypto_digest(digest_out, buf, len) < 0)
  333. goto done;
  334. rv = 0;
  335. done:
  336. tor_free(buf);
  337. return rv;
  338. }
  339. /** Compute all digests of the DER encoding of <b>pk</b>, and store them
  340. * in <b>digests_out</b>. Return 0 on success, -1 on failure. */
  341. int
  342. crypto_pk_get_common_digests(crypto_pk_t *pk, common_digests_t *digests_out)
  343. {
  344. char *buf;
  345. size_t buflen;
  346. int len;
  347. int rv = -1;
  348. buflen = crypto_pk_keysize(pk)*2;
  349. buf = tor_malloc(buflen);
  350. len = crypto_pk_asn1_encode(pk, buf, buflen);
  351. if (len < 0)
  352. goto done;
  353. if (crypto_common_digests(digests_out, (char*)buf, len) < 0)
  354. goto done;
  355. rv = 0;
  356. done:
  357. tor_free(buf);
  358. return rv;
  359. }
  360. static const char RSA_PUBLIC_TAG[] = "RSA PUBLIC KEY";
  361. static const char RSA_PRIVATE_TAG[] = "RSA PRIVATE KEY";
  362. /* These are overestimates for how many extra bytes we might need to encode
  363. * a key in DER */
  364. #define PRIVATE_ASN_MAX_OVERHEAD_FACTOR 16
  365. #define PUBLIC_ASN_MAX_OVERHEAD_FACTOR 3
  366. /** Helper: PEM-encode <b>env</b> and write it to a newly allocated string.
  367. * If <b>private_key</b>, write the private part of <b>env</b>; otherwise
  368. * write only the public portion. On success, set *<b>dest</b> to the new
  369. * string, *<b>len</b> to the string's length, and return 0. On failure,
  370. * return -1.
  371. */
  372. static int
  373. crypto_pk_write_to_string_generic(crypto_pk_t *env,
  374. char **dest, size_t *len,
  375. bool private_key)
  376. {
  377. const int factor =
  378. private_key ? PRIVATE_ASN_MAX_OVERHEAD_FACTOR
  379. : PUBLIC_ASN_MAX_OVERHEAD_FACTOR;
  380. size_t buflen = crypto_pk_keysize(env) * factor;
  381. const char *tag =
  382. private_key ? RSA_PRIVATE_TAG : RSA_PUBLIC_TAG;
  383. char *buf = tor_malloc(buflen);
  384. char *result = NULL;
  385. size_t resultlen = 0;
  386. int rv = -1;
  387. int n = private_key
  388. ? crypto_pk_asn1_encode_private(env, buf, buflen)
  389. : crypto_pk_asn1_encode(env, buf, buflen);
  390. if (n < 0)
  391. goto done;
  392. resultlen = pem_encoded_size(n, tag);
  393. result = tor_malloc(resultlen);
  394. if (pem_encode(result, resultlen,
  395. (const unsigned char *)buf, n, tag) < 0) {
  396. goto done;
  397. }
  398. *dest = result;
  399. *len = resultlen;
  400. rv = 0;
  401. done:
  402. if (rv < 0 && result) {
  403. memwipe(result, 0, resultlen);
  404. tor_free(result);
  405. }
  406. memwipe(buf, 0, buflen);
  407. tor_free(buf);
  408. return rv;
  409. }
  410. /** PEM-encode the public key portion of <b>env</b> and write it to a
  411. * newly allocated string. On success, set *<b>dest</b> to the new
  412. * string, *<b>len</b> to the string's length, and return 0. On
  413. * failure, return -1.
  414. */
  415. int
  416. crypto_pk_write_public_key_to_string(crypto_pk_t *env,
  417. char **dest, size_t *len)
  418. {
  419. return crypto_pk_write_to_string_generic(env, dest, len, false);
  420. }
  421. /** PEM-encode the private key portion of <b>env</b> and write it to a
  422. * newly allocated string. On success, set *<b>dest</b> to the new
  423. * string, *<b>len</b> to the string's length, and return 0. On
  424. * failure, return -1.
  425. */
  426. int
  427. crypto_pk_write_private_key_to_string(crypto_pk_t *env,
  428. char **dest, size_t *len)
  429. {
  430. return crypto_pk_write_to_string_generic(env, dest, len, true);
  431. }
  432. /**
  433. * Helper. Read a PEM-encoded RSA from the first <b>len</b> characters of
  434. * <b>src</b>, and store the result in <b>env</b>. If <b>private_key</b>,
  435. * expect a private key; otherwise expect a public key. Return 0 on success,
  436. * -1 on failure. If len is -1, the string is nul-terminated.
  437. */
  438. static int
  439. crypto_pk_read_from_string_generic(crypto_pk_t *env, const char *src,
  440. size_t len, int severity,
  441. bool private_key)
  442. {
  443. if (len == (size_t)-1) // "-1" indicates "use the length of the string."
  444. len = strlen(src);
  445. const char *ktype = private_key ? "private key" : "public key";
  446. const char *tag =
  447. private_key ? RSA_PRIVATE_TAG : RSA_PUBLIC_TAG;
  448. size_t buflen = len;
  449. uint8_t *buf = tor_malloc(buflen);
  450. int rv = -1;
  451. int n = pem_decode(buf, buflen, src, len, tag);
  452. if (n < 0) {
  453. log_fn(severity, LD_CRYPTO,
  454. "Error decoding PEM wrapper while reading %s", ktype);
  455. goto done;
  456. }
  457. crypto_pk_t *pk = private_key
  458. ? crypto_pk_asn1_decode_private((const char*)buf, n)
  459. : crypto_pk_asn1_decode((const char*)buf, n);
  460. if (! pk) {
  461. log_fn(severity, LD_CRYPTO,
  462. "Error decoding ASN.1 while reading %s", ktype);
  463. goto done;
  464. }
  465. if (private_key)
  466. crypto_pk_assign_private(env, pk);
  467. else
  468. crypto_pk_assign_public(env, pk);
  469. crypto_pk_free(pk);
  470. rv = 0;
  471. done:
  472. memwipe(buf, 0, buflen);
  473. tor_free(buf);
  474. return rv;
  475. }
  476. /** Read a PEM-encoded public key from the first <b>len</b> characters of
  477. * <b>src</b>, and store the result in <b>env</b>. Return 0 on success, -1 on
  478. * failure. If len is -1, the string is nul-terminated.
  479. */
  480. int
  481. crypto_pk_read_public_key_from_string(crypto_pk_t *env,
  482. const char *src, size_t len)
  483. {
  484. return crypto_pk_read_from_string_generic(env, src, len, LOG_INFO, false);
  485. }
  486. /** Read a PEM-encoded private key from the <b>len</b>-byte string <b>src</b>
  487. * into <b>env</b>. Return 0 on success, -1 on failure. If len is -1,
  488. * the string is nul-terminated.
  489. */
  490. int
  491. crypto_pk_read_private_key_from_string(crypto_pk_t *env,
  492. const char *src, ssize_t len)
  493. {
  494. return crypto_pk_read_from_string_generic(env, src, len, LOG_INFO, true);
  495. }
  496. /** If a file is longer than this, we won't try to decode its private key */
  497. #define MAX_PRIVKEY_FILE_LEN (16*1024*1024)
  498. /** Read a PEM-encoded private key from the file named by
  499. * <b>keyfile</b> into <b>env</b>. Return 0 on success, -1 on failure.
  500. */
  501. int
  502. crypto_pk_read_private_key_from_filename(crypto_pk_t *env,
  503. const char *keyfile)
  504. {
  505. struct stat st;
  506. char *buf = read_file_to_str(keyfile, 0, &st);
  507. if (!buf) {
  508. log_warn(LD_CRYPTO, "Unable to read file for private key in %s",
  509. escaped(keyfile));
  510. return -1;
  511. }
  512. if (st.st_size > MAX_PRIVKEY_FILE_LEN) {
  513. log_warn(LD_CRYPTO, "Private key file %s was far too large.",
  514. escaped(keyfile));
  515. tor_free(buf);
  516. return -1;
  517. }
  518. int rv = crypto_pk_read_from_string_generic(env, buf, (ssize_t)st.st_size,
  519. LOG_WARN, true);
  520. if (rv < 0) {
  521. log_warn(LD_CRYPTO, "Unable to decode private key from file %s",
  522. escaped(keyfile));
  523. }
  524. memwipe(buf, 0, (size_t)st.st_size);
  525. tor_free(buf);
  526. return rv;
  527. }
  528. /** Write the private key from <b>env</b> into the file named by <b>fname</b>,
  529. * PEM-encoded. Return 0 on success, -1 on failure.
  530. */
  531. int
  532. crypto_pk_write_private_key_to_filename(crypto_pk_t *env,
  533. const char *fname)
  534. {
  535. char *s = NULL;
  536. size_t n = 0;
  537. if (crypto_pk_write_private_key_to_string(env, &s, &n) < 0)
  538. return -1;
  539. int rv = write_bytes_to_file(fname, s, n, 0);
  540. memwipe(s, 0, n);
  541. tor_free(s);
  542. return rv;
  543. }
  544. /** Given a crypto_pk_t <b>pk</b>, allocate a new buffer containing the
  545. * Base64 encoding of the DER representation of the private key as a NUL
  546. * terminated string, and return it via <b>priv_out</b>. Return 0 on
  547. * success, -1 on failure.
  548. *
  549. * It is the caller's responsibility to sanitize and free the resulting buffer.
  550. */
  551. int
  552. crypto_pk_base64_encode_private(const crypto_pk_t *pk, char **priv_out)
  553. {
  554. size_t buflen = crypto_pk_keysize(pk)*16;
  555. char *buf = tor_malloc(buflen);
  556. char *result = NULL;
  557. size_t reslen = 0;
  558. bool ok = false;
  559. int n = crypto_pk_asn1_encode_private(pk, buf, buflen);
  560. if (n < 0)
  561. goto done;
  562. reslen = base64_encode_size(n, 0)+1;
  563. result = tor_malloc(reslen);
  564. if (base64_encode(result, reslen, buf, n, 0) < 0)
  565. goto done;
  566. ok = true;
  567. done:
  568. memwipe(buf, 0, buflen);
  569. tor_free(buf);
  570. if (result && ! ok) {
  571. memwipe(result, 0, reslen);
  572. tor_free(result);
  573. }
  574. *priv_out = result;
  575. return ok ? 0 : -1;
  576. }
  577. /** Given a string containing the Base64 encoded DER representation of the
  578. * private key <b>str</b>, decode and return the result on success, or NULL
  579. * on failure.
  580. */
  581. crypto_pk_t *
  582. crypto_pk_base64_decode_private(const char *str, size_t len)
  583. {
  584. crypto_pk_t *pk = NULL;
  585. char *der = tor_malloc_zero(len + 1);
  586. int der_len = base64_decode(der, len, str, len);
  587. if (der_len <= 0) {
  588. log_warn(LD_CRYPTO, "Stored RSA private key seems corrupted (base64).");
  589. goto out;
  590. }
  591. pk = crypto_pk_asn1_decode_private(der, der_len);
  592. out:
  593. memwipe(der, 0, len+1);
  594. tor_free(der);
  595. return pk;
  596. }