crypto.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431
  1. /* Copyright 2001,2002,2003 Roger Dingledine, Matej Pfajfar. */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. #include "../or/or.h"
  5. #include <string.h>
  6. #include <openssl/err.h>
  7. #include <openssl/rsa.h>
  8. #include <openssl/pem.h>
  9. #include <openssl/evp.h>
  10. #include <openssl/rand.h>
  11. #include <openssl/opensslv.h>
  12. #include <openssl/bn.h>
  13. #include <openssl/dh.h>
  14. #include <stdlib.h>
  15. #include <assert.h>
  16. #include <stdio.h>
  17. #include <limits.h>
  18. #include "crypto.h"
  19. #include "log.h"
  20. #include "aes.h"
  21. #ifdef MS_WINDOWS
  22. #include <wincrypt.h>
  23. #endif
  24. #if OPENSSL_VERSION_NUMBER < 0x00905000l
  25. #error "We require openssl >= 0.9.5"
  26. #elif OPENSSL_VERSION_NUMBER < 0x00906000l
  27. #define OPENSSL_095
  28. #endif
  29. /*
  30. * Certain functions that return a success code in OpenSSL 0.9.6 return void
  31. * (and don't indicate errors) in OpenSSL version 0.9.5.
  32. *
  33. * [OpenSSL 0.9.5 matters, because it ships with Redhat 6.2.]
  34. */
  35. #ifdef OPENSSL_095
  36. #define RETURN_SSL_OUTCOME(exp) (exp); return 0
  37. #else
  38. #define RETURN_SSL_OUTCOME(exp) return !(exp)
  39. #endif
  40. struct crypto_pk_env_t
  41. {
  42. int type;
  43. int refs; /* reference counting; so we don't have to copy keys */
  44. unsigned char *key;
  45. /* auxiliary data structure(s) used by the underlying crypto library */
  46. unsigned char *aux;
  47. };
  48. struct crypto_cipher_env_t
  49. {
  50. int type;
  51. unsigned char *key;
  52. unsigned char *iv;
  53. /* auxiliary data structure(s) used by the underlying crypto library */
  54. unsigned char *aux;
  55. };
  56. /* static INLINE const EVP_CIPHER *
  57. crypto_cipher_evp_cipher(int type, int enc);
  58. */
  59. static INLINE int
  60. crypto_cipher_iv_length(int type) {
  61. /*
  62. printf("%d -> %d IV\n",type,
  63. EVP_CIPHER_iv_length(crypto_cipher_evp_cipher(type,0)));
  64. */
  65. switch(type)
  66. {
  67. case CRYPTO_CIPHER_IDENTITY: return 0;
  68. case CRYPTO_CIPHER_DES: return 8;
  69. case CRYPTO_CIPHER_RC4: return 16;
  70. case CRYPTO_CIPHER_3DES: return 8;
  71. case CRYPTO_CIPHER_AES_CTR: return 0;
  72. default: assert(0); return -1;
  73. }
  74. }
  75. static INLINE int
  76. crypto_cipher_key_length(int type) {
  77. /*
  78. printf("%d -> %d\n",type,
  79. EVP_CIPHER_key_length(crypto_cipher_evp_cipher(type,0)));
  80. */
  81. switch(type)
  82. {
  83. case CRYPTO_CIPHER_IDENTITY: return 0;
  84. case CRYPTO_CIPHER_DES: return 8;
  85. case CRYPTO_CIPHER_RC4: return 16;
  86. case CRYPTO_CIPHER_3DES: return 16;
  87. case CRYPTO_CIPHER_AES_CTR: return 16;
  88. default: assert(0); return -1;
  89. }
  90. }
  91. static INLINE const EVP_CIPHER *
  92. crypto_cipher_evp_cipher(int type, int enc) {
  93. switch(type)
  94. {
  95. case CRYPTO_CIPHER_IDENTITY: return EVP_enc_null();
  96. case CRYPTO_CIPHER_DES: return EVP_des_ofb();
  97. case CRYPTO_CIPHER_RC4: return EVP_rc4();
  98. case CRYPTO_CIPHER_3DES: return EVP_des_ede_ofb();
  99. default: return NULL;
  100. }
  101. }
  102. static INLINE int
  103. crypto_get_rsa_padding_overhead(int padding) {
  104. switch(padding)
  105. {
  106. case RSA_NO_PADDING: return 0;
  107. case RSA_PKCS1_OAEP_PADDING: return 42;
  108. case RSA_PKCS1_PADDING: return 11;
  109. default: assert(0); return -1;
  110. }
  111. }
  112. static int _crypto_global_initialized = 0;
  113. int crypto_global_init()
  114. {
  115. if (!_crypto_global_initialized) {
  116. ERR_load_crypto_strings();
  117. _crypto_global_initialized = 1;
  118. }
  119. return 0;
  120. }
  121. int crypto_global_cleanup()
  122. {
  123. ERR_free_strings();
  124. return 0;
  125. }
  126. crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa)
  127. {
  128. crypto_pk_env_t *env;
  129. assert(rsa);
  130. env = (crypto_pk_env_t *)tor_malloc(sizeof(crypto_pk_env_t));
  131. env->type = CRYPTO_PK_RSA;
  132. env->refs = 1;
  133. env->key = (unsigned char*)rsa;
  134. env->aux = NULL;
  135. return env;
  136. }
  137. RSA *_crypto_pk_env_get_rsa(crypto_pk_env_t *env)
  138. {
  139. if (env->type != CRYPTO_PK_RSA)
  140. return NULL;
  141. return (RSA*)env->key;
  142. }
  143. EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env)
  144. {
  145. RSA *key = NULL;
  146. EVP_PKEY *pkey = NULL;
  147. if (env->type != CRYPTO_PK_RSA)
  148. return NULL;
  149. assert(env->key);
  150. if (!(key = RSAPrivateKey_dup((RSA*)env->key)))
  151. goto error;
  152. if (!(pkey = EVP_PKEY_new()))
  153. goto error;
  154. if (!(EVP_PKEY_assign_RSA(pkey, key)))
  155. goto error;
  156. return pkey;
  157. error:
  158. if (pkey)
  159. EVP_PKEY_free(pkey);
  160. if (key)
  161. RSA_free(key);
  162. return NULL;
  163. }
  164. crypto_pk_env_t *crypto_new_pk_env(int type)
  165. {
  166. RSA *rsa;
  167. switch(type) {
  168. case CRYPTO_PK_RSA:
  169. rsa = RSA_new();
  170. if (!rsa) return NULL;
  171. return _crypto_new_pk_env_rsa(rsa);
  172. default:
  173. return NULL;
  174. }
  175. }
  176. void crypto_free_pk_env(crypto_pk_env_t *env)
  177. {
  178. assert(env);
  179. if(--env->refs > 0)
  180. return;
  181. switch(env->type) {
  182. case CRYPTO_PK_RSA:
  183. if (env->key)
  184. RSA_free((RSA *)env->key);
  185. break;
  186. default:
  187. break;
  188. }
  189. free(env);
  190. }
  191. /* Create a new crypto_cipher_env_t for a given onion cipher type, key,
  192. * iv, and encryption flag (1=encrypt, 0=decrypt). Return the crypto object
  193. * on success; NULL on failure.
  194. */
  195. crypto_cipher_env_t *
  196. crypto_create_init_cipher(int cipher_type, char *key, char *iv, int encrypt_mode)
  197. {
  198. int r;
  199. crypto_cipher_env_t *crypto = NULL;
  200. if (! (crypto = crypto_new_cipher_env(cipher_type))) {
  201. log_fn(LOG_WARN, "Unable to allocate crypto object");
  202. return NULL;
  203. }
  204. if (crypto_cipher_set_key(crypto, key)) {
  205. log_fn(LOG_WARN, "Unable to set key: %s", crypto_perror());
  206. goto error;
  207. }
  208. if (crypto_cipher_set_iv(crypto, iv)) {
  209. log_fn(LOG_WARN, "Unable to set iv: %s", crypto_perror());
  210. goto error;
  211. }
  212. if (encrypt_mode)
  213. r = crypto_cipher_encrypt_init_cipher(crypto);
  214. else
  215. r = crypto_cipher_decrypt_init_cipher(crypto);
  216. if (r) {
  217. log_fn(LOG_WARN, "Unable to initialize cipher: %s", crypto_perror());
  218. goto error;
  219. }
  220. return crypto;
  221. error:
  222. if (crypto)
  223. crypto_free_cipher_env(crypto);
  224. return NULL;
  225. }
  226. crypto_cipher_env_t *crypto_new_cipher_env(int type)
  227. {
  228. crypto_cipher_env_t *env;
  229. int iv_len, key_len;
  230. env = (crypto_cipher_env_t *)tor_malloc(sizeof(crypto_cipher_env_t));
  231. env->type = type;
  232. env->key = NULL;
  233. env->iv = NULL;
  234. env->aux = NULL;
  235. iv_len = crypto_cipher_iv_length(type);
  236. key_len = crypto_cipher_key_length(type);
  237. if (type == CRYPTO_CIPHER_AES_CTR) {
  238. env->aux = (unsigned char *)aes_new_cipher();
  239. } else if (! crypto_cipher_evp_cipher(type,0))
  240. /* This is not an openssl cipher */
  241. goto err;
  242. else {
  243. env->aux = (unsigned char *)tor_malloc(sizeof(EVP_CIPHER_CTX));
  244. EVP_CIPHER_CTX_init((EVP_CIPHER_CTX *)env->aux);
  245. }
  246. if(iv_len)
  247. env->iv = (unsigned char *)tor_malloc(iv_len);
  248. if(key_len)
  249. env->key = (unsigned char *)tor_malloc(key_len);
  250. return env;
  251. err:
  252. if (env->key)
  253. free(env->key);
  254. if (env->iv)
  255. free(env->iv);
  256. if (env->aux)
  257. free(env->aux);
  258. if (env)
  259. free(env);
  260. return NULL;
  261. }
  262. void crypto_free_cipher_env(crypto_cipher_env_t *env)
  263. {
  264. assert(env);
  265. if (env->type == CRYPTO_CIPHER_AES_CTR) {
  266. assert(env->aux);
  267. aes_free_cipher((aes_cnt_cipher_t*)env->aux);
  268. env->aux = NULL;
  269. } else if (crypto_cipher_evp_cipher(env->type,0)) {
  270. /* This is an openssl cipher */
  271. assert(env->aux);
  272. EVP_CIPHER_CTX_cleanup((EVP_CIPHER_CTX *)env->aux);
  273. }
  274. if (env->aux)
  275. free((void *)env->aux);
  276. if (env->iv)
  277. free((void *)env->iv);
  278. if (env->key)
  279. free((void *)env->key);
  280. free((void *)env);
  281. }
  282. /* public key crypto */
  283. int crypto_pk_generate_key(crypto_pk_env_t *env)
  284. {
  285. assert(env);
  286. switch(env->type) {
  287. case CRYPTO_PK_RSA:
  288. if (env->key)
  289. RSA_free((RSA *)env->key);
  290. env->key = (unsigned char *)RSA_generate_key(1024,65537, NULL, NULL);
  291. if (!env->key)
  292. return -1;
  293. break;
  294. default:
  295. return -1;
  296. }
  297. return 0;
  298. }
  299. int crypto_pk_read_private_key_from_file(crypto_pk_env_t *env, FILE *src)
  300. {
  301. assert(env && src);
  302. switch(env->type) {
  303. case CRYPTO_PK_RSA:
  304. if (env->key)
  305. RSA_free((RSA *)env->key);
  306. env->key = (unsigned char *)PEM_read_RSAPrivateKey(src, NULL, NULL, NULL);
  307. if (!env->key)
  308. return -1;
  309. break;
  310. default :
  311. return -1;
  312. }
  313. return 0;
  314. }
  315. int crypto_pk_read_private_key_from_filename(crypto_pk_env_t *env, const char *keyfile)
  316. {
  317. FILE *f_pr;
  318. assert(env && keyfile);
  319. if(strspn(keyfile,CONFIG_LEGAL_FILENAME_CHARACTERS) != strlen(keyfile)) {
  320. /* filename contains nonlegal characters */
  321. return -1;
  322. }
  323. /* open the keyfile */
  324. f_pr=fopen(keyfile,"rb");
  325. if (!f_pr)
  326. return -1;
  327. /* read the private key */
  328. if(crypto_pk_read_private_key_from_file(env, f_pr) < 0) {
  329. log_fn(LOG_WARN,"Error reading private key : %s",crypto_perror());
  330. fclose(f_pr);
  331. return -1;
  332. }
  333. fclose(f_pr);
  334. /* check the private key */
  335. switch(crypto_pk_check_key(env)) {
  336. case 0:
  337. log_fn(LOG_WARN,"Private key read but is invalid : %s.", crypto_perror());
  338. return -1;
  339. case -1:
  340. log_fn(LOG_WARN,"Private key read but validity checking failed : %s",crypto_perror());
  341. return -1;
  342. /* case 1: fall through */
  343. }
  344. return 0;
  345. }
  346. int crypto_pk_read_public_key_from_file(crypto_pk_env_t *env, FILE *src)
  347. {
  348. assert(env && src);
  349. switch(env->type) {
  350. case CRYPTO_PK_RSA:
  351. if(env->key)
  352. RSA_free((RSA *)env->key);
  353. env->key = (unsigned char *)PEM_read_RSAPublicKey(src, NULL, NULL, NULL);
  354. if (!env->key)
  355. return -1;
  356. break;
  357. default :
  358. return -1;
  359. }
  360. return 0;
  361. }
  362. int crypto_pk_write_public_key_to_string(crypto_pk_env_t *env, char **dest, int *len) {
  363. BUF_MEM *buf;
  364. BIO *b;
  365. assert(env && env->key && dest);
  366. switch(env->type) {
  367. case CRYPTO_PK_RSA:
  368. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  369. /* Now you can treat b as if it were a file. Just use the
  370. * PEM_*_bio_* functions instead of the non-bio variants.
  371. */
  372. if(!PEM_write_bio_RSAPublicKey(b, (RSA *)env->key))
  373. return -1;
  374. BIO_get_mem_ptr(b, &buf);
  375. BIO_set_close(b, BIO_NOCLOSE); /* so BIO_free doesn't free buf */
  376. BIO_free(b);
  377. *dest = tor_malloc(buf->length+1);
  378. memcpy(*dest, buf->data, buf->length);
  379. (*dest)[buf->length] = 0; /* null terminate it */
  380. *len = buf->length;
  381. BUF_MEM_free(buf);
  382. break;
  383. default:
  384. return -1;
  385. }
  386. return 0;
  387. }
  388. int crypto_pk_read_public_key_from_string(crypto_pk_env_t *env, const char *src, int len) {
  389. BIO *b;
  390. assert(env && src);
  391. switch(env->type) {
  392. case CRYPTO_PK_RSA:
  393. b = BIO_new(BIO_s_mem()); /* Create a memory BIO */
  394. BIO_write(b, src, len);
  395. RSA_free((RSA *)env->key);
  396. env->key = (unsigned char *)PEM_read_bio_RSAPublicKey(b, NULL, NULL, NULL);
  397. if(!env->key)
  398. return -1;
  399. BIO_free(b);
  400. break;
  401. default:
  402. return -1;
  403. }
  404. return 0;
  405. }
  406. int
  407. crypto_pk_write_private_key_to_filename(crypto_pk_env_t *env,
  408. const char *fname)
  409. {
  410. BIO *bio;
  411. char *cp;
  412. long len;
  413. char *s;
  414. int r;
  415. assert(env->type == CRYPTO_PK_RSA);
  416. if (!(bio = BIO_new(BIO_s_mem())))
  417. return -1;
  418. if (PEM_write_bio_RSAPrivateKey(bio, (RSA*)env->key, NULL,NULL,0,NULL,NULL)
  419. == 0) {
  420. BIO_free(bio);
  421. return -1;
  422. }
  423. len = BIO_get_mem_data(bio, &cp);
  424. s = tor_malloc(len+1);
  425. strncpy(s, cp, len);
  426. s[len] = '\0';
  427. r = write_str_to_file(fname, s);
  428. BIO_free(bio);
  429. free(s);
  430. return r;
  431. }
  432. int crypto_pk_write_private_key_to_file(crypto_pk_env_t *env, FILE *dest)
  433. {
  434. assert(env && dest);
  435. switch(env->type) {
  436. case CRYPTO_PK_RSA:
  437. if (!env->key)
  438. return -1;
  439. if (PEM_write_RSAPrivateKey(dest, (RSA *)env->key, NULL, NULL, 0,0, NULL) == 0)
  440. return -1;
  441. break;
  442. default :
  443. return -1;
  444. }
  445. return 0;
  446. }
  447. int crypto_pk_write_public_key_to_file(crypto_pk_env_t *env, FILE *dest)
  448. {
  449. assert(env && dest);
  450. switch(env->type) {
  451. case CRYPTO_PK_RSA:
  452. if (!env->key)
  453. return -1;
  454. if (PEM_write_RSAPublicKey(dest, (RSA *)env->key) == 0)
  455. return -1;
  456. break;
  457. default :
  458. return -1;
  459. }
  460. return 0;
  461. }
  462. int crypto_pk_check_key(crypto_pk_env_t *env)
  463. {
  464. assert(env);
  465. switch(env->type) {
  466. case CRYPTO_PK_RSA:
  467. return RSA_check_key((RSA *)env->key);
  468. default:
  469. return -1;
  470. }
  471. }
  472. int crypto_pk_cmp_keys(crypto_pk_env_t *a, crypto_pk_env_t *b) {
  473. int result;
  474. if (!a || !b)
  475. return -1;
  476. if (!a->key || !b->key)
  477. return -1;
  478. if (a->type != b->type)
  479. return -1;
  480. switch(a->type) {
  481. case CRYPTO_PK_RSA:
  482. assert(((RSA *)a->key)->n && ((RSA *)a->key)->e && ((RSA *)b->key)->n && ((RSA *)b->key)->e);
  483. result = BN_cmp(((RSA *)a->key)->n, ((RSA *)b->key)->n);
  484. if (result)
  485. return result;
  486. return BN_cmp(((RSA *)a->key)->e, ((RSA *)b->key)->e);
  487. default:
  488. return -1;
  489. }
  490. }
  491. /* return the size of the public key modulus in 'env', in bytes. */
  492. int crypto_pk_keysize(crypto_pk_env_t *env)
  493. {
  494. assert(env && env->key);
  495. return RSA_size((RSA *)env->key);
  496. }
  497. crypto_pk_env_t *crypto_pk_dup_key(crypto_pk_env_t *env) {
  498. assert(env && env->key);
  499. switch(env->type) {
  500. case CRYPTO_PK_RSA:
  501. env->refs++;
  502. break;
  503. default:
  504. return NULL;
  505. }
  506. return env;
  507. }
  508. int crypto_pk_public_encrypt(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to, int padding)
  509. {
  510. assert(env && from && to);
  511. switch(env->type) {
  512. case CRYPTO_PK_RSA:
  513. return RSA_public_encrypt(fromlen, from, to, (RSA *)env->key, padding);
  514. default:
  515. return -1;
  516. }
  517. }
  518. int crypto_pk_private_decrypt(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to, int padding)
  519. {
  520. assert(env && from && to);
  521. switch(env->type) {
  522. case CRYPTO_PK_RSA:
  523. if (!(((RSA*)env->key)->p))
  524. return -1;
  525. return RSA_private_decrypt(fromlen, from, to, (RSA *)env->key, padding);
  526. default:
  527. return -1;
  528. }
  529. }
  530. int crypto_pk_public_checksig(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to)
  531. {
  532. assert(env && from && to);
  533. switch(env->type) {
  534. case CRYPTO_PK_RSA:
  535. return RSA_public_decrypt(fromlen, from, to, (RSA *)env->key,
  536. RSA_PKCS1_PADDING);
  537. default:
  538. return -1;
  539. }
  540. }
  541. int crypto_pk_private_sign(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to)
  542. {
  543. assert(env && from && to);
  544. switch(env->type) {
  545. case CRYPTO_PK_RSA:
  546. if (!(((RSA*)env->key)->p))
  547. return -1;
  548. return RSA_private_encrypt(fromlen, from, to, (RSA *)env->key,
  549. RSA_PKCS1_PADDING);
  550. default:
  551. return -1;
  552. }
  553. }
  554. /* Return 0 if sig is a correct signature for SHA1(data). Else return -1.
  555. */
  556. int crypto_pk_public_checksig_digest(crypto_pk_env_t *env, unsigned char *data, int datalen, unsigned char *sig, int siglen)
  557. {
  558. char digest[CRYPTO_SHA1_DIGEST_LEN];
  559. char buf[1024];
  560. int r;
  561. assert(env && data && sig);
  562. if (crypto_SHA_digest(data,datalen,digest)<0) {
  563. log_fn(LOG_WARN, "couldn't compute digest");
  564. return -1;
  565. }
  566. r = crypto_pk_public_checksig(env,sig,siglen,buf);
  567. if (r != CRYPTO_SHA1_DIGEST_LEN) {
  568. log_fn(LOG_WARN, "Invalid signature");
  569. return -1;
  570. }
  571. if (memcmp(buf, digest, CRYPTO_SHA1_DIGEST_LEN)) {
  572. log_fn(LOG_WARN, "Signature mismatched with digest.");
  573. return -1;
  574. }
  575. return 0;
  576. }
  577. /* Fill 'to' with a signature of SHA1(from).
  578. */
  579. int crypto_pk_private_sign_digest(crypto_pk_env_t *env, unsigned char *from, int fromlen, unsigned char *to)
  580. {
  581. char digest[CRYPTO_SHA1_DIGEST_LEN];
  582. if (crypto_SHA_digest(from,fromlen,digest)<0)
  583. return 0;
  584. return crypto_pk_private_sign(env,digest,CRYPTO_SHA1_DIGEST_LEN,to);
  585. }
  586. /* Perform a hybrid (public/secret) encryption on 'fromlen' bytes of data
  587. * from 'from', with padding type 'padding', storing the results on 'to'.
  588. *
  589. * If no padding is used, the public key must be at least as large as
  590. * 'from'.
  591. *
  592. * Returns the number of bytes written on success, -1 on failure.
  593. *
  594. * The encrypted data consists of:
  595. *
  596. * The source data, padded and encrypted with the public key, if the
  597. * padded source data is no longer than the public key.
  598. * OR
  599. * The beginning of the source data prefixed with a 16-symmetric key,
  600. * padded and encrypted with the public key; followed by the rest of
  601. * the source data encrypted in AES-CTR mode with the symmetric key.
  602. */
  603. int crypto_pk_public_hybrid_encrypt(crypto_pk_env_t *env, unsigned char *from,
  604. int fromlen, unsigned char *to,
  605. int padding)
  606. {
  607. int overhead, pkeylen, outlen, r, symlen;
  608. crypto_cipher_env_t *cipher = NULL;
  609. char buf[1024];
  610. assert(env && from && to);
  611. overhead = crypto_get_rsa_padding_overhead(padding);
  612. pkeylen = crypto_pk_keysize(env);
  613. if (padding == RSA_NO_PADDING && fromlen < pkeylen)
  614. return -1;
  615. if (fromlen+overhead <= pkeylen) {
  616. /* It all fits in a single encrypt. */
  617. return crypto_pk_public_encrypt(env,from,fromlen,to,padding);
  618. }
  619. cipher = crypto_new_cipher_env(CRYPTO_CIPHER_AES_CTR);
  620. if (!cipher) return -1;
  621. if (crypto_cipher_generate_key(cipher)<0)
  622. goto err;
  623. if (padding == RSA_NO_PADDING)
  624. cipher->key[0] &= 0x7f;
  625. if (crypto_cipher_encrypt_init_cipher(cipher)<0)
  626. goto err;
  627. memcpy(buf, cipher->key, 16);
  628. memcpy(buf+16, from, pkeylen-overhead-16);
  629. /* Length of symmetrically encrypted data. */
  630. symlen = fromlen-(pkeylen-overhead-16);
  631. outlen = crypto_pk_public_encrypt(env,buf,pkeylen-overhead,to,padding);
  632. if (outlen!=pkeylen) {
  633. goto err;
  634. }
  635. r = crypto_cipher_encrypt(cipher,
  636. from+pkeylen-overhead-16, symlen,
  637. to+outlen);
  638. if (r<0) goto err;
  639. memset(buf, 0, 1024);
  640. crypto_free_cipher_env(cipher);
  641. return outlen + symlen;
  642. err:
  643. memset(buf, 0, 1024);
  644. if (cipher) crypto_free_cipher_env(cipher);
  645. return -1;
  646. }
  647. /* Invert crypto_pk_public_hybrid_encrypt. */
  648. int crypto_pk_private_hybrid_decrypt(crypto_pk_env_t *env, unsigned char *from,
  649. int fromlen, unsigned char *to,
  650. int padding)
  651. {
  652. int overhead, pkeylen, outlen, r;
  653. crypto_cipher_env_t *cipher = NULL;
  654. char buf[1024];
  655. overhead = crypto_get_rsa_padding_overhead(padding);
  656. pkeylen = crypto_pk_keysize(env);
  657. if (fromlen <= pkeylen) {
  658. return crypto_pk_private_decrypt(env,from,fromlen,to,padding);
  659. }
  660. outlen = crypto_pk_private_decrypt(env,from,pkeylen,buf,padding);
  661. if (outlen<0) {
  662. log_fn(LOG_WARN, "Error decrypting public-key data");
  663. return -1;
  664. }
  665. if (outlen < 16) {
  666. log_fn(LOG_WARN, "No room for a symmetric key");
  667. return -1;
  668. }
  669. cipher = crypto_create_init_cipher(CRYPTO_CIPHER_AES_CTR, buf, "", 0);
  670. if (!cipher) {
  671. return -1;
  672. }
  673. memcpy(to,buf+16,outlen-16);
  674. outlen -= 16;
  675. r = crypto_cipher_decrypt(cipher, from+pkeylen, fromlen-pkeylen,
  676. to+outlen);
  677. if (r<0)
  678. goto err;
  679. memset(buf,0,1024);
  680. crypto_free_cipher_env(cipher);
  681. return outlen + (fromlen-pkeylen);
  682. err:
  683. memset(buf, 0, 1024);
  684. if (cipher) crypto_free_cipher_env(cipher);
  685. return -1;
  686. }
  687. /* Encode the public portion of 'pk' into 'dest'. Return -1 on error,
  688. * or the number of characters used on success.
  689. */
  690. int crypto_pk_asn1_encode(crypto_pk_env_t *pk, char *dest, int dest_len)
  691. {
  692. int len;
  693. unsigned char *buf, *bufp;
  694. len = i2d_RSAPublicKey((RSA*)pk->key, NULL);
  695. if (len < 0 || len > dest_len)
  696. return -1;
  697. bufp = buf = (unsigned char *)tor_malloc(len+1);
  698. len = i2d_RSAPublicKey((RSA*)pk->key, &bufp);
  699. if (len < 0) {
  700. tor_free(buf);
  701. return -1;
  702. }
  703. /* We don't encode directly into 'dest', because that would be illegal
  704. * type-punning. (C99 is smarter than me, C99 is smarter than me...)
  705. */
  706. memcpy(dest,buf,len);
  707. tor_free(buf);
  708. return len;
  709. }
  710. /* Decode an ASN1-encoded public key from str.
  711. */
  712. crypto_pk_env_t *crypto_pk_asn1_decode(const char *str, int len)
  713. {
  714. RSA *rsa;
  715. unsigned char *buf;
  716. const unsigned char *bufp;
  717. bufp = buf = tor_malloc(len);
  718. memcpy(buf,str,len);
  719. /* This ifdef suppresses a type warning. Take out the first case once
  720. * everybody is using openssl 0.9.7 or later.
  721. */
  722. #if OPENSSL_VERSION_NUMBER < 0x00907000l
  723. rsa = d2i_RSAPublicKey(NULL, &buf, len);
  724. #else
  725. rsa = d2i_RSAPublicKey(NULL, &bufp, len);
  726. #endif
  727. tor_free(buf);
  728. if (!rsa)
  729. return NULL; /* XXXX log openssl error */
  730. return _crypto_new_pk_env_rsa(rsa);
  731. }
  732. /* Given a private or public key pk, put a SHA1 hash of the public key into
  733. * digest_out (must have 20 bytes of space).
  734. */
  735. int crypto_pk_get_digest(crypto_pk_env_t *pk, char *digest_out)
  736. {
  737. unsigned char *buf, *bufp;
  738. int len;
  739. assert(pk->type == CRYPTO_PK_RSA);
  740. len = i2d_RSAPublicKey((RSA*)pk->key, NULL);
  741. if (len < 0)
  742. return -1;
  743. buf = bufp = tor_malloc(len+1);
  744. len = i2d_RSAPublicKey((RSA*)pk->key, &bufp);
  745. if (len < 0) {
  746. free(buf);
  747. return -1;
  748. }
  749. if (crypto_SHA_digest(buf, len, digest_out) < 0) {
  750. free(buf);
  751. return -1;
  752. }
  753. return 0;
  754. }
  755. /* Given a private or public key pk, put a fingerprint of the
  756. * public key into fp_out (must have at least FINGERPRINT_LEN+1 bytes of
  757. * space).
  758. */
  759. int
  760. crypto_pk_get_fingerprint(crypto_pk_env_t *pk, char *fp_out)
  761. {
  762. unsigned char *bufp;
  763. unsigned char digest[20];
  764. unsigned char buf[FINGERPRINT_LEN+1];
  765. int i;
  766. if (crypto_pk_get_digest(pk, digest)) {
  767. return -1;
  768. }
  769. bufp = buf;
  770. for (i = 0; i < 20; ++i) {
  771. sprintf(bufp,"%02X",digest[i]);
  772. bufp += 2;
  773. if (i%2 && i != 19) {
  774. *bufp++ = ' ';
  775. }
  776. }
  777. *bufp = '\0';
  778. assert(strlen(buf) == FINGERPRINT_LEN);
  779. assert(crypto_pk_check_fingerprint_syntax(buf));
  780. strcpy(fp_out, buf);
  781. return 0;
  782. }
  783. int
  784. crypto_pk_check_fingerprint_syntax(const char *s)
  785. {
  786. int i;
  787. for (i = 0; i < FINGERPRINT_LEN; ++i) {
  788. if ((i%5) == 4) {
  789. if (!isspace((int)s[i])) return 0;
  790. } else {
  791. if (!isxdigit((int)s[i])) return 0;
  792. }
  793. }
  794. if (s[FINGERPRINT_LEN]) return 0;
  795. return 1;
  796. }
  797. /* symmetric crypto */
  798. int crypto_cipher_generate_key(crypto_cipher_env_t *env)
  799. {
  800. int key_len;
  801. assert(env);
  802. key_len = crypto_cipher_key_length(env->type);
  803. if (key_len > 0)
  804. return crypto_rand(key_len, env->key);
  805. else if (key_len == 0)
  806. return 0;
  807. else
  808. return -1;
  809. }
  810. int crypto_cipher_set_iv(crypto_cipher_env_t *env, unsigned char *iv)
  811. {
  812. int iv_len;
  813. assert(env && iv);
  814. iv_len = crypto_cipher_iv_length(env->type);
  815. if (!iv_len)
  816. return 0;
  817. if (!env->iv)
  818. return -1;
  819. memcpy((void*)env->iv, (void*)iv, iv_len);
  820. return 0;
  821. }
  822. int crypto_cipher_set_key(crypto_cipher_env_t *env, unsigned char *key)
  823. {
  824. int key_len;
  825. assert(env && key);
  826. key_len = crypto_cipher_key_length(env->type);
  827. if (!key_len)
  828. return 0;
  829. if (!env->key)
  830. return -1;
  831. memcpy((void*)env->key, (void*)key, key_len);
  832. return 0;
  833. }
  834. unsigned char *crypto_cipher_get_key(crypto_cipher_env_t *env)
  835. {
  836. return env->key;
  837. }
  838. int crypto_cipher_encrypt_init_cipher(crypto_cipher_env_t *env)
  839. {
  840. assert(env);
  841. if (crypto_cipher_evp_cipher(env->type, 1)) {
  842. RETURN_SSL_OUTCOME(EVP_EncryptInit((EVP_CIPHER_CTX *)env->aux,
  843. crypto_cipher_evp_cipher(env->type, 1),
  844. env->key, env->iv));
  845. } else if (env->type == CRYPTO_CIPHER_AES_CTR) {
  846. aes_set_key((aes_cnt_cipher_t*)env->aux, env->key, 128);
  847. return 0;
  848. } else {
  849. return -1;
  850. }
  851. }
  852. int crypto_cipher_decrypt_init_cipher(crypto_cipher_env_t *env)
  853. {
  854. assert(env);
  855. if (crypto_cipher_evp_cipher(env->type, 0)) {
  856. RETURN_SSL_OUTCOME(EVP_EncryptInit((EVP_CIPHER_CTX *)env->aux,
  857. crypto_cipher_evp_cipher(env->type, 0),
  858. env->key, env->iv));
  859. } else if (env->type == CRYPTO_CIPHER_AES_CTR) {
  860. aes_set_key((aes_cnt_cipher_t*)env->aux, env->key, 128);
  861. return 0;
  862. } else {
  863. return -1;
  864. }
  865. }
  866. int crypto_cipher_encrypt(crypto_cipher_env_t *env, unsigned char *from, unsigned int fromlen, unsigned char *to)
  867. {
  868. int tolen;
  869. assert(env && from && to);
  870. if (env->type == CRYPTO_CIPHER_AES_CTR) {
  871. aes_crypt((aes_cnt_cipher_t*)env->aux, from, fromlen, to);
  872. return 0;
  873. } else {
  874. RETURN_SSL_OUTCOME(EVP_EncryptUpdate((EVP_CIPHER_CTX *)env->aux, to, &tolen, from, fromlen));
  875. }
  876. }
  877. int crypto_cipher_decrypt(crypto_cipher_env_t *env, unsigned char *from, unsigned int fromlen, unsigned char *to)
  878. {
  879. int tolen;
  880. assert(env && from && to);
  881. if (env->type == CRYPTO_CIPHER_AES_CTR) {
  882. aes_crypt((aes_cnt_cipher_t*)env->aux, from, fromlen, to);
  883. return 0;
  884. } else {
  885. RETURN_SSL_OUTCOME(EVP_DecryptUpdate((EVP_CIPHER_CTX *)env->aux, to, &tolen, from, fromlen));
  886. }
  887. }
  888. int
  889. crypto_cipher_rewind(crypto_cipher_env_t *env, long delta)
  890. {
  891. return crypto_cipher_advance(env, -delta);
  892. }
  893. int
  894. crypto_cipher_advance(crypto_cipher_env_t *env, long delta)
  895. {
  896. if (env->type == CRYPTO_CIPHER_AES_CTR) {
  897. aes_adjust_counter((aes_cnt_cipher_t*)env->aux, delta);
  898. return 0;
  899. } else {
  900. return -1;
  901. }
  902. }
  903. /* SHA-1 */
  904. int crypto_SHA_digest(const unsigned char *m, int len, unsigned char *digest)
  905. {
  906. assert(m && digest);
  907. return (SHA1(m,len,digest) == NULL);
  908. }
  909. struct crypto_digest_env_t {
  910. SHA_CTX d;
  911. };
  912. crypto_digest_env_t *
  913. crypto_new_digest_env(int type)
  914. {
  915. crypto_digest_env_t *r;
  916. assert(type == CRYPTO_SHA1_DIGEST);
  917. r = tor_malloc(sizeof(crypto_digest_env_t));
  918. SHA1_Init(&r->d);
  919. return r;
  920. }
  921. void
  922. crypto_free_digest_env(crypto_digest_env_t *digest) {
  923. if(digest)
  924. free(digest);
  925. }
  926. void
  927. crypto_digest_add_bytes(crypto_digest_env_t *digest, const char *data,
  928. size_t len)
  929. {
  930. assert(digest);
  931. assert(data);
  932. SHA1_Update(&digest->d, (void*)data, len);
  933. }
  934. void crypto_digest_get_digest(crypto_digest_env_t *digest,
  935. char *out, size_t out_len)
  936. {
  937. static char r[SHA_DIGEST_LENGTH];
  938. assert(digest && out);
  939. assert(out_len <= SHA_DIGEST_LENGTH);
  940. SHA1_Final(r, &digest->d);
  941. memcpy(out, r, out_len);
  942. }
  943. crypto_digest_env_t *
  944. crypto_digest_dup(const crypto_digest_env_t *digest)
  945. {
  946. crypto_digest_env_t *r;
  947. assert(digest);
  948. r = tor_malloc(sizeof(crypto_digest_env_t));
  949. memcpy(r,digest,sizeof(crypto_digest_env_t));
  950. return r;
  951. }
  952. void
  953. crypto_digest_assign(crypto_digest_env_t *into,
  954. const crypto_digest_env_t *from)
  955. {
  956. assert(into && from);
  957. memcpy(into,from,sizeof(crypto_digest_env_t));
  958. }
  959. /* DH */
  960. static BIGNUM *dh_param_p = NULL;
  961. static BIGNUM *dh_param_g = NULL;
  962. static void init_dh_param() {
  963. BIGNUM *p, *g;
  964. int r;
  965. if (dh_param_p && dh_param_g)
  966. return;
  967. p = BN_new();
  968. g = BN_new();
  969. assert(p && g);
  970. #if 0
  971. /* This is from draft-ietf-ipsec-ike-modp-groups-05.txt. It's a safe
  972. prime, and supposedly it equals:
  973. 2^1536 - 2^1472 - 1 + 2^64 * { [2^1406 pi] + 741804 }
  974. */
  975. r = BN_hex2bn(&p,
  976. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1"
  977. "29024E088A67CC74020BBEA63B139B22514A08798E3404DD"
  978. "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245"
  979. "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
  980. "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D"
  981. "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F"
  982. "83655D23DCA3AD961C62F356208552BB9ED529077096966D"
  983. "670C354E4ABC9804F1746C08CA237327FFFFFFFFFFFFFFFF");
  984. #endif
  985. /* This is from rfc2409, section 6.2. It's a safe prime, and
  986. supposedly it equals:
  987. 2^1024 - 2^960 - 1 + 2^64 * { [2^894 pi] + 129093 }.
  988. */
  989. /* See also rfc 3536 */
  990. r = BN_hex2bn(&p,
  991. "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E08"
  992. "8A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B"
  993. "302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9"
  994. "A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE6"
  995. "49286651ECE65381FFFFFFFFFFFFFFFF");
  996. assert(r);
  997. r = BN_set_word(g, 2);
  998. assert(r);
  999. dh_param_p = p;
  1000. dh_param_g = g;
  1001. }
  1002. crypto_dh_env_t *crypto_dh_new()
  1003. {
  1004. crypto_dh_env_t *res = NULL;
  1005. if (!dh_param_p)
  1006. init_dh_param();
  1007. res = tor_malloc(sizeof(crypto_dh_env_t));
  1008. res->dh = NULL;
  1009. if (!(res->dh = DH_new()))
  1010. goto err;
  1011. if (!(res->dh->p = BN_dup(dh_param_p)))
  1012. goto err;
  1013. if (!(res->dh->g = BN_dup(dh_param_g)))
  1014. goto err;
  1015. return res;
  1016. err:
  1017. if (res && res->dh) DH_free(res->dh); /* frees p and g too */
  1018. if (res) free(res);
  1019. return NULL;
  1020. }
  1021. int crypto_dh_get_bytes(crypto_dh_env_t *dh)
  1022. {
  1023. assert(dh);
  1024. return DH_size(dh->dh);
  1025. }
  1026. int crypto_dh_generate_public(crypto_dh_env_t *dh)
  1027. {
  1028. if (!DH_generate_key(dh->dh))
  1029. return -1;
  1030. return 0;
  1031. }
  1032. int crypto_dh_get_public(crypto_dh_env_t *dh, char *pubkey, int pubkey_len)
  1033. {
  1034. int bytes;
  1035. assert(dh);
  1036. if (!dh->dh->pub_key) {
  1037. if (!DH_generate_key(dh->dh))
  1038. return -1;
  1039. }
  1040. assert(dh->dh->pub_key);
  1041. bytes = BN_num_bytes(dh->dh->pub_key);
  1042. if (pubkey_len < bytes)
  1043. return -1;
  1044. memset(pubkey, 0, pubkey_len);
  1045. BN_bn2bin(dh->dh->pub_key, pubkey+(pubkey_len-bytes));
  1046. return 0;
  1047. }
  1048. #undef MIN
  1049. #define MIN(a,b) ((a)<(b)?(a):(b))
  1050. int crypto_dh_compute_secret(crypto_dh_env_t *dh,
  1051. char *pubkey, int pubkey_len,
  1052. char *secret_out, int secret_bytes_out)
  1053. {
  1054. unsigned char hash[20];
  1055. unsigned char *secret_tmp = NULL;
  1056. BIGNUM *pubkey_bn = NULL;
  1057. int secret_len;
  1058. int i;
  1059. assert(dh);
  1060. assert(secret_bytes_out/20 <= 255);
  1061. if (!(pubkey_bn = BN_bin2bn(pubkey, pubkey_len, NULL)))
  1062. goto error;
  1063. secret_tmp = tor_malloc(crypto_dh_get_bytes(dh)+1);
  1064. secret_len = DH_compute_key(secret_tmp, pubkey_bn, dh->dh);
  1065. /* sometimes secret_len might be less than 128, e.g., 127. that's ok. */
  1066. for (i = 0; i < secret_bytes_out; i += 20) {
  1067. secret_tmp[secret_len] = (unsigned char) i/20;
  1068. if (crypto_SHA_digest(secret_tmp, secret_len+1, hash))
  1069. goto error;
  1070. memcpy(secret_out+i, hash, MIN(20, secret_bytes_out-i));
  1071. }
  1072. secret_len = secret_bytes_out;
  1073. goto done;
  1074. error:
  1075. secret_len = -1;
  1076. done:
  1077. if (pubkey_bn)
  1078. BN_free(pubkey_bn);
  1079. tor_free(secret_tmp);
  1080. return secret_len;
  1081. }
  1082. void crypto_dh_free(crypto_dh_env_t *dh)
  1083. {
  1084. assert(dh && dh->dh);
  1085. DH_free(dh->dh);
  1086. free(dh);
  1087. }
  1088. /* random numbers */
  1089. #ifdef MS_WINDOWS
  1090. int crypto_seed_rng()
  1091. {
  1092. static int provider_set = 0;
  1093. static HCRYPTPROV provider;
  1094. char buf[21];
  1095. if (!provider_set) {
  1096. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, 0)) {
  1097. if (GetLastError() != NTE_BAD_KEYSET) {
  1098. log_fn(LOG_ERR,"Can't get CryptoAPI provider [1]");
  1099. return -1;
  1100. }
  1101. /* Yes, we need to try it twice. */
  1102. if (!CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL,
  1103. CRYPT_NEWKEYSET)) {
  1104. log_fn(LOG_ERR,"Can't get CryptoAPI provider [2]");
  1105. return -1;
  1106. }
  1107. }
  1108. provider_set = 1;
  1109. }
  1110. if (!CryptGenRandom(provider, 20, buf)) {
  1111. log_fn(LOG_ERR,"Can't get entropy from CryptoAPI.");
  1112. return -1;
  1113. }
  1114. RAND_seed(buf, 20);
  1115. /* And add the current screen state to the entopy pool for
  1116. * good measure. */
  1117. RAND_screen();
  1118. return 0;
  1119. }
  1120. #else
  1121. int crypto_seed_rng()
  1122. {
  1123. static char *filenames[] = {
  1124. "/dev/srandom", "/dev/urandom", "/dev/random", NULL
  1125. };
  1126. int i, n;
  1127. char buf[21];
  1128. FILE *f;
  1129. for (i = 0; filenames[i]; ++i) {
  1130. f = fopen(filenames[i], "rb");
  1131. if (!f) continue;
  1132. log_fn(LOG_INFO, "Seeding RNG from %s", filenames[i]);
  1133. n = fread(buf, 1, 20, f);
  1134. fclose(f);
  1135. if (n != 20) {
  1136. log_fn(LOG_WARN, "Error reading from entropy source");
  1137. return -1;
  1138. }
  1139. RAND_seed(buf, 20);
  1140. return 0;
  1141. }
  1142. log_fn(LOG_WARN, "Cannot seed RNG -- no entropy source found.");
  1143. return -1;
  1144. }
  1145. #endif
  1146. int crypto_rand(unsigned int n, unsigned char *to)
  1147. {
  1148. assert(to);
  1149. return (RAND_bytes(to, n) != 1);
  1150. }
  1151. void crypto_pseudo_rand(unsigned int n, unsigned char *to)
  1152. {
  1153. assert(to);
  1154. if (RAND_pseudo_bytes(to, n) == -1) {
  1155. log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
  1156. exit(1);
  1157. }
  1158. }
  1159. /* return a pseudo random number between 0 and max-1 */
  1160. int crypto_pseudo_rand_int(unsigned int max) {
  1161. unsigned int val;
  1162. unsigned int cutoff;
  1163. assert(max < UINT_MAX);
  1164. assert(max > 0); /* don't div by 0 */
  1165. /* We ignore any values that are >= 'cutoff,' to avoid biasing the
  1166. * distribution with clipping at the upper end of unsigned int's
  1167. * range.
  1168. */
  1169. cutoff = UINT_MAX - (UINT_MAX%max);
  1170. while(1) {
  1171. crypto_pseudo_rand(sizeof(val), (unsigned char*) &val);
  1172. if (val < cutoff)
  1173. return val % max;
  1174. }
  1175. }
  1176. /* errors */
  1177. char *crypto_perror()
  1178. {
  1179. return (char *)ERR_reason_error_string(ERR_get_error());
  1180. }
  1181. int
  1182. base64_encode(char *dest, int destlen, const char *src, int srclen)
  1183. {
  1184. EVP_ENCODE_CTX ctx;
  1185. int len, ret;
  1186. /* 48 bytes of input -> 64 bytes of output plus newline.
  1187. Plus one more byte, in case I'm wrong.
  1188. */
  1189. if (destlen < ((srclen/48)+1)*66)
  1190. return -1;
  1191. EVP_EncodeInit(&ctx);
  1192. EVP_EncodeUpdate(&ctx, dest, &len, (char*) src, srclen);
  1193. EVP_EncodeFinal(&ctx, dest+len, &ret);
  1194. ret += len;
  1195. return ret;
  1196. }
  1197. int
  1198. base64_decode(char *dest, int destlen, const char *src, int srclen)
  1199. {
  1200. EVP_ENCODE_CTX ctx;
  1201. int len, ret;
  1202. /* 64 bytes of input -> *up to* 48 bytes of output.
  1203. Plus one more byte, in caes I'm wrong.
  1204. */
  1205. if (destlen < ((srclen/64)+1)*49)
  1206. return -1;
  1207. EVP_DecodeInit(&ctx);
  1208. EVP_DecodeUpdate(&ctx, dest, &len, (char*) src, srclen);
  1209. EVP_DecodeFinal(&ctx, dest, &ret);
  1210. ret += len;
  1211. return ret;
  1212. }
  1213. static const char BASE32_CHARS[] = "abcdefghijklmnopqrstuvwxyz012345";
  1214. int
  1215. base32_encode(char *dest, int destlen, const char *src, int srclen)
  1216. {
  1217. int nbits, i, bit, v, u;
  1218. nbits = srclen * 8;
  1219. if ((nbits%5) != 0)
  1220. /* We need an even multiple of 5 bits. */
  1221. return -1;
  1222. if ((nbits/5)+1 < destlen)
  1223. /* Not enough space. */
  1224. return -1;
  1225. for (i=0,bit=0; bit < nbits; ++i, bit+=5) {
  1226. /* set v to the 16-bit value starting at src[bits/8], 0-padded. */
  1227. v = ((unsigned char)src[bit/8]) << 8;
  1228. if (bit+5<nbits) v += src[(bit/8)+1];
  1229. /* set u to the 5-bit value at the bit'th bit of src. */
  1230. u = (v >> (11-(bit%8))) & 0x1F;
  1231. dest[i] = BASE32_CHARS[u];
  1232. }
  1233. dest[i] = '\0';
  1234. return 0;
  1235. }