Encryption.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (c) 2022, Matthew Olsson <mattco@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Span.h>
  8. #include <LibPDF/ObjectDerivatives.h>
  9. namespace PDF {
  10. class SecurityHandler : public RefCounted<SecurityHandler> {
  11. public:
  12. static PDFErrorOr<NonnullRefPtr<SecurityHandler>> create(Document*, NonnullRefPtr<DictObject> encryption_dict);
  13. virtual ~SecurityHandler() = default;
  14. virtual bool try_provide_user_password(StringView password) = 0;
  15. virtual bool has_user_password() const = 0;
  16. virtual void encrypt(NonnullRefPtr<Object>, Reference reference) const = 0;
  17. virtual void decrypt(NonnullRefPtr<Object>, Reference reference) const = 0;
  18. };
  19. class StandardSecurityHandler : public SecurityHandler {
  20. public:
  21. static PDFErrorOr<NonnullRefPtr<StandardSecurityHandler>> create(Document*, NonnullRefPtr<DictObject> encryption_dict);
  22. StandardSecurityHandler(Document*, size_t revision, DeprecatedString const& o_entry, DeprecatedString const& u_entry, u32 flags, bool encrypt_metadata, size_t length);
  23. ~StandardSecurityHandler() override = default;
  24. bool try_provide_user_password(StringView password_string) override;
  25. bool has_user_password() const override { return m_encryption_key.has_value(); }
  26. protected:
  27. void encrypt(NonnullRefPtr<Object>, Reference reference) const override;
  28. void decrypt(NonnullRefPtr<Object>, Reference reference) const override;
  29. private:
  30. template<bool is_revision_2>
  31. ByteBuffer compute_user_password_value(ByteBuffer password_string);
  32. ByteBuffer compute_encryption_key(ByteBuffer password_string);
  33. Document* m_document;
  34. size_t m_revision;
  35. Optional<ByteBuffer> m_encryption_key;
  36. DeprecatedString m_o_entry;
  37. DeprecatedString m_u_entry;
  38. u32 m_flags;
  39. bool m_encrypt_metadata;
  40. size_t m_length;
  41. };
  42. class RC4 {
  43. public:
  44. RC4(ReadonlyBytes key);
  45. void generate_bytes(ByteBuffer&);
  46. ByteBuffer encrypt(ReadonlyBytes bytes);
  47. private:
  48. Array<size_t, 256> m_bytes;
  49. };
  50. }