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.
 
 
 
 
 
 

502 lines
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 <string.h>
  60. #include <openssl/bio.h>
  61. #include <openssl/err.h>
  62. #include <openssl/mem.h>
  63. #include "internal.h"
  64. BIGNUM *BN_bin2bn(const uint8_t *in, size_t len, BIGNUM *ret) {
  65. unsigned num_words, m;
  66. BN_ULONG word = 0;
  67. BIGNUM *bn = NULL;
  68. if (ret == NULL) {
  69. ret = bn = BN_new();
  70. }
  71. if (ret == NULL) {
  72. return NULL;
  73. }
  74. if (len == 0) {
  75. ret->top = 0;
  76. return ret;
  77. }
  78. num_words = ((len - 1) / BN_BYTES) + 1;
  79. m = (len - 1) % BN_BYTES;
  80. if (bn_wexpand(ret, num_words) == NULL) {
  81. if (bn) {
  82. BN_free(bn);
  83. }
  84. return NULL;
  85. }
  86. ret->top = num_words;
  87. ret->neg = 0;
  88. while (len--) {
  89. word = (word << 8) | *(in++);
  90. if (m-- == 0) {
  91. ret->d[--num_words] = word;
  92. word = 0;
  93. m = BN_BYTES - 1;
  94. }
  95. }
  96. /* need to call this due to clear byte at top if avoiding having the top bit
  97. * set (-ve number) */
  98. bn_correct_top(ret);
  99. return ret;
  100. }
  101. size_t BN_bn2bin(const BIGNUM *in, uint8_t *out) {
  102. size_t n, i;
  103. BN_ULONG l;
  104. n = i = BN_num_bytes(in);
  105. while (i--) {
  106. l = in->d[i / BN_BYTES];
  107. *(out++) = (unsigned char)(l >> (8 * (i % BN_BYTES))) & 0xff;
  108. }
  109. return n;
  110. }
  111. /* constant_time_select_ulong returns |x| if |v| is 1 and |y| if |v| is 0. Its
  112. * behavior is undefined if |v| takes any other value. */
  113. static BN_ULONG constant_time_select_ulong(int v, BN_ULONG x, BN_ULONG y) {
  114. BN_ULONG mask = v;
  115. mask--;
  116. return (~mask & x) | (mask & y);
  117. }
  118. /* constant_time_le_size_t returns 1 if |x| <= |y| and 0 otherwise. |x| and |y|
  119. * must not have their MSBs set. */
  120. static int constant_time_le_size_t(size_t x, size_t y) {
  121. return ((x - y - 1) >> (sizeof(size_t) * 8 - 1)) & 1;
  122. }
  123. /* read_word_padded returns the |i|'th word of |in|, if it is not out of
  124. * bounds. Otherwise, it returns 0. It does so without branches on the size of
  125. * |in|, however it necessarily does not have the same memory access pattern. If
  126. * the access would be out of bounds, it reads the last word of |in|. |in| must
  127. * not be zero. */
  128. static BN_ULONG read_word_padded(const BIGNUM *in, size_t i) {
  129. /* Read |in->d[i]| if valid. Otherwise, read the last word. */
  130. BN_ULONG l = in->d[constant_time_select_ulong(
  131. constant_time_le_size_t(in->dmax, i), in->dmax - 1, i)];
  132. /* Clamp to zero if above |d->top|. */
  133. return constant_time_select_ulong(constant_time_le_size_t(in->top, i), 0, l);
  134. }
  135. int BN_bn2bin_padded(uint8_t *out, size_t len, const BIGNUM *in) {
  136. size_t i;
  137. BN_ULONG l;
  138. /* Special case for |in| = 0. Just branch as the probability is negligible. */
  139. if (BN_is_zero(in)) {
  140. memset(out, 0, len);
  141. return 1;
  142. }
  143. /* Check if the integer is too big. This case can exit early in non-constant
  144. * time. */
  145. if ((size_t)in->top > (len + (BN_BYTES - 1)) / BN_BYTES) {
  146. return 0;
  147. }
  148. if ((len % BN_BYTES) != 0) {
  149. l = read_word_padded(in, len / BN_BYTES);
  150. if (l >> (8 * (len % BN_BYTES)) != 0) {
  151. return 0;
  152. }
  153. }
  154. /* Write the bytes out one by one. Serialization is done without branching on
  155. * the bits of |in| or on |in->top|, but if the routine would otherwise read
  156. * out of bounds, the memory access pattern can't be fixed. However, for an
  157. * RSA key of size a multiple of the word size, the probability of BN_BYTES
  158. * leading zero octets is low.
  159. *
  160. * See Falko Stenzke, "Manger's Attack revisited", ICICS 2010. */
  161. i = len;
  162. while (i--) {
  163. l = read_word_padded(in, i / BN_BYTES);
  164. *(out++) = (uint8_t)(l >> (8 * (i % BN_BYTES))) & 0xff;
  165. }
  166. return 1;
  167. }
  168. static const char hextable[] = "0123456789abcdef";
  169. char *BN_bn2hex(const BIGNUM *bn) {
  170. int i, j, v, z = 0;
  171. char *buf;
  172. char *p;
  173. buf = (char *)OPENSSL_malloc(bn->top * BN_BYTES * 2 + 2);
  174. if (buf == NULL) {
  175. OPENSSL_PUT_ERROR(BN, BN_bn2hex, ERR_R_MALLOC_FAILURE);
  176. return NULL;
  177. }
  178. p = buf;
  179. if (bn->neg) {
  180. *(p++) = '-';
  181. }
  182. if (BN_is_zero(bn)) {
  183. *(p++) = '0';
  184. }
  185. for (i = bn->top - 1; i >= 0; i--) {
  186. for (j = BN_BITS2 - 8; j >= 0; j -= 8) {
  187. /* strip leading zeros */
  188. v = ((int)(bn->d[i] >> (long)j)) & 0xff;
  189. if (z || v != 0) {
  190. *(p++) = hextable[v >> 4];
  191. *(p++) = hextable[v & 0x0f];
  192. z = 1;
  193. }
  194. }
  195. }
  196. *p = '\0';
  197. return buf;
  198. }
  199. /* decode_hex decodes |i| bytes of hex data from |in| and updates |bn|. */
  200. static void decode_hex(BIGNUM *bn, const char *in, int i) {
  201. int h, m, j, k, c;
  202. BN_ULONG l=0;
  203. j = i; /* least significant 'hex' */
  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 |in_len| bytes of decimal data from |in| and updates |bn|. */
  230. static void decode_dec(BIGNUM *bn, const char *in, int in_len) {
  231. int i, j;
  232. BN_ULONG l = 0;
  233. j = BN_DEC_NUM - (in_len % BN_DEC_NUM);
  234. if (j == BN_DEC_NUM) {
  235. j = 0;
  236. }
  237. l = 0;
  238. for (i = 0; i < in_len; i++) {
  239. l *= 10;
  240. l += in[i] - '0';
  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. /* i is the number of hex digests; */
  278. if (bn_expand(ret, i * 4) == NULL) {
  279. goto err;
  280. }
  281. decode(ret, in, i);
  282. bn_correct_top(ret);
  283. if (!BN_is_zero(ret)) {
  284. ret->neg = neg;
  285. }
  286. *outp = ret;
  287. return num;
  288. err:
  289. if (*outp == NULL) {
  290. BN_free(ret);
  291. }
  292. return 0;
  293. }
  294. int BN_hex2bn(BIGNUM **outp, const char *in) {
  295. return bn_x2bn(outp, in, decode_hex, isxdigit);
  296. }
  297. char *BN_bn2dec(const BIGNUM *a) {
  298. int i = 0, num, ok = 0;
  299. char *buf = NULL;
  300. char *p;
  301. BIGNUM *t = NULL;
  302. BN_ULONG *bn_data = NULL, *lp;
  303. /* get an upper bound for the length of the decimal integer
  304. * num <= (BN_num_bits(a) + 1) * log(2)
  305. * <= 3 * BN_num_bits(a) * 0.1001 + log(2) + 1 (rounding error)
  306. * <= BN_num_bits(a)/10 + BN_num_bits/1000 + 1 + 1
  307. */
  308. i = BN_num_bits(a) * 3;
  309. num = i / 10 + i / 1000 + 1 + 1;
  310. bn_data =
  311. (BN_ULONG *)OPENSSL_malloc((num / BN_DEC_NUM + 1) * sizeof(BN_ULONG));
  312. buf = (char *)OPENSSL_malloc(num + 3);
  313. if ((buf == NULL) || (bn_data == NULL)) {
  314. OPENSSL_PUT_ERROR(BN, BN_bn2dec, ERR_R_MALLOC_FAILURE);
  315. goto err;
  316. }
  317. t = BN_dup(a);
  318. if (t == NULL) {
  319. goto err;
  320. }
  321. #define BUF_REMAIN (num + 3 - (size_t)(p - buf))
  322. p = buf;
  323. lp = bn_data;
  324. if (BN_is_zero(t)) {
  325. *(p++) = '0';
  326. *(p++) = '\0';
  327. } else {
  328. if (BN_is_negative(t)) {
  329. *p++ = '-';
  330. }
  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. OPENSSL_free(bn_data);
  354. BN_free(t);
  355. if (!ok) {
  356. OPENSSL_free(buf);
  357. buf = NULL;
  358. }
  359. return buf;
  360. }
  361. int BN_dec2bn(BIGNUM **outp, const char *in) {
  362. return bn_x2bn(outp, in, decode_dec, isdigit);
  363. }
  364. int BN_asc2bn(BIGNUM **outp, const char *in) {
  365. const char *const orig_in = in;
  366. if (*in == '-') {
  367. in++;
  368. }
  369. if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
  370. if (!BN_hex2bn(outp, in+2)) {
  371. return 0;
  372. }
  373. } else {
  374. if (!BN_dec2bn(outp, in)) {
  375. return 0;
  376. }
  377. }
  378. if (*orig_in == '-' && !BN_is_zero(*outp)) {
  379. (*outp)->neg = 1;
  380. }
  381. return 1;
  382. }
  383. int BN_print(BIO *bp, const BIGNUM *a) {
  384. int i, j, v, z = 0;
  385. int ret = 0;
  386. if (a->neg && BIO_write(bp, "-", 1) != 1) {
  387. goto end;
  388. }
  389. if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
  390. goto end;
  391. }
  392. for (i = a->top - 1; i >= 0; i--) {
  393. for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
  394. /* strip leading zeros */
  395. v = ((int)(a->d[i] >> (long)j)) & 0x0f;
  396. if (z || v != 0) {
  397. if (BIO_write(bp, &hextable[v], 1) != 1) {
  398. goto end;
  399. }
  400. z = 1;
  401. }
  402. }
  403. }
  404. ret = 1;
  405. end:
  406. return ret;
  407. }
  408. int BN_print_fp(FILE *fp, const BIGNUM *a) {
  409. BIO *b;
  410. int ret;
  411. b = BIO_new(BIO_s_file());
  412. if (b == NULL) {
  413. return 0;
  414. }
  415. BIO_set_fp(b, fp, BIO_NOCLOSE);
  416. ret = BN_print(b, a);
  417. BIO_free(b);
  418. return ret;
  419. }
  420. BN_ULONG BN_get_word(const BIGNUM *bn) {
  421. switch (bn->top) {
  422. case 0:
  423. return 0;
  424. case 1:
  425. return bn->d[0];
  426. default:
  427. return BN_MASK2;
  428. }
  429. }