Neuron®
The Neuron® is the basis for the creation of open and secure federated networks for smart societies.
Loading...
Searching...
No Matches
Base32.cs
1using System;
2using System.IO;
3
4namespace Waher.Content
5{
10 public static class Base32
11 {
12 private const string Base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
13
19 public static byte[] Decode(string Base32)
20 {
21 MemoryStream ms = new MemoryStream();
22 ushort Buffer = 0;
23 int Offset = 0;
24
25 foreach (char ch in Base32)
26 {
27 if (char.IsWhiteSpace(ch))
28 continue;
29
30 Buffer <<= 5;
31 Offset += 5;
32
33 if (ch >= 'A' && ch <= 'Z')
34 Buffer |= (byte)(ch - 'A');
35 else if (ch >= '2' && ch <= '7')
36 Buffer |= (byte)(ch - '2' + 26);
37 else if (ch == '=')
38 break;
39 else if (ch >= 'a' && ch <= 'z')
40 Buffer |= (byte)(ch - 'a'); // Support lower-case letters as well.
41 else
42 throw new FormatException("Invalid Base32 character: " + ch.ToString());
43
44 if (Offset >= 8)
45 {
46 ms.WriteByte((byte)(Buffer >> (Offset - 8)));
47 Offset -= 8;
48 }
49 }
50
51 return ms.ToArray();
52 }
53
59 public static string Encode(byte[] Data)
60 {
61 if (Data == null || Data.Length == 0)
62 return string.Empty;
63
64 int Nr8CharBlocks = ((Data.Length << 3) + 39) / 40;
65 int Len = Nr8CharBlocks << 3;
66 char[] Result = new char[Len];
67 ushort Buffer = 0;
68 int NrBits = 0;
69 int Pos = 0;
70 byte b;
71
72 for (int i = 0; i < Data.Length; i++)
73 {
74 Buffer <<= 8;
75 Buffer |= Data[i];
76 NrBits += 8;
77
78 while (NrBits >= 5)
79 {
80 NrBits -= 5;
81 b = (byte)(Buffer >> NrBits);
82 Result[Pos++] = Base32Chars[b & 0x1f];
83 }
84 }
85
86 if (NrBits > 0)
87 {
88 b = (byte)(Buffer << (5 - NrBits));
89 Result[Pos++] = Base32Chars[b & 0x1f];
90 }
91
92 while (Pos < Len)
93 Result[Pos++] = '=';
94
95 return new string(Result);
96 }
97 }
98}
Static class that does BASE32 encoding and decoding as defined in RFC4648: https://datatracker....
Definition: Base32.cs:11
static byte[] Decode(string Base32)
Converts a Base32-encoded string to its binary representation.
Definition: Base32.cs:19
static string Encode(byte[] Data)
Converts a binary block of data to a Base32-encoded string.
Definition: Base32.cs:59