// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Text; using System.Collections; namespace E { public class BaseBase { private string charset; private int basis; private int pad; public BaseBase(string charset, int basis, int pad) { this.charset = charset; this.basis = basis; this.pad = pad; } private int[] mask = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 }; public string Encode(byte[] b) { StringBuilder sb = new StringBuilder(); bool[] bit = new bool[8 * b.Length]; for(int i = 0; i < b.Length; i++) { for(int j = 0; j < 8; j++) { bit[8 * i + j] = ((b[i] & mask[7 - j]) != 0); } } for(int i = 0; i < bit.Length; i += basis) { int v = Get(bit, i, basis); sb.Append(charset[v]); } return sb.ToString().PadRight(((sb.Length + pad - 1) / pad) * pad, '='); } public byte[] Decode(string s) { string s2 = s.Trim("=".ToCharArray()); bool[] bit = new bool[basis * s2.Length]; for(int i = 0; i < s2.Length; i++) { byte b = (byte)charset.IndexOf(s2[i]); for(int j = 0; j < basis; j++) { bit[basis * i + j] = ((b & mask[basis - 1 - j]) != 0); } } byte[] byt = new byte[bit.Length / 8]; for(int i = 0; i < byt.Length; i++) { byt[i] = (byte)Get(bit, i * 8, 8); } return byt; } private int Get(bool[] bit, int ix, int n) { int res = 0; for(int i = 0; i < n; i++) { res = 2 * res + ((ix + i < bit.Length) ? (bit[ix + i] ? 1 : 0) : 0); } return res; } } public class Base64 : BaseBase { private const string BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; public Base64() : base(BASE64, 6, 4) { } } public class Base32 : BaseBase { private const string BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567/"; public Base32() : base(BASE32, 5, 8) { } } public class MainClass { public static void Test(byte[] b) { Base64 b64 = new Base64(); Console.WriteLine(b64.Encode(b)); Console.WriteLine(Convert.ToBase64String(b)); byte[] b2 = b64.Decode(b64.Encode(b)); for(int i = 0; i < b2.Length; i++) Console.Write(" " + b2[i]); Console.WriteLine(); Base32 b32 = new Base32(); Console.WriteLine(b32.Encode(b)); byte[] b3 = b32.Decode(b32.Encode(b)); for(int i = 0; i < b3.Length; i++) Console.Write(" " + b3[i]); Console.WriteLine(); } public static void Main(string[] args) { Test(new byte[] { }); Test(new byte[] { 1 }); Test(new byte[] { 1, 2 }); Test(new byte[] { 1, 2, 3 }); Test(new byte[] { 1, 2, 3, 4 }); Test(new byte[] { 1, 2, 3, 4, 5 }); Test(new byte[] { 1, 2, 3, 4, 5, 6 }); Test(new byte[] { 1, 2, 3, 4, 5, 6, 7 }); Test(Encoding.ASCII.GetBytes("foobar")); } } }