2
0

load.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (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 <stdlib.h>
  11. #include <openssl/x509.h>
  12. #include <openssl/pem.h>
  13. #include "../testutil.h"
  14. X509 *load_cert_pem(const char *file, OSSL_LIB_CTX *libctx)
  15. {
  16. X509 *cert = NULL;
  17. BIO *bio = NULL;
  18. if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new(BIO_s_file())))
  19. return NULL;
  20. if (TEST_int_gt(BIO_read_filename(bio, file), 0)
  21. && TEST_ptr(cert = X509_new_ex(libctx, NULL)))
  22. (void)TEST_ptr(cert = PEM_read_bio_X509(bio, &cert, NULL, NULL));
  23. BIO_free(bio);
  24. return cert;
  25. }
  26. STACK_OF(X509) *load_certs_pem(const char *file)
  27. {
  28. STACK_OF(X509) *certs;
  29. BIO *bio;
  30. X509 *x;
  31. if (!TEST_ptr(file) || (bio = BIO_new_file(file, "r")) == NULL)
  32. return NULL;
  33. certs = sk_X509_new_null();
  34. if (certs == NULL) {
  35. BIO_free(bio);
  36. return NULL;
  37. }
  38. ERR_set_mark();
  39. do {
  40. x = PEM_read_bio_X509(bio, NULL, 0, NULL);
  41. if (x != NULL && !sk_X509_push(certs, x)) {
  42. OSSL_STACK_OF_X509_free(certs);
  43. BIO_free(bio);
  44. return NULL;
  45. } else if (x == NULL) {
  46. /*
  47. * We probably just ran out of certs, so ignore any errors
  48. * generated
  49. */
  50. ERR_pop_to_mark();
  51. }
  52. } while (x != NULL);
  53. BIO_free(bio);
  54. return certs;
  55. }
  56. EVP_PKEY *load_pkey_pem(const char *file, OSSL_LIB_CTX *libctx)
  57. {
  58. EVP_PKEY *key = NULL;
  59. BIO *bio = NULL;
  60. if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new(BIO_s_file())))
  61. return NULL;
  62. if (TEST_int_gt(BIO_read_filename(bio, file), 0)) {
  63. unsigned long err = ERR_peek_error();
  64. if (TEST_ptr(key = PEM_read_bio_PrivateKey_ex(bio, NULL, NULL, NULL,
  65. libctx, NULL))
  66. && err != ERR_peek_error()) {
  67. TEST_info("Spurious error from reading PEM");
  68. EVP_PKEY_free(key);
  69. key = NULL;
  70. }
  71. }
  72. BIO_free(bio);
  73. return key;
  74. }
  75. X509_REQ *load_csr_der(const char *file, OSSL_LIB_CTX *libctx)
  76. {
  77. X509_REQ *csr = NULL;
  78. BIO *bio = NULL;
  79. if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new_file(file, "rb")))
  80. return NULL;
  81. csr = X509_REQ_new_ex(libctx, NULL);
  82. if (TEST_ptr(csr))
  83. (void)TEST_ptr(d2i_X509_REQ_bio(bio, &csr));
  84. BIO_free(bio);
  85. return csr;
  86. }