Advertisement
Guest User

B64 Encode

a guest
Mar 19th, 2021
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Text;
  4.  
  5. namespace B64Del
  6. {
  7.     class Program
  8.     {
  9.        
  10.         private static char[] arr =
  11.         {
  12.             'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
  13.             'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
  14.             'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a',
  15.             'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  16.             'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  17.             't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
  18.             '2', '3', '4', '5', '6', '7', '8', '9', '+',
  19.             '/'
  20.         };
  21.        
  22.         private static string StrToBin(string str)
  23.         {
  24.             string bin = "";
  25.             foreach (char c in str)
  26.             {
  27.                 bin += Convert.ToString((int) c, 2).PadLeft(8, '0');
  28.             }
  29.             return bin;
  30.         }
  31.  
  32.         private static string BinToLet(string bin)
  33.         {
  34.             return arr[Convert.ToInt32(bin, 2)].ToString();
  35.         }
  36.  
  37.         private static int DecideOverLen(int len)
  38.         {
  39.             if (len % 6 == 0) return len / 6;
  40.             else return len / 6 + 1;
  41.         }
  42.        
  43.         private static string B64Encrypt(string str)
  44.         {
  45.             string binaryStr = StrToBin(str);
  46.             string[] thing = new string[DecideOverLen(binaryStr.Length)];
  47.            
  48.             // forming bin str
  49.             for (int i = 0; i < thing.Length; i++)
  50.             {
  51.                 for (int j = 0; j < 6; j++)
  52.                 {
  53.                     try
  54.                     {
  55.                         thing[i] += binaryStr[i * 6 + j];
  56.                     } catch {}
  57.                 }
  58.             }
  59.  
  60.             string res = "";
  61.            
  62.             // forming b64 res
  63.            
  64.             foreach (string bin in thing)
  65.             {
  66.                 res += BinToLet(bin + String.Join("", Enumerable.Repeat("0", 6 - bin.Length)));
  67.             }
  68.            
  69.             // adding = as padding
  70.  
  71.             res += String.Join("", Enumerable.Repeat("=", 4 - res.Length % 4));
  72.            
  73.             return res;
  74.         }
  75.        
  76.         private static void Main(string[] args)
  77.         {
  78.             Console.WriteLine(B64Encrypt("hello world"));
  79.             Console.ReadLine();
  80.         }
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement