1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #ifndef mozilla_Base64_h__
8 #define mozilla_Base64_h__
9 
10 #include "nsString.h"
11 
12 class nsIInputStream;
13 
14 namespace mozilla {
15 
16 [[nodiscard]] nsresult Base64EncodeInputStream(nsIInputStream* aInputStream,
17                                                nsACString& aDest,
18                                                uint32_t aCount,
19                                                uint32_t aOffset = 0);
20 [[nodiscard]] nsresult Base64EncodeInputStream(nsIInputStream* aInputStream,
21                                                nsAString& aDest,
22                                                uint32_t aCount,
23                                                uint32_t aOffset = 0);
24 
25 [[nodiscard]] nsresult Base64Encode(const char* aBinary, uint32_t aBinaryLen,
26                                     char** aBase64);
27 [[nodiscard]] nsresult Base64Encode(const nsACString& aBinary,
28                                     nsACString& aBase64);
29 
30 // The high bits of any characters in aBinary are dropped.
31 [[nodiscard]] nsresult Base64Encode(const nsAString& aBinary,
32                                     nsAString& aBase64);
33 
34 [[nodiscard]] nsresult Base64Decode(const char* aBase64, uint32_t aBase64Len,
35                                     char** aBinary, uint32_t* aBinaryLen);
36 [[nodiscard]] nsresult Base64Decode(const nsACString& aBase64,
37                                     nsACString& aBinary);
38 
39 // The high bits of any characters in aBase64 are dropped.
40 [[nodiscard]] nsresult Base64Decode(const nsAString& aBase64,
41                                     nsAString& aBinary);
42 
43 enum class Base64URLEncodePaddingPolicy {
44   Include,
45   Omit,
46 };
47 
48 /**
49  * Converts |aBinary| to an unpadded, Base64 URL-encoded string per RFC 4648.
50  * Aims to encode the data in constant time. The caller retains ownership
51  * of |aBinary|.
52  */
53 [[nodiscard]] nsresult Base64URLEncode(
54     uint32_t aBinaryLen, const uint8_t* aBinary,
55     Base64URLEncodePaddingPolicy aPaddingPolicy, nsACString& aBase64);
56 
57 enum class Base64URLDecodePaddingPolicy {
58   Require,
59   Ignore,
60   Reject,
61 };
62 
63 /**
64  * Decodes a Base64 URL-encoded |aBase64| into |aBinary|.
65  */
66 [[nodiscard]] nsresult Base64URLDecode(
67     const nsACString& aBase64, Base64URLDecodePaddingPolicy aPaddingPolicy,
68     FallibleTArray<uint8_t>& aBinary);
69 
70 }  // namespace mozilla
71 
72 #endif
73