crypto_rsa.c 19 KB

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