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 MOZ_MUST_USE nsresult Base64EncodeInputStream(nsIInputStream* aInputStream,
17                                               nsACString& aDest,
18                                               uint32_t aCount,
19                                               uint32_t aOffset = 0);
20 MOZ_MUST_USE nsresult Base64EncodeInputStream(nsIInputStream* aInputStream,
21                                               nsAString& aDest, uint32_t aCount,
22                                               uint32_t aOffset = 0);
23 
24 MOZ_MUST_USE nsresult Base64Encode(const char* aBinary, uint32_t aBinaryLen,
25                                    char** aBase64);
26 MOZ_MUST_USE nsresult Base64Encode(const nsACString& aBinary,
27                                    nsACString& aBase64);
28 
29 // The high bits of any characters in aBinary are dropped.
30 MOZ_MUST_USE nsresult Base64Encode(const nsAString& aBinary,
31                                    nsAString& aBase64);
32 
33 MOZ_MUST_USE nsresult Base64Decode(const char* aBase64, uint32_t aBase64Len,
34                                    char** aBinary, uint32_t* aBinaryLen);
35 MOZ_MUST_USE nsresult Base64Decode(const nsACString& aBase64,
36                                    nsACString& aBinary);
37 
38 // The high bits of any characters in aBase64 are dropped.
39 MOZ_MUST_USE nsresult Base64Decode(const nsAString& aBase64,
40                                    nsAString& aBinary);
41 
42 enum class Base64URLEncodePaddingPolicy {
43   Include,
44   Omit,
45 };
46 
47 /**
48  * Converts |aBinary| to an unpadded, Base64 URL-encoded string per RFC 4648.
49  * Aims to encode the data in constant time. The caller retains ownership
50  * of |aBinary|.
51  */
52 MOZ_MUST_USE nsresult Base64URLEncode(
53     uint32_t aBinaryLen, const uint8_t* aBinary,
54     Base64URLEncodePaddingPolicy aPaddingPolicy, nsACString& aBase64);
55 
56 enum class Base64URLDecodePaddingPolicy {
57   Require,
58   Ignore,
59   Reject,
60 };
61 
62 /**
63  * Decodes a Base64 URL-encoded |aBase64| into |aBinary|.
64  */
65 MOZ_MUST_USE nsresult Base64URLDecode(
66     const nsACString& aBase64, Base64URLDecodePaddingPolicy aPaddingPolicy,
67     FallibleTArray<uint8_t>& aBinary);
68 
69 }  // namespace mozilla
70 
71 #endif
72