Advertisement
tomdodd4598

Untitled

Jun 2nd, 2021
1,160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4.  
  5. namespace CipherTest
  6. {
  7.     // Thanks to Nathan Moinvaziri on stackoverflow for the original byte <-> hex code transformers! https://stackoverflow.com/a/5919521
  8.     static class Helpers
  9.     {
  10.         static readonly Regex ValidRegex = new Regex(@"^[\x20-\xFF]+$", RegexOptions.Compiled);
  11.         static readonly Regex HexRegex = new Regex("^[0-9A-Fa-f]+$", RegexOptions.Compiled);
  12.  
  13.         static readonly string HexAlphabet = "0123456789ABCDEF";
  14.         static readonly int[] HexValue = new int[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
  15.  
  16.         public static ulong RL(this ulong x, int n) => (x << n) | (x >> (64 - n));
  17.  
  18.         public static bool IsValidString(string str) => ValidRegex.IsMatch(str);
  19.  
  20.         public static bool IsHexString(string str) => HexRegex.IsMatch(str);
  21.  
  22.         public static string BytesToHex(byte[] bytes)
  23.         {
  24.             StringBuilder result = new StringBuilder(bytes.Length * 2);
  25.  
  26.             foreach (byte b in bytes)
  27.             {
  28.                 result.Append(HexAlphabet[(int)(b >> 4)]);
  29.                 result.Append(HexAlphabet[(int)(b & 0xF)]);
  30.             }
  31.  
  32.             return result.ToString();
  33.         }
  34.  
  35.         public static byte[] HexToBytes(string hex)
  36.         {
  37.             if ((hex.Length & 1) == 1 || !IsHexString(hex))
  38.             {
  39.                 return null;
  40.             }
  41.  
  42.             byte[] bytes = new byte[hex.Length / 2];
  43.  
  44.             for (int x = 0, i = 0; i < hex.Length; i += 2, x += 1)
  45.             {
  46.                 bytes[x] = (byte) (HexValue[Char.ToUpper(hex[i + 0]) - '0'] << 4 | HexValue[Char.ToUpper(hex[i + 1]) - '0']);
  47.             }
  48.  
  49.             return bytes;
  50.         }
  51.     }
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement