25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

convert.c 12 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.] */
  56. #include <openssl/bn.h>
  57. #include <ctype.h>
  58. #include <stdio.h>
  59. #include <openssl/bio.h>
  60. #include <openssl/err.h>
  61. #include <openssl/mem.h>
  62. #include "internal.h"
  63. BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) {
  64. unsigned num_words, m;
  65. BN_ULONG word = 0;
  66. BIGNUM *bn = NULL;
  67. if (ret == NULL) {
  68. ret = bn = BN_new();
  69. }
  70. if (ret == NULL) {
  71. return NULL;
  72. }
  73. if (len == 0) {
  74. ret->top = 0;
  75. return ret;
  76. }
  77. num_words = ((len - 1) / BN_BYTES) + 1;
  78. m = (len - 1) % BN_BYTES;
  79. if (bn_wexpand(ret, num_words) == NULL) {
  80. if (bn) {
  81. BN_free(bn);
  82. }
  83. return NULL;
  84. }
  85. ret->top = num_words;
  86. ret->neg = 0;
  87. while (len--) {
  88. word = (word << 8) | *(in++);
  89. if (m-- == 0) {
  90. ret->d[--num_words] = word;
  91. word = 0;
  92. m = BN_BYTES - 1;
  93. }
  94. }
  95. /* need to call this due to clear byte at top if avoiding having the top bit
  96. * set (-ve number) */
  97. bn_correct_top(ret);
  98. return ret;
  99. }
  100. size_t BN_bn2bin(const BIGNUM *in, uint8_t *out) {
  101. size_t n, i;
  102. BN_ULONG l;
  103. n = i = BN_num_bytes(in);
  104. while (i--) {
  105. l = in->d[i / BN_BYTES];
  106. *(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
  107. }
  108. return n;
  109. }
  110. /* constant_time_select_ulong returns |x| if |v| is 1 and |y| if |v| is 0. Its
  111. * behavior is undefined if |v| takes any other value. */
  112. static BN_ULONG constant_time_select_ulong(int v, BN_ULONG x, BN_ULONG y) {
  113. BN_ULONG mask = v;
  114. mask--;
  115. return (~mask & x) | (mask & y);
  116. }
  117. /* constant_time_le_size_t returns 1 if |x| <= |y| and 0 otherwise. |x| and |y|
  118. * must not have their MSBs set. */
  119. static int constant_time_le_size_t(size_t x, size_t y) {
  120. return ((x - y - 1) >> (sizeof(size_t) * 8 - 1)) & 1;
  121. }
  122. /* read_word_padded returns the |i|'th word of |in|, if it is not out of
  123. * bounds. Otherwise, it returns 0. It does so without branches on the size of
  124. * |in|, however it necessarily does not have the same memory access pattern. If
  125. * the access would be out of bounds, it reads the last word of |in|. |in| must
  126. * not be zero. */
  127. static BN_ULONG read_word_padded(const BIGNUM *in, size_t i) {
  128. /* Read |in->d[i]| if valid. Otherwise, read the last word. */
  129. BN_ULONG l = in->d[constant_time_select_ulong(
  130. constant_time_le_size_t(in->dmax, i), in->dmax - 1, i)];
  131. /* Clamp to zero if above |d->top|. */
  132. return constant_time_select_ulong(constant_time_le_size_t(in->top, i), 0, l);
  133. }
  134. int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) {
  135. size_t i;
  136. BN_ULONG l;
  137. /* Special case for |in| = 0. Just branch as the probability is negligible. */
  138. if (BN_is_zero(in)) {
  139. memset(out, 0, len);
  140. return 1;
  141. }
  142. /* Check if the integer is too big. This case can exit early in non-constant
  143. * time. */
  144. if ((size_t)in->top > (len + (BN_BYTES - 1)) / BN_BYTES) {
  145. return 0;
  146. }
  147. if ((len % BN_BYTES) != 0) {
  148. l = read_word_padded(in, len / BN_BYTES);
  149. if (l >> (8 * (len % BN_BYTES)) != 0) {
  150. return 0;
  151. }
  152. }
  153. /* Write the bytes out one by one. Serialization is done without branching on
  154. * the bits of |in| or on |in->top|, but if the routine would otherwise read
  155. * out of bounds, the memory access pattern can't be fixed. However, for an
  156. * RSA key of size a multiple of the word size, the probability of BN_BYTES
  157. * leading zero octets is low.
  158. *
  159. * See Falko Stenzke, "Manger's Attack revisited", ICICS 2010. */
  160. i = len;
  161. while (i--) {
  162. l = read_word_padded(in, i / BN_BYTES);
  163. *(out++) = (uint8_t)(l >> (8 * (i % BN_BYTES))) & 0xff;
  164. }
  165. return 1;
  166. }
  167. static const char hextable[] = "0123456789abcdef";
  168. char *BN_bn2hex(const BIGNUM *bn) {
  169. int i, j, v, z = 0;
  170. char *buf;
  171. char *p;
  172. buf = (char *)OPENSSL_malloc(bn->top * BN_BYTES * 2 + 2);
  173. if (buf == NULL) {
  174. OPENSSL_PUT_ERROR(BN, BN_bn2hex, ERR_R_MALLOC_FAILURE);
  175. return NULL;
  176. }
  177. p = buf;
  178. if (bn->neg) {
  179. *(p++) = '-';
  180. }
  181. if (BN_is_zero(bn)) {
  182. *(p++) = '0';
  183. }
  184. for (i = bn->top - 1; i >= 0; i--) {
  185. for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
  186. /* strip leading zeros */
  187. v = ((int)(bn->d[i] >> (long)j)) & 0xff;
  188. if (z || v != 0) {
  189. *(p++) = hextable[v >> 4];
  190. *(p++) = hextable[v & 0x0f];
  191. z = 1;
  192. }
  193. }
  194. }
  195. *p = '\0';
  196. return buf;
  197. }
  198. /* decode_hex decodes |i| bytes of hex data from |in| and updates |bn|. */
  199. static void decode_hex(BIGNUM *bn, const char *in, int i) {
  200. int h, m, j, k, c;
  201. BN_ULONG l=0;
  202. j = i; /* least significant 'hex' */
  203. h = 0;
  204. while (j > 0) {
  205. m = ((BN_BYTES * 2) <= j) ? (BN_BYTES * 2) : j;
  206. l = 0;
  207. for (;;) {
  208. c = in[j - m];
  209. if ((c >= '0') && (c <= '9')) {
  210. k = c - '0';
  211. } else if ((c >= 'a') && (c <= 'f')) {
  212. k = c - 'a' + 10;
  213. } else if ((c >= 'A') && (c <= 'F')) {
  214. k = c - 'A' + 10;
  215. } else {
  216. k = 0; /* paranoia */
  217. }
  218. l = (l << 4) | k;
  219. if (--m <= 0) {
  220. bn->d[h++] = l;
  221. break;
  222. }
  223. }
  224. j -= (BN_BYTES * 2);
  225. }
  226. bn->top = h;
  227. }
  228. /* decode_dec decodes |i| bytes of decimal data from |in| and updates |bn|. */
  229. static void decode_dec(BIGNUM *bn, const char *in, int i) {
  230. int j;
  231. BN_ULONG l = 0;
  232. j = BN_DEC_NUM - (i % BN_DEC_NUM);
  233. if (j == BN_DEC_NUM) {
  234. j = 0;
  235. }
  236. l = 0;
  237. while (*in) {
  238. l *= 10;
  239. l += *in - '0';
  240. in++;
  241. if (++j == BN_DEC_NUM) {
  242. BN_mul_word(bn, BN_DEC_CONV);
  243. BN_add_word(bn, l);
  244. l = 0;
  245. j = 0;
  246. }
  247. }
  248. }
  249. typedef void (*decode_func) (BIGNUM *bn, const char *in, int i);
  250. typedef int (*char_test_func) (int c);
  251. static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) {
  252. BIGNUM *ret = NULL;
  253. int neg = 0, i;
  254. int num;
  255. if (in == NULL || *in == 0) {
  256. return 0;
  257. }
  258. if (*in == '-') {
  259. neg = 1;
  260. in++;
  261. }
  262. for (i = 0; want_char((unsigned char)in[i]); i++) {}
  263. num = i + neg;
  264. if (outp == NULL) {
  265. return num;
  266. }
  267. /* in is the start of the hex digits, and it is 'i' long */
  268. if (*outp == NULL) {
  269. ret = BN_new();
  270. if (ret == NULL) {
  271. return 0;
  272. }
  273. } else {
  274. ret = *outp;
  275. BN_zero(ret);
  276. }
  277. ret->neg = neg;
  278. /* i is the number of hex digests; */
  279. if (bn_expand(ret, i * 4) == NULL) {
  280. goto err;
  281. }
  282. decode(ret, in, i);
  283. bn_correct_top(ret);
  284. *outp = ret;
  285. return num;
  286. err:
  287. if (*outp == NULL) {
  288. BN_free(ret);
  289. }
  290. return 0;
  291. }
  292. int BN_hex2bn(BIGNUM **outp, const char *in) {
  293. return bn_x2bn(outp, in, decode_hex, isxdigit);
  294. }
  295. char *BN_bn2dec(const BIGNUM *a) {
  296. int i = 0, num, ok = 0;
  297. char *buf = NULL;
  298. char *p;
  299. BIGNUM *t = NULL;
  300. BN_ULONG *bn_data = NULL, *lp;
  301. /* get an upper bound for the length of the decimal integer
  302. * num <= (BN_num_bits(a) + 1) * log(2)
  303. * <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error)
  304. * <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
  305. */
  306. i = BN_num_bits(a) * 3;
  307. num = i / 10 + i / 1000 + 1 + 1;
  308. bn_data =
  309. (BN_ULONG *)OPENSSL_malloc((num / BN_DEC_NUM + 1) * sizeof(BN_ULONG));
  310. buf = (char *)OPENSSL_malloc(num + 3);
  311. if ((buf == NULL) || (bn_data == NULL)) {
  312. OPENSSL_PUT_ERROR(BN, BN_bn2dec, ERR_R_MALLOC_FAILURE);
  313. goto err;
  314. }
  315. t = BN_dup(a);
  316. if (t == NULL) {
  317. goto err;
  318. }
  319. #define BUF_REMAIN (num + 3 - (size_t)(p - buf))
  320. p = buf;
  321. lp = bn_data;
  322. if (BN_is_zero(t)) {
  323. *(p++) = '0';
  324. *(p++) = '\0';
  325. } else {
  326. if (BN_is_negative(t)) {
  327. *p++ = '-';
  328. }
  329. while (!BN_is_zero(t)) {
  330. *lp = BN_div_word(t, BN_DEC_CONV);
  331. lp++;
  332. }
  333. lp--;
  334. /* We now have a series of blocks, BN_DEC_NUM chars
  335. * in length, where the last one needs truncation.
  336. * The blocks need to be reversed in order. */
  337. BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
  338. while (*p) {
  339. p++;
  340. }
  341. while (lp != bn_data) {
  342. lp--;
  343. BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
  344. while (*p) {
  345. p++;
  346. }
  347. }
  348. }
  349. ok = 1;
  350. err:
  351. if (bn_data != NULL) {
  352. OPENSSL_free(bn_data);
  353. }
  354. if (t != NULL) {
  355. BN_free(t);
  356. }
  357. if (!ok && buf) {
  358. OPENSSL_free(buf);
  359. buf = NULL;
  360. }
  361. return buf;
  362. }
  363. int BN_dec2bn(BIGNUM **outp, const char *in) {
  364. return bn_x2bn(outp, in, decode_dec, isdigit);
  365. }
  366. int BN_asc2bn(BIGNUM **outp, const char *in) {
  367. const char *const orig_in = in;
  368. if (*in == '-') {
  369. in++;
  370. }
  371. if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
  372. if (!BN_hex2bn(outp, in+2)) {
  373. return 0;
  374. }
  375. } else {
  376. if (!BN_dec2bn(outp, in)) {
  377. return 0;
  378. }
  379. }
  380. if (*orig_in == '-') {
  381. (*outp)->neg = 1;
  382. }
  383. return 1;
  384. }
  385. int BN_print(BIO *bp, const BIGNUM *a) {
  386. int i, j, v, z = 0;
  387. int ret = 0;
  388. if (a->neg && BIO_write(bp, "-", 1) != 1) {
  389. goto end;
  390. }
  391. if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
  392. goto end;
  393. }
  394. for (i = a->top - 1; i >= 0; i--) {
  395. for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
  396. /* strip leading zeros */
  397. v = ((int)(a->d[i] >> (long)j)) & 0x0f;
  398. if (z || v != 0) {
  399. if (BIO_write(bp, &hextable[v], 1) != 1) {
  400. goto end;
  401. }
  402. z = 1;
  403. }
  404. }
  405. }
  406. ret = 1;
  407. end:
  408. return ret;
  409. }
  410. int BN_print_fp(FILE *fp, const BIGNUM *a) {
  411. BIO *b;
  412. int ret;
  413. b = BIO_new(BIO_s_file());
  414. if (b == NULL) {
  415. return 0;
  416. }
  417. BIO_set_fp(b, fp, BIO_NOCLOSE);
  418. ret = BN_print(b, a);
  419. BIO_free(b);
  420. return ret;
  421. }
  422. BN_ULONG BN_get_word(const BIGNUM *bn) {
  423. switch (bn->top) {
  424. case 0:
  425. return 0;
  426. case 1:
  427. return bn->d[0];
  428. default:
  429. return BN_MASK2;
  430. }
  431. }