t_pkey.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 <openssl/objects.h>
  12. #include <openssl/buffer.h>
  13. #include "internal/bn_int.h"
  14. /* Number of octets per line */
  15. #define ASN1_BUF_PRINT_WIDTH 15
  16. /* Maximum indent */
  17. #define ASN1_PRINT_MAX_INDENT 128
  18. int ASN1_buf_print(BIO *bp, const unsigned char *buf, size_t buflen, int indent)
  19. {
  20. size_t i;
  21. for (i = 0; i < buflen; i++) {
  22. if ((i % ASN1_BUF_PRINT_WIDTH) == 0) {
  23. if (i > 0 && BIO_puts(bp, "\n") <= 0)
  24. return 0;
  25. if (!BIO_indent(bp, indent, ASN1_PRINT_MAX_INDENT))
  26. return 0;
  27. }
  28. /*
  29. * Use colon separators for each octet for compatibility as
  30. * this function is used to print out key components.
  31. */
  32. if (BIO_printf(bp, "%02x%s", buf[i],
  33. (i == buflen - 1) ? "" : ":") <= 0)
  34. return 0;
  35. }
  36. if (BIO_write(bp, "\n", 1) <= 0)
  37. return 0;
  38. return 1;
  39. }
  40. int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num,
  41. unsigned char *ign, int indent)
  42. {
  43. int n, rv = 0;
  44. const char *neg;
  45. unsigned char *buf = NULL, *tmp = NULL;
  46. int buflen;
  47. if (num == NULL)
  48. return 1;
  49. neg = BN_is_negative(num) ? "-" : "";
  50. if (!BIO_indent(bp, indent, ASN1_PRINT_MAX_INDENT))
  51. return 0;
  52. if (BN_is_zero(num)) {
  53. if (BIO_printf(bp, "%s 0\n", number) <= 0)
  54. return 0;
  55. return 1;
  56. }
  57. if (BN_num_bytes(num) <= BN_BYTES) {
  58. if (BIO_printf(bp, "%s %s%lu (%s0x%lx)\n", number, neg,
  59. (unsigned long)bn_get_words(num)[0], neg,
  60. (unsigned long)bn_get_words(num)[0]) <= 0)
  61. return 0;
  62. return 1;
  63. }
  64. buflen = BN_num_bytes(num) + 1;
  65. buf = tmp = OPENSSL_malloc(buflen);
  66. if (buf == NULL)
  67. goto err;
  68. buf[0] = 0;
  69. if (BIO_printf(bp, "%s%s\n", number,
  70. (neg[0] == '-') ? " (Negative)" : "") <= 0)
  71. goto err;
  72. n = BN_bn2bin(num, buf + 1);
  73. if (buf[1] & 0x80)
  74. n++;
  75. else
  76. tmp++;
  77. if (ASN1_buf_print(bp, tmp, n, indent + 4) == 0)
  78. goto err;
  79. rv = 1;
  80. err:
  81. OPENSSL_clear_free(buf, buflen);
  82. return rv;
  83. }