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.
 
 
 
 
 
 

65 lines
2.0 KiB

  1. /* Copyright (c) 2015, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include <openssl/bn.h>
  15. #include <openssl/bytestring.h>
  16. #include <openssl/err.h>
  17. int BN_parse_asn1_unsigned(CBS *cbs, BIGNUM *ret) {
  18. CBS child;
  19. if (!CBS_get_asn1(cbs, &child, CBS_ASN1_INTEGER) ||
  20. CBS_len(&child) == 0) {
  21. OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
  22. return 0;
  23. }
  24. if (CBS_data(&child)[0] & 0x80) {
  25. OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
  26. return 0;
  27. }
  28. // INTEGERs must be minimal.
  29. if (CBS_data(&child)[0] == 0x00 &&
  30. CBS_len(&child) > 1 &&
  31. !(CBS_data(&child)[1] & 0x80)) {
  32. OPENSSL_PUT_ERROR(BN, BN_R_BAD_ENCODING);
  33. return 0;
  34. }
  35. return BN_bin2bn(CBS_data(&child), CBS_len(&child), ret) != NULL;
  36. }
  37. int BN_marshal_asn1(CBB *cbb, const BIGNUM *bn) {
  38. // Negative numbers are unsupported.
  39. if (BN_is_negative(bn)) {
  40. OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
  41. return 0;
  42. }
  43. CBB child;
  44. if (!CBB_add_asn1(cbb, &child, CBS_ASN1_INTEGER) ||
  45. // The number must be padded with a leading zero if the high bit would
  46. // otherwise be set or if |bn| is zero.
  47. (BN_num_bits(bn) % 8 == 0 && !CBB_add_u8(&child, 0x00)) ||
  48. !BN_bn2cbb_padded(&child, BN_num_bytes(bn), bn) ||
  49. !CBB_flush(cbb)) {
  50. OPENSSL_PUT_ERROR(BN, BN_R_ENCODE_ERROR);
  51. return 0;
  52. }
  53. return 1;
  54. }