pemtest.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright 2017 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 <string.h>
  10. #include <openssl/bio.h>
  11. #include <openssl/pem.h>
  12. #include "testutil.h"
  13. static const char raw[] = "hello world";
  14. static const char encoded[] = "aGVsbG8gd29ybGQ=";
  15. static const char pemtype[] = "PEMTESTDATA";
  16. static int test_b64(void)
  17. {
  18. BIO *b = BIO_new(BIO_s_mem());
  19. char *name = NULL, *header = NULL;
  20. unsigned char *data = NULL;
  21. long len;
  22. int ret = 0;
  23. if (!TEST_ptr(b)
  24. || !TEST_true(BIO_printf(b, "-----BEGIN %s-----\n", pemtype))
  25. || !TEST_true(BIO_printf(b, "%s\n", encoded))
  26. || !TEST_true(BIO_printf(b, "-----END %s-----\n", pemtype))
  27. || !TEST_true(PEM_read_bio_ex(b, &name, &header, &data, &len,
  28. PEM_FLAG_ONLY_B64)))
  29. goto err;
  30. if (!TEST_int_eq(memcmp(pemtype, name, sizeof(pemtype) - 1), 0)
  31. || !TEST_int_eq(len,sizeof(raw) - 1)
  32. || !TEST_int_eq(memcmp(data, raw, sizeof(raw) - 1), 0))
  33. goto err;
  34. ret = 1;
  35. err:
  36. BIO_free(b);
  37. OPENSSL_free(name);
  38. OPENSSL_free(header);
  39. OPENSSL_free(data);
  40. return ret;
  41. }
  42. static int test_invalid(void)
  43. {
  44. BIO *b = BIO_new(BIO_s_mem());
  45. char *name = NULL, *header = NULL;
  46. unsigned char *data = NULL;
  47. long len;
  48. if (!TEST_ptr(b)
  49. || !TEST_true(BIO_printf(b, "-----BEGIN %s-----\n", pemtype))
  50. || !TEST_true(BIO_printf(b, "%c%s\n", '\t', encoded))
  51. || !TEST_true(BIO_printf(b, "-----END %s-----\n", pemtype))
  52. /* Expected to fail due to non-base64 character */
  53. || TEST_true(PEM_read_bio_ex(b, &name, &header, &data, &len,
  54. PEM_FLAG_ONLY_B64))) {
  55. BIO_free(b);
  56. return 0;
  57. }
  58. BIO_free(b);
  59. OPENSSL_free(name);
  60. OPENSSL_free(header);
  61. OPENSSL_free(data);
  62. return 1;
  63. }
  64. int setup_tests(void)
  65. {
  66. ADD_TEST(test_b64);
  67. ADD_TEST(test_invalid);
  68. return 1;
  69. }