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