-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathBase64NoPad.cs
88 lines (83 loc) · 3.2 KB
/
Base64NoPad.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ipfs
{
/// <summary>
/// A codec for Base-64 (RFC 4648) with no padding.
/// </summary>
/// <remarks>
/// <para>
/// A codec for Base-64, <see cref="Encode"/> and <see cref="Decode"/>. Adds the extension method <see cref="ToBase64NoPad"/>
/// to encode a byte array and <see cref="FromBase64NoPad"/> to decode a Base-64 string.
/// </para>
/// </remarks>
public static class Base64NoPad
{
/// <summary>
/// Converts an array of 8-bit unsigned integers to its equivalent string representation that is
/// encoded with base-64 characters.
/// </summary>s
/// <param name="bytes">
/// An array of 8-bit unsigned integers.
/// </param>
/// <returns>
/// The string representation, in base 64, of the contents of <paramref name="bytes"/>.
/// </returns>
public static string Encode(byte[] bytes)
{
return Convert.ToBase64String(bytes)
.TrimEnd('=');
}
/// <summary>
/// Converts an array of 8-bit unsigned integers to its equivalent string representation that is
/// encoded with base-64 digits.
/// </summary>
/// <param name="bytes">
/// An array of 8-bit unsigned integers.
/// </param>s
/// <returns>
/// The string representation, in base 64, of the contents of <paramref name="bytes"/>.
/// </returns>
public static string ToBase64NoPad(this byte[] bytes)
{
return Encode(bytes);
}
/// <summary>
/// Converts the specified <see cref="string"/>, which encodes binary data as base 64 digits,
/// to an equivalent 8-bit unsigned integer array.
/// </summary>
/// <param name="s">
/// The base 64 string to convert.
/// </param>
/// <returns>
/// An array of 8-bit unsigned integers that is equivalent to <paramref name="s"/>.
/// </returns>
public static byte[] Decode(string s)
{
switch (s.Length % 4) // Pad with trailing '='s
{
case 0: break; // No pad chars in this case
case 2: s += "=="; break; // Two pad chars
case 3: s += "="; break; // One pad char
default: throw new Exception("Illegal base64 string!");
}
return Convert.FromBase64String(s); // Standard base64 decoder
}
/// <summary>
/// Converts the specified <see cref="string"/>, which encodes binary data as base 64 digits,
/// to an equivalent 8-bit unsigned integer array.
/// </summary>
/// <param name="s">
/// The base 64 string to convert.
/// </param>
/// <returns>
/// An array of 8-bit unsigned integers that is equivalent to <paramref name="s"/>.
/// </returns>
public static byte[] FromBase64NoPad(this string s)
{
return Decode(s);
}
}
}