You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

506 line
12 KiB

  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 (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. m = 0;
  204. h = 0;
  205. while (j > 0) {
  206. m = ((BN_BYTES * 2) <= j) ? (BN_BYTES * 2) : j;
  207. l = 0;
  208. for (;;) {
  209. c = in[j - m];
  210. if ((c >= '0') && (c <= '9')) {
  211. k = c - '0';
  212. } else if ((c >= 'a') && (c <= 'f')) {
  213. k = c - 'a' + 10;
  214. } else if ((c >= 'A') && (c <= 'F')) {
  215. k = c - 'A' + 10;
  216. } else {
  217. k = 0; /* paranoia */
  218. }
  219. l = (l << 4) | k;
  220. if (--m <= 0) {
  221. bn->d[h++] = l;
  222. break;
  223. }
  224. }
  225. j -= (BN_BYTES * 2);
  226. }
  227. bn->top = h;
  228. }
  229. /* decode_dec decodes |i| bytes of decimal data from |in| and updates |bn|. */
  230. static void decode_dec(BIGNUM *bn, const char *in, int i) {
  231. int j;
  232. BN_ULONG l = 0;
  233. j = BN_DEC_NUM - (i % BN_DEC_NUM);
  234. if (j == BN_DEC_NUM) {
  235. j = 0;
  236. }
  237. l = 0;
  238. while (*in) {
  239. l *= 10;
  240. l += *in - '0';
  241. in++;
  242. if (++j == BN_DEC_NUM) {
  243. BN_mul_word(bn, BN_DEC_CONV);
  244. BN_add_word(bn, l);
  245. l = 0;
  246. j = 0;
  247. }
  248. }
  249. }
  250. typedef void (*decode_func) (BIGNUM *bn, const char *in, int i);
  251. typedef int (*char_test_func) (int c);
  252. static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) {
  253. BIGNUM *ret = NULL;
  254. int neg = 0, i;
  255. int num;
  256. if (in == NULL || *in == 0) {
  257. return 0;
  258. }
  259. if (*in == '-') {
  260. neg = 1;
  261. in++;
  262. }
  263. for (i = 0; want_char((unsigned char)in[i]); i++) {}
  264. num = i + neg;
  265. if (outp == NULL) {
  266. return num;
  267. }
  268. /* in is the start of the hex digits, and it is 'i' long */
  269. if (*outp == NULL) {
  270. ret = BN_new();
  271. if (ret == NULL) {
  272. return 0;
  273. }
  274. } else {
  275. ret = *outp;
  276. BN_zero(ret);
  277. }
  278. ret->neg = neg;
  279. /* i is the number of hex digests; */
  280. if (bn_expand(ret, i * 4) == NULL) {
  281. goto err;
  282. }
  283. decode(ret, in, i);
  284. bn_correct_top(ret);
  285. *outp = ret;
  286. return num;
  287. err:
  288. if (*outp == NULL) {
  289. BN_free(ret);
  290. }
  291. return 0;
  292. }
  293. int BN_hex2bn(BIGNUM **outp, const char *in) {
  294. return bn_x2bn(outp, in, decode_hex, isxdigit);
  295. }
  296. char *BN_bn2dec(const BIGNUM *a) {
  297. int i = 0, num, ok = 0;
  298. char *buf = NULL;
  299. char *p;
  300. BIGNUM *t = NULL;
  301. BN_ULONG *bn_data = NULL, *lp;
  302. /* get an upper bound for the length of the decimal integer
  303. * num <= (BN_num_bits(a) + 1) * log(2)
  304. * <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error)
  305. * <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
  306. */
  307. i = BN_num_bits(a) * 3;
  308. num = i / 10 + i / 1000 + 1 + 1;
  309. bn_data =
  310. (BN_ULONG *)OPENSSL_malloc((num / BN_DEC_NUM + 1) * sizeof(BN_ULONG));
  311. buf = (char *)OPENSSL_malloc(num + 3);
  312. if ((buf == NULL) || (bn_data == NULL)) {
  313. OPENSSL_PUT_ERROR(BN, BN_bn2dec, ERR_R_MALLOC_FAILURE);
  314. goto err;
  315. }
  316. t = BN_dup(a);
  317. if (t == NULL) {
  318. goto err;
  319. }
  320. #define BUF_REMAIN (num + 3 - (size_t)(p - buf))
  321. p = buf;
  322. lp = bn_data;
  323. if (BN_is_zero(t)) {
  324. *(p++) = '0';
  325. *(p++) = '\0';
  326. } else {
  327. if (BN_is_negative(t)) {
  328. *p++ = '-';
  329. }
  330. i = 0;
  331. while (!BN_is_zero(t)) {
  332. *lp = BN_div_word(t, BN_DEC_CONV);
  333. lp++;
  334. }
  335. lp--;
  336. /* We now have a series of blocks, BN_DEC_NUM chars
  337. * in length, where the last one needs truncation.
  338. * The blocks need to be reversed in order. */
  339. BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT1, *lp);
  340. while (*p) {
  341. p++;
  342. }
  343. while (lp != bn_data) {
  344. lp--;
  345. BIO_snprintf(p, BUF_REMAIN, BN_DEC_FMT2, *lp);
  346. while (*p) {
  347. p++;
  348. }
  349. }
  350. }
  351. ok = 1;
  352. err:
  353. if (bn_data != NULL) {
  354. OPENSSL_free(bn_data);
  355. }
  356. if (t != NULL) {
  357. BN_free(t);
  358. }
  359. if (!ok && buf) {
  360. OPENSSL_free(buf);
  361. buf = NULL;
  362. }
  363. return buf;
  364. }
  365. int BN_dec2bn(BIGNUM **outp, const char *in) {
  366. return bn_x2bn(outp, in, decode_dec, isdigit);
  367. }
  368. int BN_asc2bn(BIGNUM **outp, const char *in) {
  369. const char *const orig_in = in;
  370. if (*in == '-') {
  371. in++;
  372. }
  373. if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
  374. if (!BN_hex2bn(outp, in+2)) {
  375. return 0;
  376. }
  377. } else {
  378. if (!BN_dec2bn(outp, in)) {
  379. return 0;
  380. }
  381. }
  382. if (*orig_in == '-') {
  383. (*outp)->neg = 1;
  384. }
  385. return 1;
  386. }
  387. int BN_print(BIO *bp, const BIGNUM *a) {
  388. int i, j, v, z = 0;
  389. int ret = 0;
  390. if (a->neg && BIO_write(bp, "-", 1) != 1) {
  391. goto end;
  392. }
  393. if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
  394. goto end;
  395. }
  396. for (i = a->top - 1; i >= 0; i--) {
  397. for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
  398. /* strip leading zeros */
  399. v = ((int)(a->d[i] >> (long)j)) & 0x0f;
  400. if (z || v != 0) {
  401. if (BIO_write(bp, &hextable[v], 1) != 1) {
  402. goto end;
  403. }
  404. z = 1;
  405. }
  406. }
  407. }
  408. ret = 1;
  409. end:
  410. return ret;
  411. }
  412. int BN_print_fp(FILE *fp, const BIGNUM *a) {
  413. BIO *b;
  414. int ret;
  415. b = BIO_new(BIO_s_file());
  416. if (b == NULL) {
  417. return 0;
  418. }
  419. BIO_set_fp(b, fp, BIO_NOCLOSE);
  420. ret = BN_print(b, a);
  421. BIO_free(b);
  422. return ret;
  423. }
  424. BN_ULONG BN_get_word(const BIGNUM *bn) {
  425. switch (bn->top) {
  426. case 0:
  427. return 0;
  428. case 1:
  429. return bn->d[0];
  430. default:
  431. return BN_MASK2;
  432. }
  433. }