// 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.Collections.Specialized; using System.Text; namespace E { public class Base64 { private static char[] EncVals = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".ToCharArray(); private static int[] DecVals; static Base64() { DecVals = new int[128]; for(int i = 0; i < 64; i++) { DecVals[EncVals[i]] = i; } } public string Encode(byte[] b) { int len = (b.Length * 8 + 5) / 6; int extra = 3 - (len + 3) % 4; char[] res = new char[len + extra]; int p = b.Length - b.Length % 3; int ix = 0; int tmp; for(int i = 0; i < p; i += 3) { tmp = (b[i] << 16) | (b[i + 1] << 8) | b[i + 2]; res[ix + 3] = EncVals[tmp & 0x3F]; res[ix + 2] = EncVals[(tmp >> 6) & 0x3F]; res[ix + 1] = EncVals[(tmp >> 12) & 0x3F]; res[ix] = EncVals[tmp >> 18]; ix += 4; } if(extra == 1) { tmp = (b[p] << 16) | (b[p + 1] << 8); res[ix + 3] = '='; res[ix + 2] = EncVals[(tmp >> 6) & 0x3F]; res[ix + 1] = EncVals[(tmp >> 12) & 0x3F]; res[ix] = EncVals[tmp >> 18]; } else if(extra == 2) { tmp = b[p] << 16; res[ix + 3] = '='; res[ix + 2] = '='; res[ix + 1] = EncVals[(tmp >> 12) & 0x3F]; res[ix] = EncVals[tmp >> 18]; } return new String(res); } public byte[] Decode(string s) { int len = s.Length; while(s[len - 1] == '=') len--; len = (len / 4 + 2) * 3; byte[] res = new byte[len]; int ix = 0; int tmp; for(int i = 0; i < s.Length; i += 4) { tmp = (DecVals[s[i]] << 18) | (DecVals[s[i + 1]] << 12) | (DecVals[s[i + 2]] << 6) | DecVals[s[i + 3]]; res[ix] = (byte)(tmp >> 16); res[ix + 1] = (byte)((tmp >> 8) & 0xFF); res[ix + 2] = (byte)(tmp & 0xFF); ix += 3; } return res; } } public class MainClass { private const int N = 1000000; private static Random rng = new Random(); public static void Main(string[] args) { for(int L = 96; L < 100; L++) { byte[] b = new byte[L]; rng.NextBytes(b); DateTime t1 = DateTime.Now; for(int i = 0; i < N; i++) { string s = Convert.ToBase64String(b); byte[] b2 = Convert.FromBase64String(s); if(b2[i % L] != b[i % L]) { throw new Exception("Ooops"); } } DateTime t2 = DateTime.Now; Console.WriteLine("Framework: " + (t2-t1).TotalSeconds); Base64 b64 = new Base64(); DateTime t3 = DateTime.Now; for(int i = 0; i < N; i++) { string s = b64.Encode(b); byte[] b2 = b64.Decode(s); if(b2[i % L] != b[i % L]) { throw new Exception("Ooops"); } } DateTime t4 = DateTime.Now; Console.WriteLine("Special: " + (t4-t3).TotalSeconds); } } } }