load.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. sk_X509_pop_free(certs, X509_free);
  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. (void)TEST_ptr(key = PEM_read_bio_PrivateKey_ex(bio, NULL, NULL, NULL,
  64. libctx, NULL));
  65. BIO_free(bio);
  66. return key;
  67. }
  68. X509_REQ *load_csr_der(const char *file)
  69. {
  70. X509_REQ *csr = NULL;
  71. BIO *bio = NULL;
  72. if (!TEST_ptr(file) || !TEST_ptr(bio = BIO_new_file(file, "rb")))
  73. return NULL;
  74. (void)TEST_ptr(csr = d2i_X509_REQ_bio(bio, NULL));
  75. BIO_free(bio);
  76. return csr;
  77. }