2
0

bn_mpi.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <stdio.h>
  10. #include "internal/cryptlib.h"
  11. #include "bn_lcl.h"
  12. int BN_bn2mpi(const BIGNUM *a, unsigned char *d)
  13. {
  14. int bits;
  15. int num = 0;
  16. int ext = 0;
  17. long l;
  18. bits = BN_num_bits(a);
  19. num = (bits + 7) / 8;
  20. if (bits > 0) {
  21. ext = ((bits & 0x07) == 0);
  22. }
  23. if (d == NULL)
  24. return (num + 4 + ext);
  25. l = num + ext;
  26. d[0] = (unsigned char)(l >> 24) & 0xff;
  27. d[1] = (unsigned char)(l >> 16) & 0xff;
  28. d[2] = (unsigned char)(l >> 8) & 0xff;
  29. d[3] = (unsigned char)(l) & 0xff;
  30. if (ext)
  31. d[4] = 0;
  32. num = BN_bn2bin(a, &(d[4 + ext]));
  33. if (a->neg)
  34. d[4] |= 0x80;
  35. return (num + 4 + ext);
  36. }
  37. BIGNUM *BN_mpi2bn(const unsigned char *d, int n, BIGNUM *ain)
  38. {
  39. long len;
  40. int neg = 0;
  41. BIGNUM *a = NULL;
  42. if (n < 4) {
  43. BNerr(BN_F_BN_MPI2BN, BN_R_INVALID_LENGTH);
  44. return NULL;
  45. }
  46. len = ((long)d[0] << 24) | ((long)d[1] << 16) | ((int)d[2] << 8) | (int)
  47. d[3];
  48. if ((len + 4) != n) {
  49. BNerr(BN_F_BN_MPI2BN, BN_R_ENCODING_ERROR);
  50. return NULL;
  51. }
  52. if (ain == NULL)
  53. a = BN_new();
  54. else
  55. a = ain;
  56. if (a == NULL)
  57. return NULL;
  58. if (len == 0) {
  59. a->neg = 0;
  60. a->top = 0;
  61. return a;
  62. }
  63. d += 4;
  64. if ((*d) & 0x80)
  65. neg = 1;
  66. if (BN_bin2bn(d, (int)len, a) == NULL) {
  67. if (ain == NULL)
  68. BN_free(a);
  69. return NULL;
  70. }
  71. a->neg = neg;
  72. if (neg) {
  73. BN_clear_bit(a, BN_num_bits(a) - 1);
  74. }
  75. bn_check_top(a);
  76. return a;
  77. }