PEM.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Base64.h>
  27. #include <AK/GenericLexer.h>
  28. #include <LibCrypto/ASN1/PEM.h>
  29. namespace Crypto {
  30. ByteBuffer decode_pem(ReadonlyBytes data)
  31. {
  32. GenericLexer lexer { data };
  33. ByteBuffer decoded;
  34. // FIXME: Parse multiple.
  35. enum {
  36. PreStartData,
  37. Started,
  38. Ended,
  39. } state { PreStartData };
  40. while (!lexer.is_eof()) {
  41. switch (state) {
  42. case PreStartData:
  43. if (lexer.consume_specific("-----BEGIN"))
  44. state = Started;
  45. lexer.consume_line();
  46. break;
  47. case Started: {
  48. if (lexer.consume_specific("-----END")) {
  49. state = Ended;
  50. lexer.consume_line();
  51. break;
  52. }
  53. auto b64decoded = decode_base64(lexer.consume_line().trim_whitespace(TrimMode::Right));
  54. decoded.append(b64decoded.data(), b64decoded.size());
  55. break;
  56. }
  57. case Ended:
  58. lexer.consume_all();
  59. break;
  60. default:
  61. ASSERT_NOT_REACHED();
  62. }
  63. }
  64. return decoded;
  65. }
  66. }