Skip to content

Instantly share code, notes, and snippets.

@marufbd
Created November 25, 2020 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marufbd/fa49bdf22dad13862d189ece24fd5216 to your computer and use it in GitHub Desktop.
Save marufbd/fa49bdf22dad13862d189ece24fd5216 to your computer and use it in GitHub Desktop.
Binary helper C#
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace CryptoLib
{
public class BinaryHelper
{
public static string ToBase64UrlString(byte[] payload)
{
char[] padding = { '=' };
string returnValue = Convert.ToBase64String(payload)
//.TrimEnd(padding)
.Replace('+', '-')
.Replace('/', '_');
return returnValue;
}
public static byte[] FromBase64UrlString(string b64Payload)
{
string incoming = b64Payload
.Replace('_', '/').Replace('-', '+');
switch (b64Payload.Length % 4)
{
case 2: incoming += "=="; break;
case 3: incoming += "="; break;
}
byte[] bytes = Convert.FromBase64String(incoming);
return bytes;
}
public static string HexStringToAsciiString(String hex)
{
return Encoding.ASCII.GetString(HexStringToByteArray(hex));
}
public static byte[] HexStringToByteArray(String hex)
{
hex = Regex.Replace(hex, " ", "");
int numberChars = hex.Length;
if(numberChars%2!=0)
throw new InvalidOperationException("must have even number of hexadecimal characters");
byte[] bytes = new byte[numberChars / 2];
for (int i = 0; i < numberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
public static string ByteArrayToHexString(byte[] ba, bool useUppercase=false)
{
var format=useUppercase? "{0:X2}": "{0:x2}";
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat(format, b);
return hex.ToString();
}
public static string AsciiStringToHexString(String ascii)
{
return ByteArrayToHexString(Encoding.ASCII.GetBytes(ascii));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment