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.
 
 
 
 
 
 

466 lines
11 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 <assert.h>
  58. #include <ctype.h>
  59. #include <limits.h>
  60. #include <stdio.h>
  61. #include <openssl/bio.h>
  62. #include <openssl/bytestring.h>
  63. #include <openssl/err.h>
  64. #include <openssl/mem.h>
  65. #include "../fipsmodule/bn/internal.h"
  66. int BN_bn2cbb_padded(CBB *out, size_t len, const BIGNUM *in) {
  67. uint8_t *ptr;
  68. return CBB_add_space(out, &ptr, len) && BN_bn2bin_padded(ptr, len, in);
  69. }
  70. static const char hextable[] = "0123456789abcdef";
  71. char *BN_bn2hex(const BIGNUM *bn) {
  72. char *buf = OPENSSL_malloc(1 /* leading '-' */ + 1 /* zero is non-empty */ +
  73. bn->top * BN_BYTES * 2 + 1 /* trailing NUL */);
  74. if (buf == NULL) {
  75. OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
  76. return NULL;
  77. }
  78. char *p = buf;
  79. if (bn->neg) {
  80. *(p++) = '-';
  81. }
  82. if (BN_is_zero(bn)) {
  83. *(p++) = '0';
  84. }
  85. int z = 0;
  86. for (int i = bn->top - 1; i >= 0; i--) {
  87. for (int j = BN_BITS2 - 8; j >= 0; j -= 8) {
  88. // strip leading zeros
  89. int v = ((int)(bn->d[i] >> (long)j)) & 0xff;
  90. if (z || v != 0) {
  91. *(p++) = hextable[v >> 4];
  92. *(p++) = hextable[v & 0x0f];
  93. z = 1;
  94. }
  95. }
  96. }
  97. *p = '\0';
  98. return buf;
  99. }
  100. // decode_hex decodes |in_len| bytes of hex data from |in| and updates |bn|.
  101. static int decode_hex(BIGNUM *bn, const char *in, int in_len) {
  102. if (in_len > INT_MAX/4) {
  103. OPENSSL_PUT_ERROR(BN, BN_R_BIGNUM_TOO_LONG);
  104. return 0;
  105. }
  106. // |in_len| is the number of hex digits.
  107. if (!bn_expand(bn, in_len * 4)) {
  108. return 0;
  109. }
  110. int i = 0;
  111. while (in_len > 0) {
  112. // Decode one |BN_ULONG| at a time.
  113. int todo = BN_BYTES * 2;
  114. if (todo > in_len) {
  115. todo = in_len;
  116. }
  117. BN_ULONG word = 0;
  118. int j;
  119. for (j = todo; j > 0; j--) {
  120. char c = in[in_len - j];
  121. BN_ULONG hex;
  122. if (c >= '0' && c <= '9') {
  123. hex = c - '0';
  124. } else if (c >= 'a' && c <= 'f') {
  125. hex = c - 'a' + 10;
  126. } else if (c >= 'A' && c <= 'F') {
  127. hex = c - 'A' + 10;
  128. } else {
  129. hex = 0;
  130. // This shouldn't happen. The caller checks |isxdigit|.
  131. assert(0);
  132. }
  133. word = (word << 4) | hex;
  134. }
  135. bn->d[i++] = word;
  136. in_len -= todo;
  137. }
  138. assert(i <= bn->dmax);
  139. bn->top = i;
  140. return 1;
  141. }
  142. // decode_dec decodes |in_len| bytes of decimal data from |in| and updates |bn|.
  143. static int decode_dec(BIGNUM *bn, const char *in, int in_len) {
  144. int i, j;
  145. BN_ULONG l = 0;
  146. // Decode |BN_DEC_NUM| digits at a time.
  147. j = BN_DEC_NUM - (in_len % BN_DEC_NUM);
  148. if (j == BN_DEC_NUM) {
  149. j = 0;
  150. }
  151. l = 0;
  152. for (i = 0; i < in_len; i++) {
  153. l *= 10;
  154. l += in[i] - '0';
  155. if (++j == BN_DEC_NUM) {
  156. if (!BN_mul_word(bn, BN_DEC_CONV) ||
  157. !BN_add_word(bn, l)) {
  158. return 0;
  159. }
  160. l = 0;
  161. j = 0;
  162. }
  163. }
  164. return 1;
  165. }
  166. typedef int (*decode_func) (BIGNUM *bn, const char *in, int in_len);
  167. typedef int (*char_test_func) (int c);
  168. static int bn_x2bn(BIGNUM **outp, const char *in, decode_func decode, char_test_func want_char) {
  169. BIGNUM *ret = NULL;
  170. int neg = 0, i;
  171. int num;
  172. if (in == NULL || *in == 0) {
  173. return 0;
  174. }
  175. if (*in == '-') {
  176. neg = 1;
  177. in++;
  178. }
  179. for (i = 0; want_char((unsigned char)in[i]) && i + neg < INT_MAX; i++) {}
  180. num = i + neg;
  181. if (outp == NULL) {
  182. return num;
  183. }
  184. // in is the start of the hex digits, and it is 'i' long
  185. if (*outp == NULL) {
  186. ret = BN_new();
  187. if (ret == NULL) {
  188. return 0;
  189. }
  190. } else {
  191. ret = *outp;
  192. BN_zero(ret);
  193. }
  194. if (!decode(ret, in, i)) {
  195. goto err;
  196. }
  197. bn_correct_top(ret);
  198. if (!BN_is_zero(ret)) {
  199. ret->neg = neg;
  200. }
  201. *outp = ret;
  202. return num;
  203. err:
  204. if (*outp == NULL) {
  205. BN_free(ret);
  206. }
  207. return 0;
  208. }
  209. int BN_hex2bn(BIGNUM **outp, const char *in) {
  210. return bn_x2bn(outp, in, decode_hex, isxdigit);
  211. }
  212. char *BN_bn2dec(const BIGNUM *a) {
  213. // It is easier to print strings little-endian, so we assemble it in reverse
  214. // and fix at the end.
  215. BIGNUM *copy = NULL;
  216. CBB cbb;
  217. if (!CBB_init(&cbb, 16) ||
  218. !CBB_add_u8(&cbb, 0 /* trailing NUL */)) {
  219. goto cbb_err;
  220. }
  221. if (BN_is_zero(a)) {
  222. if (!CBB_add_u8(&cbb, '0')) {
  223. goto cbb_err;
  224. }
  225. } else {
  226. copy = BN_dup(a);
  227. if (copy == NULL) {
  228. goto err;
  229. }
  230. while (!BN_is_zero(copy)) {
  231. BN_ULONG word = BN_div_word(copy, BN_DEC_CONV);
  232. if (word == (BN_ULONG)-1) {
  233. goto err;
  234. }
  235. const int add_leading_zeros = !BN_is_zero(copy);
  236. for (int i = 0; i < BN_DEC_NUM && (add_leading_zeros || word != 0); i++) {
  237. if (!CBB_add_u8(&cbb, '0' + word % 10)) {
  238. goto cbb_err;
  239. }
  240. word /= 10;
  241. }
  242. assert(word == 0);
  243. }
  244. }
  245. if (BN_is_negative(a) &&
  246. !CBB_add_u8(&cbb, '-')) {
  247. goto cbb_err;
  248. }
  249. uint8_t *data;
  250. size_t len;
  251. if (!CBB_finish(&cbb, &data, &len)) {
  252. goto cbb_err;
  253. }
  254. // Reverse the buffer.
  255. for (size_t i = 0; i < len/2; i++) {
  256. uint8_t tmp = data[i];
  257. data[i] = data[len - 1 - i];
  258. data[len - 1 - i] = tmp;
  259. }
  260. BN_free(copy);
  261. return (char *)data;
  262. cbb_err:
  263. OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
  264. err:
  265. BN_free(copy);
  266. CBB_cleanup(&cbb);
  267. return NULL;
  268. }
  269. int BN_dec2bn(BIGNUM **outp, const char *in) {
  270. return bn_x2bn(outp, in, decode_dec, isdigit);
  271. }
  272. int BN_asc2bn(BIGNUM **outp, const char *in) {
  273. const char *const orig_in = in;
  274. if (*in == '-') {
  275. in++;
  276. }
  277. if (in[0] == '0' && (in[1] == 'X' || in[1] == 'x')) {
  278. if (!BN_hex2bn(outp, in+2)) {
  279. return 0;
  280. }
  281. } else {
  282. if (!BN_dec2bn(outp, in)) {
  283. return 0;
  284. }
  285. }
  286. if (*orig_in == '-' && !BN_is_zero(*outp)) {
  287. (*outp)->neg = 1;
  288. }
  289. return 1;
  290. }
  291. int BN_print(BIO *bp, const BIGNUM *a) {
  292. int i, j, v, z = 0;
  293. int ret = 0;
  294. if (a->neg && BIO_write(bp, "-", 1) != 1) {
  295. goto end;
  296. }
  297. if (BN_is_zero(a) && BIO_write(bp, "0", 1) != 1) {
  298. goto end;
  299. }
  300. for (i = a->top - 1; i >= 0; i--) {
  301. for (j = BN_BITS2 - 4; j >= 0; j -= 4) {
  302. // strip leading zeros
  303. v = ((int)(a->d[i] >> (long)j)) & 0x0f;
  304. if (z || v != 0) {
  305. if (BIO_write(bp, &hextable[v], 1) != 1) {
  306. goto end;
  307. }
  308. z = 1;
  309. }
  310. }
  311. }
  312. ret = 1;
  313. end:
  314. return ret;
  315. }
  316. int BN_print_fp(FILE *fp, const BIGNUM *a) {
  317. BIO *b;
  318. int ret;
  319. b = BIO_new(BIO_s_file());
  320. if (b == NULL) {
  321. return 0;
  322. }
  323. BIO_set_fp(b, fp, BIO_NOCLOSE);
  324. ret = BN_print(b, a);
  325. BIO_free(b);
  326. return ret;
  327. }
  328. size_t BN_bn2mpi(const BIGNUM *in, uint8_t *out) {
  329. const size_t bits = BN_num_bits(in);
  330. const size_t bytes = (bits + 7) / 8;
  331. // If the number of bits is a multiple of 8, i.e. if the MSB is set,
  332. // prefix with a zero byte.
  333. int extend = 0;
  334. if (bytes != 0 && (bits & 0x07) == 0) {
  335. extend = 1;
  336. }
  337. const size_t len = bytes + extend;
  338. if (len < bytes ||
  339. 4 + len < len ||
  340. (len & 0xffffffff) != len) {
  341. // If we cannot represent the number then we emit zero as the interface
  342. // doesn't allow an error to be signalled.
  343. if (out) {
  344. OPENSSL_memset(out, 0, 4);
  345. }
  346. return 4;
  347. }
  348. if (out == NULL) {
  349. return 4 + len;
  350. }
  351. out[0] = len >> 24;
  352. out[1] = len >> 16;
  353. out[2] = len >> 8;
  354. out[3] = len;
  355. if (extend) {
  356. out[4] = 0;
  357. }
  358. BN_bn2bin(in, out + 4 + extend);
  359. if (in->neg && len > 0) {
  360. out[4] |= 0x80;
  361. }
  362. return len + 4;
  363. }
  364. BIGNUM *BN_mpi2bn(const uint8_t *in, size_t len, BIGNUM *out) {
  365. if (len < 4) {
  366. OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
  367. return NULL;
  368. }
  369. const size_t in_len = ((size_t)in[0] << 24) |
  370. ((size_t)in[1] << 16) |
  371. ((size_t)in[2] << 8) |
  372. ((size_t)in[3]);
  373. if (in_len != len - 4) {
  374. OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
  375. return NULL;
  376. }
  377. int out_is_alloced = 0;
  378. if (out == NULL) {
  379. out = BN_new();
  380. if (out == NULL) {
  381. OPENSSL_PUT_ERROR(BN, ERR_R_MALLOC_FAILURE);
  382. return NULL;
  383. }
  384. out_is_alloced = 1;
  385. }
  386. if (in_len == 0) {
  387. BN_zero(out);
  388. return out;
  389. }
  390. in += 4;
  391. if (BN_bin2bn(in, in_len, out) == NULL) {
  392. if (out_is_alloced) {
  393. BN_free(out);
  394. }
  395. return NULL;
  396. }
  397. out->neg = ((*in) & 0x80) != 0;
  398. if (out->neg) {
  399. BN_clear_bit(out, BN_num_bits(out) - 1);
  400. }
  401. return out;
  402. }