EntropySource.cs

Posted on June 28, 2020Tags , , ,   Leave a comment on EntropySource.cs

Using PC Data Creates a Strong Entropy Source

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
public class EntropySource
{
    private const int Sha3BitSize           = 256;
    private const int Sha3BitBufferMoveSize = Sha3BitSize >> 3;
    private const int CpuDataLength         = 256;
    private const int JitterDataSize        = 256;
    [DllImport("kernel32.dll")]
    private static extern int GetTickCount();
    [DllImport("kernel32.dll")]
    internal static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
    [DllImport("kernel32.dll")]
    internal static extern bool QueryPerformanceFrequency(out long lpFrequency);
    public static byte[] GetBuffer(int bufferSize)
    {
        var rhb = new byte[0];
        var rho = new byte[bufferSize];
        var EntropyThread = new Thread(() =>
        {
            var el        = new List<string>();
            var hashBytes = new HashSet<byte[]>(new ArrayComparer());
            var sw        = new Stopwatch();
            sw.Start();
            AddLocalUserData(hashBytes);
            AddProcessInformation(hashBytes, el);
            AddJitterInformation(hashBytes);
            GetWmiInfor("Win32_PerfRawData_PerfOS_Processor",              hashBytes);
            GetWmiInfor("Win32_PerfRawData_PerfOS_System",                 hashBytes);
            GetWmiInfor("Win32_PerfRawData_Counters_ProcessorInformation", hashBytes);
            GetWmiInfor("Win32_PerfRawData_Counters_Synchronization",      hashBytes);
            GetWmiInfor("Win32_PerfRawData_PerfDisk_LogicalDisk",          hashBytes);
            GetWmiInfor("Win32_PerfRawData_PerfDisk_PhysicalDisk",         hashBytes);
            GetWmiInfor("Win32_PerfFormattedData_PerfOS_Cache",            hashBytes);
            GetWmiInfor("Win32_PerfFormattedData_PerfOS_Memory",           hashBytes);
            GetWmiInfor("Win32_PerfFormattedData_PerfOS_Objects",          hashBytes);
            CpuInfo(hashBytes);
            sw.Stop();
            hashBytes.Add(sw.Elapsed.Ticks.GetBytes());
            rhb = HashBytesToArray(hashBytes);
            AddHistogramInforamation(rhb, hashBytes);
            rhb = HashBytesToArray(hashBytes);
            hashBytes.Clear();
            var div = bufferSize / Sha3BitBufferMoveSize;
            if (div * Sha3BitBufferMoveSize < bufferSize)
                div++;
            var segSize = rhb.Length / div;
            var aseg    = new byte[segSize];
            for (var i = 0; i < div; ++i)
            {
                Buffer.BlockCopy(rhb,                                            i * segSize, aseg, 0,                         segSize);
                Buffer.BlockCopy(new SHA3Managed(Sha3BitSize).ComputeHash(aseg), 0,           rho,  i * Sha3BitBufferMoveSize, Sha3BitBufferMoveSize);
            }
        }) {Priority = ThreadPriority.Highest};
        EntropyThread.Start();
        EntropyThread.Join();
        return rho;
    }
    private static void GetWmiInfor(string key, HashSet<byte[]> hashBytes)
    {
        var wmi = new WMIServices();
        wmi.GetProperties(key);
        foreach (var v in wmi.EntriesList)
        foreach (var p in v.Value)
            hashBytes.Add(p.GetBytesObject());
    }
    private static void CpuInfo(HashSet<byte[]> hashBytes)
    {
        var lhashBytes = new HashSet<byte[]>();
        var dump       = CpuTotalPc.CPULoad;
        do
        {
            var l = (byte) CpuTotalPc.CPULoad;
            if (l != 0)
                lhashBytes.Add(new[] {l});
            Thread.Sleep(1);
        } while (lhashBytes.Count < CpuDataLength);
        foreach (var b in lhashBytes)
            hashBytes.Add(b);
    }
    private static void AddHistogramInforamation(byte[] rhb, HashSet<byte[]> hashBytes)
    {
        var FFTArray = Histogram(rhb);
        for (var i = 0; i < FFTArray.Length; ++i)
            hashBytes.Add(FFTArray[i].GetBytes());
    }
    private static void AddJitterInformation(HashSet<byte[]> hashBytes)
    {
        hashBytes.Add(new JitterEx(JitterDataSize).GetBuffer());
    }
    private static void AddProcessInformation(HashSet<byte[]> hashBytes, List<string> el)
    {
        foreach (var p in Process.GetProcesses())
        {
            try
            {
                hashBytes.Add(p.Id.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.Id.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.HandleCount.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.HandleCount.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.NonpagedSystemMemorySize64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.NonpagedSystemMemorySize64.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.PagedMemorySize64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.PagedMemorySize64.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.PagedSystemMemorySize64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.PagedSystemMemorySize64.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.PeakPagedMemorySize64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.PeakPagedMemorySize64.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.PeakVirtualMemorySize64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.PeakVirtualMemorySize64.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.PeakWorkingSet64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.PeakWorkingSet64.GetBytes()");
            }
            try
            {
                hashBytes.Add(p.PrivateMemorySize64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.PrivateMemorySize64.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.ProcessName.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.ProcessName.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.Threads.Count.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.Threads.Count.GetBytes())");
            }
            try
            {
                hashBytes.Add(p.SessionId.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.SessionId.GetBytes())");
            }
            for (var i = 0; i < p.Threads.Count; i++)
            {
                try
                {
                    hashBytes.Add(p.Threads[i].CurrentPriority.GetBytes());
                }
                catch (Exception ex)
                {
                    el.Add($"{ex.Message} hashBytes.Add(p.Threads[i].CurrentPriority.GetBytes())");
                }
                try
                {
                    hashBytes.Add(p.Threads[i].Id.GetBytes());
                }
                catch (Exception ex)
                {
                    el.Add($"{ex.Message} hashBytes.Add(p.Threads[i].Id.GetBytes())");
                }
                try
                {
                    hashBytes.Add(p.Threads[i].StartAddress.ToString().GetBytes());
                }
                catch (Exception ex)
                {
                    el.Add($"{ex.Message} hashBytes.Add(p.Threads[i].StartAddress.ToString().GetBytes())");
                }
            }
            try
            {
                hashBytes.Add(p.VirtualMemorySize64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.VirtualMemorySize64.GetBytes()))");
            }
            try
            {
                hashBytes.Add(p.WorkingSet64.GetBytes());
            }
            catch (Exception ex)
            {
                el.Add($"{ex.Message} hashBytes.Add(p.WorkingSet64.GetBytes()))");
            }
        }
    }
    private static void AddLocalUserData(HashSet<byte[]> hashBytes)
    {
        hashBytes.Add(Process.GetCurrentProcess().Id.GetBytes());
        hashBytes.Add(Thread.CurrentThread.ManagedThreadId.GetBytes());
        hashBytes.Add(GetTickCount().GetBytes());
        hashBytes.Add(Process.GetProcesses().Length.GetBytes());
        QueryPerformanceFrequency(out var freq);
        hashBytes.Add(freq.GetBytes());
        for (var i = 0; i < 128; i++)
        {
            QueryPerformanceCounter(out var query);
            hashBytes.Add(query.GetBytes());
        }
        hashBytes.Add(DateTime.Now.Ticks.GetBytes());
        hashBytes.Add(Environment.UserName.GetBytes());
        hashBytes.Add(Environment.MachineName.GetBytes());
        hashBytes.Add(Environment.OSVersion.ToString().GetBytes());
        hashBytes.Add(Environment.ProcessorCount.GetBytes());
        hashBytes.Add(Environment.UserDomainName.GetBytes());
        hashBytes.Add(Environment.StackTrace.GetBytes());
        hashBytes.Add(Environment.GetLogicalDrives().GetBytes());
        hashBytes.Add(MemoryInfo.GetValues().GetBytesObjectSerial());
        hashBytes.Add(MemoryInfo.GetSystemPerformanceInformation().GetBytesObjectSerial());
    }
    private static byte[] HashBytesToArray(HashSet<byte[]> hashBytes)
    {
        byte[] rhb;
        var    ptr   = 0;
        var    count = 0;
        var    arr   = hashBytes.ToArray();
        foreach (var hba in arr)
            count += hba.Length;
        hashBytes.Add(count.GetBytes());
        arr   =  hashBytes.ToArray();
        count += arr.Last().Length;
        rhb   =  new byte[count];
        foreach (var hba in arr)
        {
            Buffer.BlockCopy(hba, 0, rhb, ptr, hba.Length);
            ptr += hba.Length;
        }
        return rhb;
    }
    private static int[] Histogram(IEnumerable<byte> ba)
    {
        var map = new int[256];
        foreach (var i in ba)
            map[i]++;
        return map;
    }
}

SHA3ModInt.cs

Posted on June 27, 2020  Leave a comment on SHA3ModInt.cs

Modified Sha3 used with JitterCacheRng.cs

using System;
[Serializable]
public class SHA3ModInt : HashAlgorithmEx
{
    private readonly KeccakSpongeManaged _sponge;
    public SHA3ModInt(int size, int rounds = 24, ulong[] seed = null)
    {
        if (rounds > 24)
            throw new Exception($"Maximum rounds allowed is {24}");
        var MaxBR     = (64 >> 3) * 25;
        var sizeBytes = size >> 3;
        var rateBytes = MaxBR - (sizeBytes << 1);
        var MaxSize   = ((MaxBR - 8)       >> 1) << 3;
        if (rateBytes < 8)
            throw new Exception($"Maximum size allowed is {MaxSize} Bits with {64} bit Width specified. Specified Size is {size} Bits.");
        var outputLength = size >> 3;
        _sponge        = new KeccakSpongeManaged(rateBytes, 200 - rateBytes, KeccakSpongeManaged.KeccakDelimiter, outputLength, seed);
        _sponge.Rounds = rounds;
        HashSizeValue  = size;
    }
    public override void Initialize()
    {
        _sponge.Initialize();
    }
    protected override void HashCore(byte[] array, int ibStart, int cbSize)
    {
        Initialize();
        _sponge.Absorb(array, ibStart, cbSize);
    }
    protected override byte[] HashFinal()
    {
        return _sponge.Squeeze();
    }
}

Random64d.cs

Posted on June 24, 2020June 25, 2020Tags , , ,   Leave a comment on Random64d.cs

64 Bit Version of Random

using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
[Serializable]
public class Random64d : RandomNumberGenerator
{
    private const                    double                   DBi  = 1.0 / 9223372036854775807;
    private const                    double                   DBui = 1.0 / ulong.MaxValue;
    private readonly                 Random                   _r1;
    private readonly                 Random                   _r2;
    [NonSerialized] private readonly RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
    private                          RNumber                  _rNumber;
    public Random64d() : this(((long) (uint) Environment.TickCount << 32) | (uint) Environment.TickCount)
    {
    }
    public Random64d(long Seed)
    {
        var Seed0 = (int) (((Seed ^ 0x86B28CAB) << 16) & 0x7fffffff);
        var Seed1 = (int) (Seed                        & 0x7fffffff);
        _r1 = new Random(Seed0);
        _r2 = new Random(Seed1);
    }
    public long InternalSample()
    {
        _rNumber.n1 = _r1.Next();
        _rNumber.n2 = _r2.Next();
        return _rNumber.total;
    }
    private double GetSampleForLargeRange()
    {
        var value = InternalSample();
        if (InternalSample() % 2 == 0)
            value = -value;
        return (value + 4611686018427387903.0) / 9223372036854775807.0;
    }
    private double Sample()
    {
        return InternalSample() * DBi;
    }
    public long Next()
    {
        return InternalSample();
    }
    public long Next(long minValue, long maxValue)
    {
        if (minValue > maxValue)
            throw new ArgumentException("maxValue must be greater than or equal to minValue");
        var num = (ulong) maxValue - (ulong) minValue;
        if (num <= long.MaxValue)
            return (long) (Sample() * num) + minValue;
        return (long) ((ulong) (GetSampleForLargeRange() * num) + (ulong) minValue);
    }
    public ulong Next(ulong minValue, ulong maxValue)
    {
        if (minValue > maxValue)
            throw new ArgumentException("maxValue must be greater than or equal to minValue");
        var num = maxValue - minValue;
        return (ulong) (InternalSample() * DBui * num) + minValue;
    }
    public long Next(long maxValue)
    {
        if (maxValue < 0)
            throw new ArgumentException("maxValue must be greater than zero.");
        return (long) (Sample() * maxValue);
    }
    public ulong Next(ulong maxValue)
    {
        return (ulong) (InternalSample() * DBui * maxValue);
    }
    public double NextDouble()
    {
        return Sample();
    }
    public byte[] GetNextByteArray(int size)
    {
        var ba = new byte[size];
        _rng.GetBytes(ba);
        return ba;
    }
    public byte[] GetNextByteArrayFn(int size)
    {
        var ba = new byte[size];
        for (var i = 0; i < size; ++i)
            ba[i] = (byte) Next(0, 256);
        return ba;
    }
    public char[] GetNextCharArray(int size)
    {
        var ca = new char[size];
        for (var i = 0; i < size; ++i)
            ca[i] = (char)Next(32, 128);
        return ca;
    }
    public string GetRandomString(int minLen, int maxLen)
    {
        if (minLen == maxLen)
            return new string(GetNextCharArray(minLen));
        return new string(GetNextCharArray((int) Next(minLen, maxLen)));
    }
    public override void GetBytes(byte[] data)
    {
        if (data == null)
            throw new ArgumentException("The buffer cannot be null.");
        _rng.GetBytes(data);
    }
    [StructLayout(LayoutKind.Explicit, Size = 8, Pack = 1)]
    [Serializable]
    public struct RNumber
    {
        [FieldOffset(0)] public long n1;
        [FieldOffset(4)] public long n2;
        [FieldOffset(0)] public long total;
    }
}

ByteArraySegment.cs

Posted on June 17, 2020June 17, 2020Tags , , ,   Leave a comment on ByteArraySegment.cs

Segment a byte array to 16, 32, 64 bit Arrays

using System;
using System.Collections.Generic;
using System.Numerics;
public class ByteArraySegment
{
    public IEnumerable<T[]> SegmentEnum<T>(T[] buffer, int size)
    {
        var idx = 0;
        var ptr = buffer.Length;
        while (ptr >= size)
        {
            var array = new T[size];
            Buffer.BlockCopy(buffer, idx, array, 0, size);
            ptr -= size;
            idx += size;
            yield return array;
        }
    }
    public List<byte[]> SegmentList(byte[] buffer, int size)
    {
        var list = new List<byte[]>(buffer.Length >> 2);
        var idx  = 0;
        var ptr  = buffer.Length;
        while (ptr >= size)
        {
            var _result = new byte[size];
            Buffer.BlockCopy(buffer, idx, _result, 0, size);
            list.Add(_result);
            ptr -= size;
            idx += size;
        }
        return list;
    }
    public char[] SegmentChar(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 2 != 0)
            throw new Exception("Buffer must be a multiple of 2.");
        var array = new char[len >> 1];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public short[] Segment16(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 2 != 0)
            throw new Exception("Buffer must be a multiple of 2.");
        var array = new short[len >> 1];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public ushort[] SegmentU16(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 2 != 0)
            throw new Exception("Buffer must be a multiple of 2.");
        var array = new ushort[len >> 1];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public int[] Segment32(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 4 != 0)
            throw new Exception("Buffer must be a multiple of 4.");
        var array = new int[len >> 2];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public float[] SegmentFloat(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 4 != 0)
            throw new Exception("Buffer must be a multiple of 4.");
        var array = new float[len >> 2];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public uint[] SegmentU32(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 4 != 0)
            throw new Exception("Buffer must be a multiple of 4.");
        var array = new uint[len >> 2];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public long[] Segment64(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 8 != 0)
            throw new Exception("Buffer must be a multiple of 8.");
        var array = new long[len >> 3];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public double[] SegmentDouble(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 8 != 0)
            throw new Exception("Buffer must be a multiple of 8.");
        var array = new double[len >> 3];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public ulong[] SegmentU64(byte[] buffer)
    {
        var len = buffer.Length;
        if (len % 8 != 0)
            throw new Exception("Buffer must be a multiple of 8.");
        var array = new ulong[len >> 3];
        Buffer.BlockCopy(buffer, 0, array, 0, len);
        return array;
    }
    public BigInteger[] SegmentBI(byte[] buffer, int size)
    {
        var idx  = 0;
        var ptr  = buffer.Length;
        var bi   = new BigInteger[buffer.Length / size];
        var ptr1 = 0;
        while (ptr >= size)
        {
            var array = new byte[size];
            Buffer.BlockCopy(buffer, idx, array, 0, size);
            ptr      -= size;
            idx      += size;
            bi[ptr1++] =  new BigInteger(array);
        }
        return bi;
    }
}

Reporter.cs

Posted on June 17, 2020Tags , ,   Leave a comment on Reporter.cs

Thread Reporter used with IProgress

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;
[ComVisible(true)]
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public class Reporter
{
    public readonly ConcurrentDictionary<string, object> GValues  = new ConcurrentDictionary<string, object>();
    public          List<string>                         ErrorLog = new List<string>();
    public Reporter()
    {
    }
    public Reporter(string DescriptorID)
    {
        LoadDescriptorFile(DescriptorID);
    }
    public string ProgramDir
    {
        get
        {
            var dir = Services.GetEnvironmentEx("Local AppData") + "\\" + Application.ProductName + "\\";
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
            return dir;
        }
    }
    public void SaveDescriptorFile(string DescriptorID)
    {
        var anx = ProgramDir + DescriptorID + "_file.bin";
        var iel = GValues.ToArray();
        using (var wrt = new Writer(anx))
        {
            foreach (var i in iel)
            {
                wrt.WriteString(i.Key);
                wrt.WriteBytes(i.Value.GetBytesObjectSerial());
            }
        }
    }
    public void LoadDescriptorFile(string DescriptorID)
    {
        var anx = ProgramDir + DescriptorID + "_file.bin";
        if (!File.Exists(anx))
            throw new Exception($"file {anx} does not exist.");
        GValues.Clear();
        using (var rdr = new Reader(anx))
        {
            var key   = rdr.ReadString();
            var value = rdr.ReadBytes();
            GValues.TryAdd(key, value);
        }
    }
    public bool DescriptorFileExists(string DescriptorID)
    {
        var anx = ProgramDir + DescriptorID + "_file.bin";
        return File.Exists(anx);
    }
    public bool CheckDescriptorExists(string DescriptorID)
    {
        return GValues.ContainsKey(DescriptorID);
    }
    public void BuildDescriptorList(List<string> lst)
    {
        foreach (var i in lst)
            Set(i, default);
    }
    public void Set(string DescriptorID, object value)
    {
        if (!GValues.ContainsKey(DescriptorID))
            GValues.TryAdd(DescriptorID, value);
        else GValues[DescriptorID] = value;
    }
    public bool GetBool(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToBoolean(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return false;
    }
    public char GetChar(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToChar(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return ' ';
    }
    public sbyte GetSByte(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToSByte(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public byte GetByte(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToByte(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public short GetShort(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToInt16(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public ushort GetUShort(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToUInt16(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public int GetInt(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToInt32(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public uint GetUInt(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToUInt32(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public long GetLong(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToInt64(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public ulong GetULong(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToUInt64(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public float GetFloat(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToSingle(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public double GetDouble(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToDouble(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public decimal GetDecimal(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToDecimal(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return 0;
    }
    public string GetString(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToString(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return " ";
    }
    public DateTime GetDateTime(string DescriptorID)
    {
        if (GValues.TryGetValue(DescriptorID, out var ov))
            try
            {
                return Convert.ToDateTime(ov);
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null) ErrorLog.Add(ex.InnerException.ToString());
            }
        return default;
    }
}

StringHelper.cs

Posted on June 16, 2020Tags , ,   Leave a comment on StringHelper.cs

String Helper Class

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
public static class StringHelper
{
    public static ushort[] SearchArray;
    /// <summary>
    ///     Included here as an example of field extraction through reflection.
    ///     Specific knowledge of the underlying class is needed. IE. _items in the list class.
    /// </summary>
    /// <param name="list"></param>
    /// <returns></returns>
    public static byte[] ExtractArray(this List<byte> list)
    {
        var t     = list.GetType();
        var items = t.GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance);
        return items.GetValue(list) as byte[];
    }
    public static string Reverse(this string str)
    {
        var len                                  = str.Length;
        var Array                                = "";
        for (var i = len - 1; i >= 0; --i) Array += str[i];
        return Array;
    }
    public static string ToUTF16(this string str)
    {
        var AsciiBytes   = Encoding.ASCII.GetBytes(str);
        var unicodeBytes = Encoding.Convert(Encoding.ASCII, Encoding.Unicode, AsciiBytes);
        return Encoding.Unicode.GetString(unicodeBytes);
    }
    public static int CountInTheSet(this char c, string TheSet)
    {
        var Count = 0;
        if (TheSet        == null) return Count;
        if (TheSet.Length == 0) return Count;
        for (var j = 0; j < TheSet.Length; j++)
            if (c == TheSet[j])
                Count++;
        return Count;
    }
    public static bool EndsWith(this string s, char value)
    {
        var thisLen = s.Length;
        if (thisLen != 0)
            if (s[thisLen - 1] == value)
                return true;
        return false;
    }
    public static void SaveToFileComma(this Dictionary<string, string> d, string pathname)
    {
        using (var sw = new StreamWriter(pathname))
        {
            foreach (var e in d)
            {
                var k = e.Key + ",";
                var v = k     + e.Value;
                sw.WriteLine(v);
            }
        }
    }
    public static IDictionary<TKey, TValue> UpdateOrAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
    {
        if (dictionary.ContainsKey(key))
            dictionary[key] = value;
        else
            dictionary.Add(key, value);
        return dictionary;
    }
    public static void CopyToEx<T>(this List<T> obj, List<T> Target)
    {
        Target.AddRange(obj);
    }
    /// <summary>
    ///     tests if c is in the set TheSet
    /// </summary>
    /// <param name="c"></param>
    /// <param name="TheSet"></param>
    /// <returns></returns>
    public static bool InTheSet(this char c, string TheSet)
    {
        if (TheSet        == null) return false;
        if (TheSet.Length == 0) return false;
        return TheSet.Any(T => c == T);
    }
    public static string Join(this string separator, IEnumerable<string> values)
    {
        using (var enumerator = values.GetEnumerator())
        {
            if (!enumerator.MoveNext())
                return string.Empty;
            var res = enumerator.Current;
            while (enumerator.MoveNext())
            {
                res += separator;
                res += enumerator.Current;
            }
            return res;
        }
    }
    [SecuritySafeCritical]
    [__DynamicallyInvokable]
    private static unsafe List<int> IndexesOf(this string Haystack, string Needle)
    {
        var Indexes = new List<int>();
        var nh      = Encoding.Default.GetBytes(Haystack);
        var nn      = Encoding.Default.GetBytes(Needle);
        fixed (byte* H = nh)
        {
            fixed (byte* N = nn)
            {
                var i = 0;
                for (byte* hNext = H, hEnd = H + nh.Length; hNext < hEnd; i++, hNext++)
                {
                    var Found = true;
                    for (byte* hInc = hNext, nInc = N, nEnd = N + nn.Length; Found && nInc < nEnd; Found = *nInc == *hInc, nInc++, hInc++)
                        ;
                    if (Found)
                        Indexes.Add(i);
                }
                return Indexes;
            }
        }
    }
    /// <summary>
    ///     Convert a string into a byte array of type ascii
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static byte[] StrToByteArray(this string str)
    {
        if (str == null)
            return null;
        if (str.Length == 0)
            return null;
        return Encoding.ASCII.GetBytes(str);
    }
    public static char CharAt(this string str, int Index)
    {
        return str.Substring(Index, 1).ToCharArray()[0];
    }
    /// <summary>
    ///     Takes a delimited string and converts it into a generic object Example: 1,2,3,4 in string form = 1234 in array form
    /// </summary>
    /// <param name="input"></param>
    /// <param name="separator"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public static object[] StringToArray(this string input, string separator, Type type)
    {
        var stringList = input.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        var list       = new object[stringList.Length];
        for (var i = 0; i < stringList.Length; i++)
            list[i] = Convert.ChangeType(stringList[i], type);
        return list;
    }
    public static byte[] HexToByte(this string hex)
    {
        if (hex.Length % 2 == 1)
            throw new Exception("The binary key cannot have an odd number of digits");
        var len = hex.Length >> 1;
        var arr = new byte[len];
        for (var i = 0; i < len; ++i)
            arr[i] = (byte) ((GetHexVal(hex[i << 1]) << 4) + GetHexVal(hex[(i << 1) + 1]));
        return arr;
    }
    private static int GetHexVal(char hex)
    {
        int val = hex;
        return val - (val < 58 ? 48 : val < 97 ? 55 : 87);
    }
    /// <summary>
    ///     takes a composite string like "12,13,14,15,16' and creates a string array
    /// </summary>
    /// <param name="input"></param>
    /// <param name="separator"></param>
    /// <returns></returns>
    public static string[] StringToStringArray(this string input, string separator)
    {
        var stringList = input.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        return stringList;
    }
    /// <summary>
    ///     tests to find out if s contains all strings in TopList
    /// </summary>
    /// <param name="s"></param>
    /// <param name="TopList"></param>
    /// <returns></returns>
    public static bool ContainsAll(this string s, List<string> sl)
    {
        var sx  = s.ToLower();
        var sl1 = new List<string>();
        var a   = 0;
        foreach (var tls in sl)
            sl1.Add(tls.ToLower());
        var Count = 0;
        foreach (var ts in sl1)
            if (sx.IndexOf(ts, StringComparison.OrdinalIgnoreCase) != -1)
                Count++;
        if (Count > 4)
            a = Count;
        if (Count >= 4)
            return true;
        return false;
    }
    public static bool IsPrint(this string s)
    {
        var c = (byte) s[0];
        if (c >= 0x20 && c <= 0x7f || c == 0x0A || c == 0x0D)
            return true;
        return false;
    }
    public static bool IsPrint(this char c)
    {
        if (c >= 0x20 && c <= 0x7f || c == 0x0A || c == 0x0D)
            return true;
        return false;
    }
    public static bool IsLetter(this char c)
    {
        if (c >= 65 && c <= 90 || c >= 97 && c <= 122)
            return true;
        return false;
    }
    public static bool IsAlphaNumeric(this string s)
    {
        return s.IsLetter() || s.IsDigit();
    }
    public static bool IsAlphaNumeric(this char c)
    {
        return c.IsLetter() || c.IsDigit();
    }
    public static bool IsLetter(this string s)
    {
        var c = (byte) s[0];
        if (c >= 65 && c <= 90 || c >= 97 && c <= 122)
            return true;
        return false;
    }
    public static bool IsOnlyAlpha(this string s)
    {
        var c = 0;
        for (var i = 0; i < s.Length; i++)
            if (IsAlpha(s))
                c++;
        if (c == s.Length)
            return true;
        return false;
    }
    /// <summary>
    ///     A better IsAlpha which includes CR and LF as well as all characters between 0x20 and 0x7f
    /// </summary>
    /// <param name="c"></param>
    /// <returns></returns>
    public static bool IsAlpha(this string c)
    {
        var Count = 0;
        for (var i = 0; i < c.Length; i++)
            if (IsPrint(c.Substring(0, 1)))
                Count++;
        if (Count == c.Length)
            return true;
        return false;
    }
    /// <summary>
    ///     Indicates whether the specified string is null or is an empty string.
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static bool IsNullOrEmpty(this string s)
    {
        return string.IsNullOrEmpty(s);
    }
    public static bool IsAlpha(this char c)
    {
        return IsPrint(c);
    }
    public static bool IsLowwer(this string c)
    {
        return c.InTheSet("abcdefghijklmnopqrstuvwxyz");
    }
    public static bool IsLowwer(this char c)
    {
        return c.InTheSet("abcdefghijklmnopqrstuvwxyz");
    }
    public static bool IsVowel(this string c)
    {
        return InTheSet(c.ToLower(), "AEIOU".ToLower());
    }
    public static bool IsConsonant(this string c)
    {
        return InTheSet(c.ToLower(), "BCDFGHJKLMNPQRSTVWXYZ".ToLower());
    }
    public static bool IsVowel(this char c)
    {
        return "AEIOUaeiou".IndexOf(c) != -1;
    }
    public static bool IsConsonant(this char c)
    {
        return "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz".IndexOf(c) != -1;
    }
    public static int ContainsDigitAt(this string str)
    {
        for (var i = 0; i < str.Length; i++)
            if (IsDigit(str[i].ToString()))
                return i;
        return -1;
    }
    public static bool IsFloat(this string str)
    {
        return str.Any(T => T == '.');
    }
    public static bool IsDigit(this string c)
    {
        if (c.Length > 1)
            return c.InTheSet("0123456789.");
        return c.InTheSet("0123456789");
    }
    public static bool IsDigit(this char c)
    {
        return c.InTheSet("0123456789");
    }
    public static bool IsSpecialCharacter(this string c)
    {
        return InTheSet(c, "~`!@#$%^&*()_+-={}[]|:;'<>?,./");
    }
    public static bool IsSpecialCharacter(this char c)
    {
        return InTheSet(c, "~`!@#$%^&*()_+-={}[]|:;'<>?,./");
    }
    /// <summary>
    ///     Test c to see if it contains any special characters
    /// </summary>
    /// <param name="c"></param>
    /// <returns></returns>
    public static bool ContainsSpecialCharacter(this string c)
    {
        var TheSet = "~`!@#$%^&*()_+-={}[]|:;'<>?,./";
        for (var j = 0; j < TheSet.Length; j++)
        for (var k = 0; k < c.Length; k++)
            if (c[k] == TheSet[j])
                return true;
        return false;
    }
    /// <summary>
    ///     Check to see if this character is contained within the set
    /// </summary>
    /// <param name="c">The c.</param>
    /// <param name="TheSet">The set.</param>
    /// <returns></returns>
    public static bool InTheSet(this string c, string TheSet)
    {
        var result = false;
        if (TheSet == null)
            return result;
        if (TheSet.Length == 0)
            return result;
        if (c == null)
            return result;
        if (c.Length == 0)
            return result;
        for (var j = 0; j < TheSet.Length; j++)
            if (c[0] == TheSet[j])
            {
                result = true;
                break;
            }
        return result;
    }
    /// <summary>
    ///     Check to see if this character is contained within the set
    /// </summary>
    /// <param name="c">The c.</param>
    /// <param name="TheSet">The set.</param>
    /// <returns></returns>
    public static bool InTheSet(this char c, char[] TheSet)
    {
        var result = false;
        if (TheSet == null)
            return result;
        if (TheSet.Length == 0)
            return result;
        for (var j = 0; j < TheSet.Length; j++)
            if (c == TheSet[j])
            {
                result = true;
                break;
            }
        return result;
    }
    public static int IndexOfN(this string str, string pattern, int n)
    {
        var c  = 0;
        var f  = pattern[0];
        var pl = pattern.Length;
        var e  = str.IndexOf(f);
        if (e == -1)
            return -1;
        do
        {
            try
            {
                e = str.IndexOf(pattern, e, StringComparison.OrdinalIgnoreCase);
            }
            catch
            {
                return -1;
            }
            if (e == -1)
                return -1;
            c++;
            e = str.IndexOf(f, e + pl + 1);
            if (e == -1)
                return -1;
        } while (c < n);
        return e - 1;
    }
    /// <summary>
    ///     Gets all indices of the pattern within the string
    /// </summary>
    /// <param name="str">The string.</param>
    /// <param name="pattern">The pattern.</param>
    /// <returns></returns>
    public static List<int> GetAllIndices(this string str, string pattern)
    {
        var lst = new List<int>();
        var f   = pattern[0];
        var pl  = pattern.Length;
        var e   = 0;
        var p   = str.IndexOf(f);
        do
        {
            try
            {
                e = str.IndexOf(pattern, p, StringComparison.OrdinalIgnoreCase);
            }
            catch
            {
                return lst;
            }
            if (e != -1)
            {
                lst.Add(e);
                p = str.IndexOf(f, e + pl);
                if (p == -1)
                    break;
            }
            else
            {
                break;
            }
        } while (e != -1);
        return lst;
    }
    public static int GetCharacterCount(this string p)
    {
        var map = new Dictionary<char, int>();
        foreach (var c in p)
            if (!map.ContainsKey(c))
                map.Add(c, 1);
            else
                map[c] += 1;
        return map.Count;
    }
    public static Dictionary<char, int> CountCharacter(this string p)
    {
        var map = new Dictionary<char, int>();
        foreach (var c in p)
            if (!map.ContainsKey(c))
                map.Add(c, 1);
            else
                map[c] += 1;
        return map;
    }
    public static int CharacterCount(this string p, char c0)
    {
        var count = 0;
        foreach (var c in p)
            if (c.Equals(c0))
                count++;
        return count;
    }
    public static bool MajorCharacter(this string p, char c)
    {
        var cc = p.CountCharacter();
        var hc = '\0';
        var mv = 0;
        foreach (var v in cc)
            if (v.Value > mv)
            {
                mv = v.Value;
                hc = v.Key;
            }
        return hc == c;
    }
    /// <summary>
    ///     Test to see if p contains only characters contained in s
    /// </summary>
    public static bool ContainsOnly(this string p, string s)
    {
        return p.Count(c => s.Any(c1 => c == c1)) == p.Length;
    }
    public static bool ContainsOnlyTheseCharacters(this string p, params char[] c)
    {
        var cc = p.CountCharacter();
        if (cc.Count > c.Length)
            return false;
        var pac = p.ToCharArray();
        var u   = pac.Except(c).ToArray();
        if (u.Length == 0)
            return true;
        return false;
    }
    public static double Uniqueness(this string s, double CharactersAllowed)
    {
        var map = new Dictionary<char, int>();
        foreach (var c in s)
            if (!map.ContainsKey(c))
                map.Add(c, 1);
            else
                map[c] += 1;
        return map.Count / CharactersAllowed * 100D;
    }
    /// <summary>
    ///     find the nth occurrence of substr within str return the index (For reverse compatibility)
    /// </summary>
    /// <param name="str"></param>
    /// <param name="substr"></param>
    /// <param name="nth"></param>
    /// <returns></returns>
    public static int SuperIndexOf(this string str, string substr, int nth)
    {
        var e = 0;
        var c = 0;
        var l = str.Length;
        do
        {
            e = str.IndexOf(substr, e, StringComparison.CurrentCultureIgnoreCase);
            if (e == -1)
                return -1;
            c++;
            e++;
            if (e >= l)
                return -1;
        } while (c < nth);
        return e - 1;
    }
    /// <summary>
    ///     find the nth occurrence of substr within str return the index (IgnoreCase)
    /// </summary>
    public static int IndexNOf(this string str, string substr, int nth)
    {
        if (str == null || substr == null || nth < 0)
            return -1;
        var e = 0;
        var c = 0;
        var l = str.Length;
        do
        {
            e = str.IndexOf(substr, e, StringComparison.CurrentCultureIgnoreCase);
            if (e == -1)
                return -1;
            c++;
            e++;
            if (e >= l)
                return -1;
        } while (c < nth);
        return e - 1;
    }
    public static List<string> StringToList(this string input, string separator)
    {
        return input.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
    }
    /// <summary>
    ///     Returns a <see cref="System.String" /> that represents this instance with commas.
    /// </summary>
    /// <param name="s">The s.</param>
    /// <returns>
    ///     A <see cref="System.String" /> that represents this instance.
    /// </returns>
    public static string ToStringWithCommas(this int s)
    {
        return s.ToString("N0");
    }
    public static string InsertCommas(this string str)
    {
        if (str == null)
            return "";
        var pos  = str.IndexOf('.');
        var frac = "";
        if (pos != -1)
        {
            frac = str.Substring(pos);
            str  = str.Substring(0, pos);
        }
        var rs  = str;
        var len = str.Length;
        if (len > 3)
            for (int i = 0, j = 0; i < len; i++)
                if (i != 0)
                    if ((len - i) % 3 == 0)
                    {
                        rs = rs.Insert(i + j, ",");
                        j++;
                    }
        return rs + frac;
    }
    public static byte[] ToByteArrayDefault(this string str)
    {
        return Encoding.Default.GetBytes(str);
    }
    public static byte[] FromBase64(this string str)
    {
        return Convert.FromBase64String(str);
    }
    public static string B64Encode(this string S)
    {
        if (S == null)
            return "";
        var encbuff = Encoding.Default.GetBytes(S);
        var enc     = Convert.ToBase64String(encbuff);
        return enc;
    }
    public static int WordCount(this string s)
    {
        var Count = 0;
        foreach (var sc in s)
            if (sc == ' ')
                Count++;
        return Count + 1;
    }
    /// <summary>
    ///     Allocate and zero the search array
    /// </summary>
    /// <param name="s"></param>
    public static void NewSearchArray(this string s)
    {
        SearchArray = new ushort[s.Length];
    }
    /// <summary>
    ///     Get the search array for external use
    /// </summary>
    /// <param name="s"></param>
    /// <returns></returns>
    public static ushort[] GetSearchArray(this string s)
    {
        return SearchArray;
    }
    public static bool IsEven(this short o)
    {
        if ((ulong) o % 2 == 0)
            return true;
        return false;
    }
    public static bool IsEven(this ushort o)
    {
        if ((ulong) o % 2 == 0)
            return true;
        return false;
    }
    public static bool IsEven(this uint o)
    {
        if ((ulong) o % 2 == 0)
            return true;
        return false;
    }
    public static bool IsEven(this ulong o)
    {
        if (o % 2 == 0)
            return true;
        return false;
    }
    public static string RemoveDiacritics(this string s)
    {
        var stFormD = s.Normalize(NormalizationForm.FormD);
        var sb      = new StringBuilder();
        for (var i = 0; i < stFormD.Length; i++)
        {
            var uc = CharUnicodeInfo.GetUnicodeCategory(stFormD[i]);
            if (uc != UnicodeCategory.NonSpacingMark)
                sb.Append(stFormD[i]);
        }
        return sb.ToString().Normalize(NormalizationForm.FormC);
    }
    public static string RemoveSpaces(this string s)
    {
        return s.Replace(" ", "");
    }
    public static bool IsNumber(this string s, bool floatpoint)
    {
        int    i;
        double d;
        var    withoutWhiteSpace = s.RemoveSpaces();
        if (floatpoint)
            return double.TryParse(withoutWhiteSpace, NumberStyles.Any, Thread.CurrentThread.CurrentUICulture, out d);
        return int.TryParse(withoutWhiteSpace, out i);
    }
    public static string UppercaseFirstLetter(this string value)
    {
        if (value.Length > 0)
        {
            var array = value.ToCharArray();
            array[0] = char.ToUpper(array[0]);
            return new string(array);
        }
        return value;
    }
    public static string ToInitials(this string str)
    {
        return Regex.Replace(str, @"^(?'b'\w)\w*,\s*(?'a'\w)\w*$|^(?'a'\w)\w*\s*(?'b'\w)\w*$", "${a}${b}", RegexOptions.Singleline);
    }
    public static string RemoveLineBreaks(this string lines)
    {
        return lines.Replace("\r", "").Replace("\n", "");
    }
    public static string ReplaceLineBreaks(this string lines, string replacement)
    {
        return lines.Replace("\r\n", replacement).Replace("\r", replacement).Replace("\n", replacement);
    }
    public static string StripHtml(this string html)
    {
        if (string.IsNullOrEmpty(html))
            return string.Empty;
        return Regex.Replace(html, @"<[^>]*>", " ");
    }
    public static string StripHTML(this string source)
    {
        try
        {
            string result;
            result = source.Replace("\r", " ");
            result = result.Replace("\n", " ");
            result = result.Replace("\t", string.Empty);
            result = Regex.Replace(result, @"( )+",                      " ");
            result = Regex.Replace(result, @"<( )*head([^>])*>",         "<head>",     RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*head( )*>)",   "</head>",    RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(<head>).*?(</head>)",       string.Empty, RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*script([^>])*>",       "<script>",   RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*script( )*>)", "</script>",  RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<script>).*?(</script>)",  string.Empty, RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*style([^>])*>",        "<style>",    RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*style( )*>)",  "</style>",   RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(<style>).*?(</style>)",     string.Empty, RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*td([^>])*>",           "\t",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*br( )*(/)?( )*>",      "\r",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*li( )*>",              "\r",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*div([^>])*>",          "\r\r",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*tr([^>])*>",           "\r\r",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*p([^>])*>",            "\r\r",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<[^>]*>",                   string.Empty, RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @" ",                         " ",          RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"•",                    " * ",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"‹",                  "<",          RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"›",                  ">",          RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"™",                   "(tm)",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"⁄",                   "/",          RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<",                      "<",          RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @">",                      ">",          RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"©",                    "(c)",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"®",                     "(r)",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"&(.{2,6});",                string.Empty, RegexOptions.IgnoreCase);
            result = result.Replace("\n", "\r");
            result = Regex.Replace(result, "(\r)( )+(\r)",  "\r\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\t)( )+(\t)",  "\t\t", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\t)( )+(\r)",  "\t\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)( )+(\t)",  "\r\t", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)(\t)+(\r)", "\r\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)(\t)+",     "\r\t", RegexOptions.IgnoreCase);
            var breaks = "\r\r\r";
            var tabs   = "\t\t\t\t\t";
            for (var index = 0; index < result.Length; index++)
            {
                result = result.Replace(breaks, "\r\r");
                result = result.Replace(tabs,   "\t\t\t\t");
                breaks = breaks + "\r";
                tabs   = tabs   + "\t";
            }
            return result;
        }
        catch
        {
            return source;
        }
    }
    public static string StripHTMLNE(this string source)
    {
        try
        {
            string result;
            result = source.Replace("\r", " ");
            result = result.Replace("\n", " ");
            result = result.Replace("\t", " ");
            result = Regex.Replace(result, @"( )+",                      " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*head([^>])*>",         "<head>",    RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*head( )*>)",   "</head>",   RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(<head>).*?(</head>)",       " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*script([^>])*>",       "<script>",  RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*script( )*>)", "</script>", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<script>).*?(</script>)",  " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*style([^>])*>",        "<style>",   RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*style( )*>)",  "</style>",  RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(<style>).*?(</style>)",     " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*td([^>])*>",           "\t",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*br( )*(/)?( )*>",      "\r",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*li( )*>",              "\r",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*div([^>])*>",          "\r\r",      RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*tr([^>])*>",           "\r\r",      RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*p([^>])*>",            "\r\r",      RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<[^>]*>",                   " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @" ",                         " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"&nbsp",                     " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"•",                    " * ",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"‹",                  "<",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"›",                  ">",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"™",                   "(tm)",      RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"⁄",                   "/",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<",                      "<",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @">",                      ">",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"©",                    "(c)",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"®",                     "(r)",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"&(.{2,6});",                " ",         RegexOptions.IgnoreCase);
            result = result.Replace("\n", "\r");
            result = Regex.Replace(result, "(\r)( )+(\r)",  "\r\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\t)( )+(\t)",  "\t\t", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\t)( )+(\r)",  "\t\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)( )+(\t)",  "\r\t", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)(\t)+(\r)", "\r\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)(\t)+",     "\r\t", RegexOptions.IgnoreCase);
            var breaks = "\r\r\r";
            var tabs   = "\t\t\t\t\t";
            for (var index = 0; index < result.Length; index++)
            {
                result = result.Replace(breaks, "\r\r");
                result = result.Replace(tabs,   "\t\t\t\t");
                breaks = breaks + "\r";
                tabs   = tabs   + "\t";
            }
            return result;
        }
        catch
        {
            return source;
        }
    }
    public static string StripHTMLAll(this string source)
    {
        try
        {
            string result;
            result = source.Replace("\r", " ");
            result = result.Replace("\n", " ");
            result = result.Replace("\t", " ");
            result = Regex.Replace(result, @"( )+",                      " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*head([^>])*>",         "<head>",    RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*head( )*>)",   "</head>",   RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(<head>).*?(</head>)",       " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*script([^>])*>",       "<script>",  RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*script( )*>)", "</script>", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<script>).*?(</script>)",  " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*style([^>])*>",        "<style>",   RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"(<( )*(/)( )*style( )*>)",  "</style>",  RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(<style>).*?(</style>)",     " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*td([^>])*>",           "\t",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*br( )*(/)?( )*>",      "\r",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*li( )*>",              "\r",        RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*div([^>])*>",          "\r\r",      RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*tr([^>])*>",           "\r\r",      RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<( )*p([^>])*>",            "\r\r",      RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<[^>]*>",                   " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @" ",                         " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"&nbsp",                     " ",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"•",                    " * ",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"‹",                  "<",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"›",                  ">",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"™",                   "(tm)",      RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"⁄",                   "/",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"<",                      "<",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @">",                      ">",         RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"©",                    "(c)",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"®",                     "(r)",       RegexOptions.IgnoreCase);
            result = Regex.Replace(result, @"&(.{2,6});",                " ",         RegexOptions.IgnoreCase);
            result = result.Replace("\n", " ");
            result = result.Replace("\r", " ");
            result = result.Replace("\t", " ");
            result = result.Replace("\n", "\r");
            result = Regex.Replace(result, "(\r)( )+(\r)",  "\r\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\t)( )+(\t)",  "\t\t", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\t)( )+(\r)",  "\t\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)( )+(\t)",  "\r\t", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)(\t)+(\r)", "\r\r", RegexOptions.IgnoreCase);
            result = Regex.Replace(result, "(\r)(\t)+",     "\r\t", RegexOptions.IgnoreCase);
            var breaks = "\r\r\r";
            var tabs   = "\t\t\t\t\t";
            for (var index = 0; index < result.Length; index++)
            {
                result = result.Replace(breaks, "\r\r");
                result = result.Replace(tabs,   "\t\t\t\t");
                breaks = breaks + "\r";
                tabs   = tabs   + "\t";
            }
            return result;
        }
        catch
        {
            return source;
        }
    }
    /// <summary>
    ///     If the searchstring contains any occurrences of the list values returns true else false.
    /// </summary>
    public static bool ContainsAny(this string searchstring, params string[] list)
    {
        var sslcs = searchstring.ToLower();
        var bfss  = sslcs.GetBytes(Encoding.ASCII);
        foreach (var s in list)
        {
            var lcs = s.ToLower();
            var bf  = lcs.GetBytes(Encoding.ASCII);
            var bm  = new BoyerMoore(bf);
            if (bm.Search(bfss) != -1)
                return true;
        }
        return false;
    }
    public static string DownloadURLToString(this string url)
    {
        var webReq = (HttpWebRequest) WebRequest.Create(url);
        try
        {
            webReq.CookieContainer = new CookieContainer();
            webReq.Method          = "GET";
            webReq.UserAgent       = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36";
            using (var response = webReq.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    var reader = new StreamReader(stream);
                    return reader.ReadToEnd();
                }
            }
        }
        catch (Exception ex)
        {
        }
        return "";
    }
    public static string ReverseWords(this string str, char sep)
    {
        char temp;
        int  left  = 0, middle = 0;
        var  chars = str.ToCharArray();
        Array.Reverse(chars);
        for (var i = 0; i <= chars.Length; i++)
        {
            if (i != chars.Length && chars[i] != sep)
                continue;
            if (left == i || left + 1 == i)
            {
                left = i + 1;
                continue;
            }
            middle = (i - left - 1) / 2 + left;
            for (var j = i - 1; j > middle; j--, left++)
            {
                temp        = chars[left];
                chars[left] = chars[j];
                chars[j]    = temp;
            }
            left = i + 1;
        }
        return new string(chars);
    }
    public static string ReverseWords(this string str)
    {
        return str.ReverseWords(' ');
    }
}

ArrayHelper.cs

Posted on June 16, 2020  Leave a comment on ArrayHelper.cs

Generic Array Helper Class

using System;
public static class ArrayHelper
{
    /// <summary>
    ///     Clear T type single dimensional array to either the default value or a set value.  (ArrayHelper.cs)
    /// </summary>
    public static void Clear<T>(this T[] array, T value = default)
    {
        if (array == null)
            throw new Exception("The array cannot be null.");
        for (var i = 0; i < array.Length; i++)
            array[i] = value;
    }
    /// <summary>
    ///     Clear T type multi dimensional array to either the default value or a set value. (ArrayHelper.cs)
    /// </summary>
    public static void Clear<T>(this T[][] array, T value = default)
    {
        if (array == null)
            throw new Exception("The array cannot be null.");
        var xlen = array.GetLength(0);
        var ylen = array.GetLength(1);
        for (var x = 0; x < xlen; x++)
        for (var y = 0; y < ylen; y++)
            array[x][y] = value;
    }
    /// <summary>
    ///     Copies a total or portion of a source array of type T starting at offset
    ///     and copying count bytes.  (ArrayHelper.cs)
    /// </summary>
    public static T[] SubArray<T>(this T[] array, int offset, int count)
    {
        if (array == null)
            throw new Exception("The array cannot be null.");
        if (count - offset > array.Length)
            throw new Exception($"Count {count} + Offset {offset} must be less than the length of the array {array.Length}");
        var result = new T[count];
        Array.Copy(array, offset, result, 0, count);
        return result;
    }
    /// <summary>
    ///     Copies the source array of type T into the target array.
    ///     (ArrayHelper.cs)
    /// </summary>
    public static void Copy<T>(this T[] array, T[] array1)
    {
        if (array == null || array1 == null)
            throw new Exception("Neither the source or target array can be null.");
        if (array == null || array1 == null)
            throw new Exception("Neither the source or target array can be null.");
        var len  = array.Length;
        var len1 = array1.Length;
        if (len > len1)
            throw new Exception("The target array must be the same length.");
        Array.Copy(array, 0, array1, 0, len);
    }
    /// <summary>
    ///     Inverts the order of the array.
    ///     (ArrayHelper.cs)
    /// </summary>
    public static T[] Invert<T>(this T[] array)
    {
        if (array == null)
            throw new Exception("The array cannot be null.");
        var len = array.Length;
        var t   = new T[len];
        for (int i = len - 1, j = 0; i >= 0; t[j++] = array[i--]) ;
        return t;
    }
    public static T[] ReSize<T>(this T[] array, int NewSize)
    {
        if (array == null)
            throw new Exception("The array cannot be null.");
        if (array.Length >= NewSize)
            return array;
        var temp = new T[NewSize];
        Array.Copy(array, 0, temp, 0, array.Length);
        return temp;
    }
    public static T[] ReSize<T>(this T[] array)
    {
        if (array == null)
            throw new Exception("The array cannot be null.");
        var cSize = (long) array.Length;
        var mul   = 1.2;
        if (cSize < int.MaxValue >> 1)
            mul = 8;
        var nSize = (long) (cSize * mul);
        if (nSize > int.MaxValue)
            nSize = int.MaxValue;
        var temp = new T[nSize];
        Array.Copy(array, 0, temp, 0, array.Length);
        return temp;
    }
    public static T[][] ReSize<T>(this T[][] array, int NewX, int NewY)
    {
        if (array == null)
            throw new Exception("The array cannot be null.");
        var xlen = array.GetLength(0);
        var ylen = array.GetLength(1);
        if (xlen >= NewX && ylen >= NewY)
            return array;
        var temp = new T[NewX][];
        for (var i = 0; i < NewX; ++i)
            temp[i] = new T[NewY];
        for (var i = 0; i < NewX; ++i)
            Array.Copy(array[i], temp[i], ylen);
        return temp;
    }
}

Converters.cs

Posted on June 13, 2020Tags , , ,   Leave a comment on Converters.cs

General Data Converters

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Text;
public static class Converters
{
    public static bool IsValidPrimitive(Type type)
    {
        switch (Type.GetTypeCode(type))
        {
            case TypeCode.Boolean:
            case TypeCode.Char:
            case TypeCode.SByte:
            case TypeCode.Byte:
            case TypeCode.Int16:
            case TypeCode.UInt16:
            case TypeCode.Int32:
            case TypeCode.UInt32:
            case TypeCode.Single:
            case TypeCode.Object:
            case TypeCode.DateTime:
            case TypeCode.String:
            case TypeCode.Int64:
            case TypeCode.UInt64:
            case TypeCode.Double:
            case TypeCode.Decimal:
                return true;
            default:
                return false;
        }
    }
    /// <summary>
    ///     Get Bytes from a single boolean object
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this bool value)
    {
        return new[] {value ? (byte) 1 : (byte) 0};
    }
    /// <summary>
    ///     Get Bytes from an array of boolean objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this bool[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (bool[]) object cannot be null.");
        var seed = new byte[0];
        return value.Aggregate(seed, (Current, bl) => Current.Add(bl.GetBytes()));
    }
    /// <summary>
    ///     Get Bytes from a single byte object
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this byte value)
    {
        return new[] {value};
    }
    /// <summary>
    ///     Get Bytes from a sbyte short object
    ///     (Converters.cs)
    /// </summary>
    [SecuritySafeCritical]
    public static unsafe byte[] GetBytes(this sbyte value)
    {
        var numArray = new byte[1];
        fixed (byte* ptr = numArray)
        {
            *(sbyte*) ptr = value;
        }
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from an array of sbyte objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this sbyte[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (sbyte[]) object cannot be null.");
        var numArray = new byte[value.Length];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single short object
    ///     (Converters.cs)
    /// </summary>
    [SecuritySafeCritical]
    public static unsafe byte[] GetBytes(this short value)
    {
        var numArray = new byte[2];
        fixed (byte* ptr = numArray)
        {
            *(short*) ptr = value;
        }
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from an array of short objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this short[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (short[]) object cannot be null.");
        var numArray = new byte[value.Length * 2];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single unsigned short object
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this ushort value)
    {
        return ((short) value).GetBytes();
    }
    /// <summary>
    ///     Get Bytes from an array of unsigned short objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this ushort[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (ushort[]) object cannot be null.");
        var numArray = new byte[value.Length * 2];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single character object
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this char value)
    {
        return ((short) value).GetBytes();
    }
    /// <summary>
    ///     Get Bytes from an array of character objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this char[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (char[]) object cannot be null.");
        var numArray = new byte[value.Length * 2];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single integer object
    ///     (Converters.cs)
    /// </summary>
    [SecuritySafeCritical]
    public static unsafe byte[] GetBytes(this int value)
    {
        var numArray = new byte[4];
        fixed (byte* ptr = numArray)
        {
            *(int*) ptr = value;
        }
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single integer object with index and count
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this int value, int sIndex, int count)
    {
        if (count > 4)
            throw new Exception("Size cannot exceed 4 bytes.");
        return value.GetBytes().SubArray(sIndex, count);
    }
    /// <summary>
    ///     Get Bytes from an array of integer objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this int[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (int[]) object cannot be null.");
        var numArray = new byte[value.Length * 4];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single unsigned integer object
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this uint value)
    {
        return ((int) value).GetBytes();
    }
    public static byte[] GetBytes(this uint value, int sIndex = 0, int count = 4)
    {
        if (count > 4)
            throw new Exception("Size cannot exceed 4 bytes.");
        return value.GetBytes().SubArray(sIndex, count);
    }
    /// <summary>
    ///     Get Bytes from an array of unsigned integer objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this uint[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (uint[]) object cannot be null.");
        var numArray = new byte[value.Length * 4];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single long object
    ///     (Converters.cs)
    /// </summary>
    public static unsafe byte[] GetBytes(this long value)
    {
        var numArray = new byte[8];
        fixed (byte* ptr = numArray)
        {
            *(long*) ptr = value;
        }
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from an array of long objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this long[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (long[]) object cannot be null.");
        var numArray = new byte[value.Length * 8];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from an array of long objects with index and count
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this long value, int sIndex = 0, int count = 8)
    {
        if (count > 8)
            throw new Exception("Size cannot exceed 8 bytes.");
        return value.GetBytes().SubArray(sIndex, count);
    }
    /// <summary>
    ///     Get Bytes from a single unsigned long object
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this ulong value)
    {
        return ((long) value).GetBytes();
    }
    public static byte[] GetBytes(this ulong value, int sIndex = 0, int count = 8)
    {
        if (count > 8)
            throw new Exception("Size cannot exceed 8 bytes.");
        return ((long) value).GetBytes().SubArray(sIndex, count);
    }
    /// <summary>
    ///     Get Bytes from an array of unsigned long objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this ulong[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (ulong[]) object cannot be null.");
        var numArray = new byte[value.Length * 8];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single float object
    ///     (Converters.cs)
    /// </summary>
    [SecuritySafeCritical]
    public static unsafe byte[] GetBytes(this float value)
    {
        return (*(int*) &value).GetBytes();
    }
    /// <summary>
    ///     Get Bytes from an array of float objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this float[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (float[]) object cannot be null.");
        var numArray = new byte[value.Length * 4];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single double object
    ///     (Converters.cs)
    /// </summary>
    public static unsafe byte[] GetBytes(this double value)
    {
        return (*(long*) &value).GetBytes();
    }
    /// <summary>
    ///     Get Bytes from an array of double objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this double[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (double[]) object cannot be null.");
        var numArray = new byte[value.Length * 8];
        Buffer.BlockCopy(value, 0, numArray, 0, numArray.Length);
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single decimal object
    ///     (Converters.cs)
    /// </summary>
    public static unsafe byte[] GetBytes(this decimal value)
    {
        var array = new byte[16];
        fixed (byte* bp = array)
        {
            *(decimal*) bp = value;
        }
        return array;
    }
    /// <summary>
    ///     Get Bytes from a single DateTime object
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this DateTime value)
    {
        return value.Ticks.GetBytes();
    }
    public static byte[] GetBytes(this DateTime[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (DateTime[]) object cannot be null.");
        var sodt = 0;
        unsafe
        {
            sodt = sizeof(DateTime);
        }
        var numArray = new byte[value.Length * sodt];
        for (var i = 0; i < value.Length; i++)
        {
            var dba = value[i].GetBytes();
            Buffer.BlockCopy(dba, 0, numArray, i * sodt, sodt);
        }
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from an array of decimal objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this decimal[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (decimal[]) object cannot be null.");
        var numArray = new byte[value.Length * 16];
        for (var i = 0; i < value.Length; i++)
        {
            var dba = value[i].GetBytes();
            Buffer.BlockCopy(dba, 0, numArray, i * 16, 16);
        }
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from a single string object using a specified Encoding.
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this string value, Encoding enc = null)
    {
        if (value == null)
            throw new Exception("GetBytes (string) object cannot be null.");
        if (enc == null)
            return Encoding.ASCII.GetBytes(value);
        switch (enc)
        {
            case ASCIIEncoding AsciiEncoding:
            {
                return Encoding.ASCII.GetBytes(value);
            }
            case UnicodeEncoding UnicodeEncoding:
            {
                var ba  = Encoding.Unicode.GetBytes(value);
                var pre = new byte[] {0xff, 0xfe};
                var ra  = new byte[ba.Length + 2];
                Array.Copy(pre, 0, ra, 0, 2);
                Array.Copy(ba,  0, ra, 2, ba.Length);
                return ra;
            }
            case UTF32Encoding Utf32Encoding:
            {
                var ba  = Encoding.UTF32.GetBytes(value);
                var pre = new byte[] {0xff, 0xfe, 0, 0};
                var ra  = new byte[ba.Length + 4];
                Array.Copy(pre, 0, ra, 0, 4);
                Array.Copy(ba,  0, ra, 4, ba.Length);
                return ra;
            }
            case UTF7Encoding Utf7Encoding:
            {
                var ba  = Encoding.UTF7.GetBytes(value);
                var pre = new byte[] {0x2b, 0x2f, 0x76};
                var ra  = new byte[ba.Length + 3];
                Array.Copy(pre, 0, ra, 0, 3);
                Array.Copy(ba,  0, ra, 3, ba.Length);
                return ra;
            }
            case UTF8Encoding Utf8Encoding:
            {
                var ba  = Encoding.UTF8.GetBytes(value);
                var pre = new byte[] {0xef, 0xbb, 0xbf};
                var ra  = new byte[ba.Length + 3];
                Array.Copy(pre, 0, ra, 0, 3);
                Array.Copy(ba,  0, ra, 3, ba.Length);
                return ra;
            }
            default:
                return Encoding.ASCII.GetBytes(value);
        }
    }
    /// <summary>
    ///     Get Bytes from a array of string objects.
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this string[] value, Encoding enc = null)
    {
        if (value == null)
            throw new Exception("GetBytes (string[]) object cannot be null.");
        var numArray  = new byte[value.Where(ss => ss != null).Sum(ss => ss.Length)];
        var dstOffset = 0;
        foreach (var str in value)
            if (str != null)
            {
                Buffer.BlockCopy(str.GetBytes(enc), 0, numArray, dstOffset, str.Length);
                dstOffset += str.Length;
            }
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from an array of string objects.??
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes1(this string[] value, Encoding enc = null)
    {
        if (value == null)
            throw new Exception("GetBytes (string[]) object cannot be null.");
        var tb        = value[0].GetBytes(enc);
        var cs        = tb.Length / value[0].Length;
        var numArray  = new byte[value.Where(ss => ss != null).Sum(ss => ss.Length) * cs];
        var dstOffset = 0;
        foreach (var str in value)
            if (str != null)
            {
                var buf = str.GetBytes(enc);
                Buffer.BlockCopy(buf, 0, numArray, dstOffset, buf.Length);
                dstOffset += buf.Length;
            }
        return numArray;
    }
    /// <summary>
    ///     Get Bytes from an array of secure string objects
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytes(this SecureString[] value)
    {
        if (value == null)
            throw new Exception("GetBytes (SecureString[]) object cannot be null.");
        var source = new List<byte[]>();
        foreach (var secureString in value)
            if (secureString != null)
            {
                var byteArray = secureString.GetBytes();
                source.Add(byteArray.CloneTo());
            }
        var seed = new byte[source.Sum(ba => ba.Length)];
        return source.Aggregate(seed, (Current, ba) => Current.Add(ba));
    }
    /// <summary>
    ///     Get Bytes from a single secure string object using a specified encoding
    ///     (Converters.cs)
    /// </summary>
    public static unsafe byte[] GetBytes(this SecureString value, Encoding enc = null)
    {
        if (value == null)
            throw new Exception("GetBytes (SecureString) object cannot be null.");
        if (enc == null)
            enc = Encoding.Default;
        var maxLength = enc.GetMaxByteCount(value.Length);
        var bytes     = IntPtr.Zero;
        var str       = IntPtr.Zero;
        try
        {
            bytes = Marshal.AllocHGlobal(maxLength);
            str   = Marshal.SecureStringToBSTR(value);
            var chars  = (char*) str.ToPointer();
            var bptr   = (byte*) bytes.ToPointer();
            var len    = enc.GetBytes(chars, value.Length, bptr, maxLength);
            var _bytes = new byte[len];
            for (var i = 0; i < len; ++i)
            {
                _bytes[i] = *bptr;
                bptr++;
            }
            return _bytes;
        }
        finally
        {
            if (bytes != IntPtr.Zero)
                Marshal.FreeHGlobal(bytes);
            if (str != IntPtr.Zero)
                Marshal.ZeroFreeBSTR(str);
        }
    }
    /// <summary>
    ///     Get Bytes from a object array with an optional object type specified.
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytesObjectGen(this object[] value, Type type = null)
    {
        return value.SelectMany(o => GetBytesObject(o, type)).ToArray();
    }
    /// <summary>
    ///     Get Bytes from a single object with an optional object type specified.
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytesObject(this object obj, Type type = null)
    {
        Type _type;
        if (type == null)
            _type = obj.GetType();
        else
            _type = type;
        switch (_type.Name.Trim('[', ']'))
        {
            case "Byte":
                return !_type.IsArray ? new byte[1] {(byte) obj} : (byte[]) obj;
                break;
            case "Boolean":
                return !_type.IsArray ? ((bool) obj).GetBytes() : ((bool[]) obj).GetBytes();
                break;
            case "SByte":
                return !_type.IsArray ? ((sbyte) obj).GetBytes() : ((sbyte[]) obj).GetBytes();
                break;
            case "Char":
                return !_type.IsArray ? ((char) obj).GetBytes() : ((char[]) obj).GetBytes();
                break;
            case "Int16":
                return !_type.IsArray ? ((short) obj).GetBytes() : ((short[]) obj).GetBytes();
                break;
            case "UInt16":
                return !_type.IsArray ? ((ushort) obj).GetBytes() : ((ushort[]) obj).GetBytes();
                break;
            case "Int32":
                return !_type.IsArray ? ((int) obj).GetBytes() : ((int[]) obj).GetBytes();
                break;
            case "UInt32":
                return !_type.IsArray ? ((uint) obj).GetBytes() : ((uint[]) obj).GetBytes();
                break;
            case "Int64":
                return !_type.IsArray ? ((long) obj).GetBytes() : ((long[]) obj).GetBytes();
                break;
            case "UInt64":
                return !_type.IsArray ? ((ulong) obj).GetBytes() : ((ulong[]) obj).GetBytes();
                break;
            case "Single":
                return !_type.IsArray ? ((float) obj).GetBytes() : ((float[]) obj).GetBytes();
                break;
            case "Double":
                return !_type.IsArray ? ((double) obj).GetBytes() : ((double[]) obj).GetBytes();
                break;
            case "String":
                return !_type.IsArray ? ((string) obj).GetBytes() : ((string[]) obj).GetBytes();
                break;
            case "Decimal":
                return !_type.IsArray ? ((decimal) obj).GetBytes() : ((decimal[]) obj).GetBytes();
                break;
            case "DateTime":
                return !_type.IsArray ? ((DateTime) obj).GetBytes() : ((DateTime[]) obj).GetBytes();
                break;
        }
        if (_type == typeof(BigInteger))
            return ((BigInteger) obj).ToByteArray();
        if (_type == typeof(SecureString))
            return ((SecureString) obj).GetBytes();
        if (_type == typeof(SecureString[]))
            return ((SecureString[]) obj).GetBytes();
        if (!_type.IsSerializable)
            throw new Exception("Error: Object is not Serializable.");
        var _fs        = new MemoryStream();
        var _formatter = new BinaryFormatter();
        _formatter.Serialize(_fs, obj);
        return _fs.GetBuffer().SubByte(0, (int) _fs.Length);
    }
    /// <summary>
    ///     Gets list of byte arrays from a list of objects of type T.
    ///     (Converters.cs)
    /// </summary>
    public static List<byte[]> GetBytesObject<T>(this List<T> value)
    {
        return value.Select(o => o.GetBytesObjectSerial()).ToList();
    }
    /// <summary>
    ///     Get Bytes from a single object with an optional object type specified.
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytesObjectSerial(this object value)
    {
        var type = value.GetType();
        if (!type.IsSerializable)
            throw new Exception("Error: Object is not Serializable.");
        using (var _fs = new MemoryStream())
        {
            var _formatter = new BinaryFormatter();
            _formatter.Serialize(_fs, value);
            return _fs.ToArray().SubArray(0, (int) _fs.Length);
        }
    }
    /// <summary>
    ///     Gets a single object of type T from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static T ToObject<T>(this byte[] value)
    {
        if (value == null)
            throw new Exception("value cannot be null.");
        using (var stream = new MemoryStream(value))
        {
            var formatter = new BinaryFormatter();
            var result    = (T) formatter.Deserialize(stream);
            return result;
        }
    }
    /// <summary>
    ///     Gets an array of objects of type T from a list of byte arrays.
    ///     (Converters.cs)
    /// </summary>
    public static T[] ToObject<T>(this List<byte[]> value)
    {
        if (value == null)
            throw new Exception("value cannot be null.");
        if (value.Count == 0)
            throw new Exception("value is empty.");
        var lst = new List<T>();
        foreach (var o in value)
            lst.Add(o.ToObject<T>());
        return lst.ToArray();
    }
    /// <summary>
    ///     Converts a hex string to a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static byte[] HexToBytes(this string hex)
    {
        if (hex.Length % 2 != 0)
            throw new Exception($"Incomplete Hex string {hex}");
        if (!hex.ContainsOnly("0123456789abcdefABCDEFxX"))
            throw new Exception("Error: hexNumber cannot contain characters other than 0-9,a-f,A-F, or xX");
        hex = hex.ToUpper();
        if (hex.IndexOf("0X", StringComparison.OrdinalIgnoreCase) != -1)
            hex = hex.Substring(2);
        return Enumerable.Range(0, hex.Length).Where(x => x % 2 == 0).Select(x => Convert.ToByte(hex.Substring(x, 2), 16)).ToArray();
    }
    /// <summary>
    ///     Converts a byte array to a hex string.
    ///     (Converters.cs)
    /// </summary>
    public static string ToHexString(this byte[] bytes)
    {
        var sb = new StringBuilder();
        foreach (var b in bytes)
            sb.Append(b.ToString("X2"));
        return sb.ToString();
    }
    /// <summary>
    ///     Converts a hex string to an unsigned long.
    ///     (Converters.cs)
    /// </summary>
    public static unsafe ulong FromHexStringTo(this string value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        if (value.Length == 0)
            return 0;
        var ba = value.HexToBytes();
        ba = ba.Invert();
        if (ba.Length > 8)
            throw new Exception("Maximum bit width is limited to 64 bits.");
        var len = ba.Length;
        switch (len)
        {
            case 1:
                fixed (byte* ptr = &ba[0])
                {
                    return *ptr;
                }
            case 2:
                fixed (byte* ptr = &ba[0])
                {
                    return *ptr | ((ulong) ptr[1] << 8);
                }
            case 3:
                fixed (byte* ptr = &ba[0])
                {
                    return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16);
                }
            case 4:
                fixed (byte* ptr = &ba[0])
                {
                    return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24);
                }
            case 5:
                fixed (byte* ptr = &ba[0])
                {
                    return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24) | ((ulong) ptr[4] << 32);
                }
            case 6:
                fixed (byte* ptr = &ba[0])
                {
                    return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24) | ((ptr[4] | ((ulong) ptr[5] << 8)) << 32);
                }
            case 7:
                fixed (byte* ptr = &ba[0])
                {
                    return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24) | ((ptr[4] | ((ulong) ptr[5] << 8) | ((ulong) ptr[6] << 16)) << 32);
                }
            case 8:
                fixed (byte* ptr = &ba[0])
                {
                    return *ptr | ((ulong) ptr[1] << 8) | ((ulong) ptr[2] << 16) | ((ulong) ptr[3] << 24) | ((ptr[4] | ((ulong) ptr[5] << 8) | ((ulong) ptr[6] << 16) | ((ulong) ptr[7] << 24)) << 32);
                }
            default:
                return 0;
        }
    }
    /// <summary>
    ///     Converts a byte array to a hex string.
    ///     (Converters.cs)
    /// </summary>
    public static string ToBinaryString(this byte[] bytes)
    {
        var len = bytes.Length;
        var sb  = new StringBuilder();
        for (var i = 0; i < len; i++)
            sb.Append(Convert.ToString(bytes[i], 2).PadLeft(8, '0'));
        return sb.ToString();
    }
    /// <summary>
    ///     Converts a binary string to an unsigned long.
    ///     (Converters.cs)
    /// </summary>
    public static ulong FromBinaryStringTo(this string value)
    {
        var reversed = value.Reverse().ToArray();
        var num      = 0ul;
        for (var p = 0; p < reversed.Count(); p++)
        {
            if (reversed[p] != '1')
                continue;
            num += (ulong) Math.Pow(2, p);
        }
        return num;
    }
    /// <summary>
    ///     Converts a binary string to a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static byte[] GetBytesFromBinaryString(this string value)
    {
        if (!value.ContainsOnly("01"))
            throw new Exception($"Error: Binary string can only contains 0's and 1's. Value:{value}");
        var len   = value.Length;
        var bLen  = (int) Math.Ceiling(len / 8d);
        var bytes = new byte[bLen];
        var size  = 8;
        for (var i = 1; i <= bLen; i++)
        {
            var idx = len - 8 * i;
            if (idx < 0)
            {
                size = 8 + idx;
                idx  = 0;
            }
            bytes[bLen - i] = Convert.ToByte(value.Substring(idx, size), 2);
        }
        return bytes;
    }
    /// <summary>
    ///     Converts a byte array to a octal string.
    ///     (Converters.cs)
    /// </summary>
    public static string ToOctalString(this byte[] value)
    {
        value = value.Invert();
        var index = value.Length - 1;
        var base8 = new StringBuilder();
        var rem   = value.Length % 3;
        if (rem == 0)
            rem = 3;
        var Base = 0;
        while (rem != 0)
        {
            Base <<= 8;
            Base +=  value[index--];
            rem--;
        }
        base8.Append(Convert.ToString(Base, 8));
        while (index >= 0)
        {
            Base = (value[index] << 16) + (value[index - 1] << 8) + value[index - 2];
            base8.Append(Convert.ToString(Base, 8).PadLeft(8, '0'));
            index -= 3;
        }
        return base8.ToString();
    }
    /// <summary>
    ///     Returns a Boolean value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static bool ToBool(this byte[] value, int pos = 0)
    {
        return BitConverter.ToBoolean(value, pos);
    }
    /// <summary>
    ///     Returns a Character value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static char ToChar(this byte[] value, int pos = 0)
    {
        return BitConverter.ToChar(value, pos);
    }
    public static unsafe byte ToByte(this byte[] value, int pos = 0)
    {
        byte bv;
        fixed (byte* bp = value)
        {
            var bpp = bp + pos;
            bv = *bpp;
            return bv;
        }
    }
    public static unsafe sbyte ToSByte(this byte[] value, int pos = 0)
    {
        fixed (byte* bp = value)
        {
            var ptr = bp + pos;
            if (pos % 2 == 0)
                return *(sbyte*) ptr;
            return (sbyte) *ptr;
        }
    }
    /// <summary>
    ///     Returns a Short value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static short ToShort(this byte[] value, int pos = 0)
    {
        return BitConverter.ToInt16(PadShort(value), pos);
    }
    /// <summary>
    ///     Returns a Unsigned Short value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static ushort ToUShort(this byte[] value, int pos = 0)
    {
        return BitConverter.ToUInt16(PadShort(value), pos);
    }
    /// <summary>
    ///     Returns a Integer value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static int ToInt(this byte[] value, int pos = 0)
    {
        return BitConverter.ToInt32(PadInt(value), pos);
    }
    /// <summary>
    ///     Returns a Unsigned Integer value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static uint ToUInt(this byte[] value, int pos = 0)
    {
        return BitConverter.ToUInt32(PadInt(value), pos);
    }
    /// <summary>
    ///     Returns a Long value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static long ToLong(this byte[] value, int pos = 0)
    {
        return BitConverter.ToInt64(PadLong(value), pos);
    }
    /// <summary>
    ///     Returns a Unsigned Long value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static ulong ToULong(this byte[] value, int pos = 0)
    {
        return BitConverter.ToUInt64(PadLong(value), pos);
    }
    /// <summary>
    ///     Returns a Float value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static float ToFloat(this byte[] value, int pos = 0)
    {
        return BitConverter.ToSingle(PadInt(value), pos);
    }
    /// <summary>
    ///     Returns a Double value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static double ToDouble(this byte[] value, int pos = 0)
    {
        return BitConverter.ToDouble(PadLong(value), pos);
    }
    /// <summary>
    ///     Returns a Decimal value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static unsafe decimal ToDecimal(this byte[] value, int pos = 0)
    {
        decimal dv;
        fixed (byte* bp = value)
        {
            var bpp = bp + pos;
            dv = *(decimal*) bpp;
        }
        return dv;
    }
    /// <summary>
    ///     Returns a String value converted from the byte at a specified position.
    ///     (Converters.cs)
    /// </summary>
    public static string ToString(this byte[] value, int pos = 0)
    {
        return BitConverter.ToString(value, pos);
    }
    /// <summary>
    ///     Returns a Secure String value converted from the byte array.
    ///     (Converters.cs)
    /// </summary>
    public static SecureString ToSecureString(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var securestring = new SecureString();
        var asCharA      = value.ToCharArray();
        foreach (var c in asCharA)
            securestring.AppendChar(c);
        return securestring;
    }
    /// <summary>
    ///     Returns a Boolean array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static bool[] ToBooleanArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var arr = new bool[value.Length];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    /// <summary>
    ///     Returns a Character array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static char[] ToCharArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var arr = new char[value.Length];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    public static byte[] ToByteArray(this byte[] value, int index = 0, int length = -1)
    {
        if (length == -1)
            length = value.Length - index;
        var ba = new byte[length];
        Buffer.BlockCopy(value, index, ba, 0, length);
        return ba;
    }
    /// <summary>
    ///     Returns a SByte array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static sbyte[] ToSByteArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var arr = new sbyte[value.Length];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    /// <summary>
    ///     Returns a Short array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static short[] ToShortArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var arr = new short[value.Length / 2];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    /// <summary>
    ///     Returns a Unsigned Short array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static ushort[] ToUShortArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var arr = new ushort[value.Length / 2];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    /// <summary>
    ///     Returns a Integer array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static int[] ToIntArray(this byte[] value, bool pad = false)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        if (pad)
            value = PadInt(value);
        var arr = new int[value.Length / 4];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    /// <summary>
    ///     Returns a Unsigned Integer array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static uint[] ToUIntArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var arr = new uint[value.Length / 4];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    /// <summary>
    ///     Returns a Long array converted from the byte array.
    ///     (Converters.cs)
    /// </summary>
    public static long[] ToLongArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var arr = new long[value.Length / 8];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    /// <summary>
    ///     Returns a Unsigned Long array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static ulong[] ToULongArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var arr = new ulong[value.Length / 8];
        Buffer.BlockCopy(value, 0, arr, 0, value.Length);
        return arr;
    }
    /// <summary>
    ///     Returns a Float array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static float[] ToFloatArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        if (value.Length % 4 != 0)
            throw new Exception("Byte Object length must be a multiple of 4");
        var arr = new List<float>();
        for (var i = 0; i < value.Length; i += 4)
        {
            var t = new[] {value[i], value[i + 1], value[i + 2], value[i + 3]};
            arr.Add(t.ToFloat());
        }
        return arr.ToArray();
    }
    /// <summary>
    ///     Returns a Double array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static double[] ToDoubleArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        if (value.Length % 8 != 0)
            throw new Exception("Byte Object length must be a multiple of 8");
        var arr = new List<double>();
        for (var i = 0; i < value.Length; i += 8)
        {
            var t = new[]
            {
                value[i], value[i + 1], value[i + 2], value[i + 3], value[i + 4], value[i + 5], value[i + 6],
                value[i           + 7]
            };
            arr.Add(t.ToDouble());
        }
        return arr.ToArray();
    }
    /// <summary>
    ///     Returns a decimal array converted from a byte array.
    ///     (Converters.cs)
    /// </summary>
    public static decimal[] ToDecimalArray(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        if (value.Length % 16 != 0)
            throw new Exception("Byte Object length must be a multiple of 16");
        var arr = new List<decimal>();
        for (var i = 0; i < value.Length; i += 16)
        {
            var t = new[]
            {
                value[i], value[i + 1], value[i + 2], value[i + 3], value[i + 4], value[i  + 5], value[i  + 6],
                value[i           + 7], value[i + 8], value[i + 9], value[i + 10], value[i + 11], value[i + 12],
                value[i           + 13],
                value[i           + 14], value[i + 15]
            };
            arr.Add(t.ToDecimal());
        }
        return arr.ToArray();
    }
    /// <summary>
    ///     Returns a Single String converted from the byte array.
    ///     (Converters.cs)
    /// </summary>
    public static string ToSingleString(this byte[] value)
    {
        if (value == null)
            throw new Exception("Value cannot be null.");
        var enc = GetEncoding(value);
        switch (enc)
        {
            case ASCIIEncoding AsciiEncoding:
                return Encoding.ASCII.GetString(value);
            case UnicodeEncoding UnicodeEncoding:
                return Encoding.Unicode.GetString(value);
            case UTF32Encoding Utf32Encoding:
                return Encoding.UTF32.GetString(value);
            case UTF7Encoding Utf7Encoding:
                return Encoding.UTF7.GetString(value);
            case UTF8Encoding Utf8Encoding:
                return Encoding.UTF8.GetString(value);
            default:
                return Encoding.ASCII.GetString(value);
        }
    }
    private static Encoding GetEncoding(byte[] Data)
    {
        if (Data == null)
            throw new Exception("Array cannot be null.");
        if (Data.Length < 2)
            return Encoding.Default;
        if (Data[0] == 0xff && Data[1] == 0xfe)
            return Encoding.Unicode;
        if (Data[0] == 0xfe && Data[1] == 0xff)
            return Encoding.BigEndianUnicode;
        if (Data.Length < 3)
            return Encoding.Default;
        if (Data[0] == 0xef && Data[1] == 0xbb && Data[2] == 0xbf)
            return Encoding.UTF8;
        if (Data[0] == 0x2b && Data[1] == 0x2f && Data[2] == 0x76)
            return Encoding.UTF7;
        if (Data.Length < 4)
            return Encoding.Default;
        if (Data[0] == 0xff && Data[1] == 0xfe && Data[2] == 0 && Data[3] == 0)
            return Encoding.UTF32;
        return Encoding.Default;
    }
    public static bool ToBool(this string value)
    {
        bool result = default;
        if (!string.IsNullOrEmpty(value))
            bool.TryParse(value, out result);
        return result;
    }
    public static char ToChar(this string value)
    {
        char result = default;
        if (!string.IsNullOrEmpty(value))
            char.TryParse(value, out result);
        return result;
    }
    public static byte ToByte(this string value)
    {
        byte result = default;
        if (!string.IsNullOrEmpty(value))
            byte.TryParse(value, out result);
        return result;
    }
    public static sbyte ToSByte(this string value)
    {
        sbyte result = default;
        if (!string.IsNullOrEmpty(value))
            sbyte.TryParse(value, out result);
        return result;
    }
    public static short ToInt16(this string value)
    {
        short result = 0;
        if (!string.IsNullOrEmpty(value))
            short.TryParse(value, out result);
        return result;
    }
    public static ushort ToUInt16(this string value)
    {
        ushort result = 0;
        if (!string.IsNullOrEmpty(value))
            ushort.TryParse(value, out result);
        return result;
    }
    public static int ToInt32(this string value)
    {
        var result = 0;
        if (!string.IsNullOrEmpty(value))
            int.TryParse(value, out result);
        return result;
    }
    public static uint ToUInt32(this string value)
    {
        uint result = 0;
        if (!string.IsNullOrEmpty(value))
            uint.TryParse(value, out result);
        return result;
    }
    public static long ToInt64(this string value)
    {
        long result = 0;
        if (!string.IsNullOrEmpty(value))
            long.TryParse(value, out result);
        return result;
    }
    public static ulong ToUInt64(this string value)
    {
        ulong result = 0;
        if (!string.IsNullOrEmpty(value))
            ulong.TryParse(value, out result);
        return result;
    }
    public static float ToFloat(this string value)
    {
        float result = 0;
        if (!string.IsNullOrEmpty(value))
            float.TryParse(value, out result);
        return result;
    }
    public static double ToDouble(this string value)
    {
        double result = 0;
        if (!string.IsNullOrEmpty(value))
            double.TryParse(value, out result);
        return result;
    }
    public static decimal ToDecimal(this string value)
    {
        decimal result = 0;
        if (!string.IsNullOrEmpty(value))
            decimal.TryParse(value, out result);
        return result;
    }
    public static bool ToBool(this char value)
    {
        bool result = default;
        if (!string.IsNullOrEmpty(value.ToString()))
            bool.TryParse(value.ToString(), out result);
        return result;
    }
    public static byte ToByte(this char value)
    {
        byte result = default;
        if (!string.IsNullOrEmpty(value.ToString()))
            byte.TryParse(value.ToString(), out result);
        return result;
    }
    public static sbyte ToSByte(this char value)
    {
        sbyte result = default;
        if (!string.IsNullOrEmpty(value.ToString()))
            sbyte.TryParse(value.ToString(), out result);
        return result;
    }
    public static short ToInt16(this char value)
    {
        short result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            short.TryParse(value.ToString(), out result);
        return result;
    }
    public static ushort ToUInt16(this char value)
    {
        ushort result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            ushort.TryParse(value.ToString(), out result);
        return result;
    }
    public static int ToInt32(this char value)
    {
        var result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            int.TryParse(value.ToString(), out result);
        return result;
    }
    public static uint ToUInt32(this char value)
    {
        uint result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            uint.TryParse(value.ToString(), out result);
        return result;
    }
    public static long ToInt64(this char value)
    {
        long result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            long.TryParse(value.ToString(), out result);
        return result;
    }
    public static ulong ToUInt64(this char value)
    {
        ulong result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            ulong.TryParse(value.ToString(), out result);
        return result;
    }
    public static float ToFloat(this char value)
    {
        float result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            float.TryParse(value.ToString(), out result);
        return result;
    }
    public static double ToDouble(this char value)
    {
        double result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            double.TryParse(value.ToString(), out result);
        return result;
    }
    public static decimal ToDecimal(this char value)
    {
        decimal result = 0;
        if (!string.IsNullOrEmpty(value.ToString()))
            decimal.TryParse(value.ToString(), out result);
        return result;
    }
    private static byte[] PadLong(byte[] ba)
    {
        var s = ba.Length % 8;
        switch (s)
        {
            case 0:
                break;
            case 1:
                Array.Resize(ref ba, ba.Length + 7);
                ba[ba.Length - 1] = 0;
                ba[ba.Length - 2] = 0;
                ba[ba.Length - 3] = 0;
                ba[ba.Length - 4] = 0;
                ba[ba.Length - 5] = 0;
                ba[ba.Length - 6] = 0;
                ba[ba.Length - 7] = 0;
                break;
            case 2:
                Array.Resize(ref ba, ba.Length + 6);
                ba[ba.Length - 1] = 0;
                ba[ba.Length - 2] = 0;
                ba[ba.Length - 3] = 0;
                ba[ba.Length - 4] = 0;
                ba[ba.Length - 5] = 0;
                ba[ba.Length - 6] = 0;
                break;
            case 3:
                Array.Resize(ref ba, ba.Length + 5);
                ba[ba.Length - 1] = 0;
                ba[ba.Length - 2] = 0;
                ba[ba.Length - 3] = 0;
                ba[ba.Length - 4] = 0;
                ba[ba.Length - 5] = 0;
                break;
            case 4:
                Array.Resize(ref ba, ba.Length + 4);
                ba[ba.Length - 1] = 0;
                ba[ba.Length - 2] = 0;
                ba[ba.Length - 3] = 0;
                ba[ba.Length - 4] = 0;
                break;
            case 5:
                Array.Resize(ref ba, ba.Length + 3);
                ba[ba.Length - 1] = 0;
                ba[ba.Length - 2] = 0;
                ba[ba.Length - 3] = 0;
                break;
            case 6:
                Array.Resize(ref ba, ba.Length + 2);
                ba[ba.Length - 1] = 0;
                ba[ba.Length - 2] = 0;
                break;
            case 7:
                Array.Resize(ref ba, ba.Length + 1);
                ba[ba.Length - 1] = 0;
                break;
        }
        return ba;
    }
    private static byte[] PadInt(byte[] ba)
    {
        var s = ba.Length % 4;
        switch (s)
        {
            case 0:
                break;
            case 1:
                Array.Resize(ref ba, ba.Length + 3);
                ba[ba.Length - 1] = 0;
                ba[ba.Length - 2] = 0;
                ba[ba.Length - 3] = 0;
                break;
            case 2:
                Array.Resize(ref ba, ba.Length + 2);
                ba[ba.Length - 1] = 0;
                ba[ba.Length - 2] = 0;
                break;
            case 3:
                Array.Resize(ref ba, ba.Length + 1);
                ba[ba.Length - 1] = 0;
                break;
        }
        return ba;
    }
    private static byte[] PadShort(byte[] ba)
    {
        var s = ba.Length % 2;
        switch (s)
        {
            case 0:
                break;
            case 1:
                Array.Resize(ref ba, ba.Length + 1);
                ba[ba.Length - 1] = 0;
                break;
        }
        return ba;
    }
}

PasswordStretch.cs

Posted on June 13, 2020June 13, 2020Tags , , ,   Leave a comment on PasswordStretch.cs

Password Stretch using Sha3

Example Code:
var b1   = new byte[0];
        var b2   = new byte[0];
        var salt = new byte[0];
        using (var db = new PasswordStretch("1234567890".ToSecureString(), 16))
        {

            b1   = (byte[]) db.GetBytes(0, 64).Clone();
            salt = db.Salt;
        }

        using (var db = new PasswordStretch("1234567891".ToSecureString(), salt))
        {

            b2 = (byte[]) db.GetBytes(0, 64).Clone();
        }
using System;
using System.Security;
using System.Security.Cryptography;
public class PasswordStretch : IDisposable
{
    private const    int         PacketCount = 4;
    private readonly byte[]      _buffer;
    private readonly byte[]      _salt;
    private readonly SHA3Managed _sha;
    public PasswordStretch(SecureString password) : this(password, 0, 1000)
    {
    }
    public PasswordStretch(SecureString password, int saltSize) : this(password, saltSize, 1000)
    {
    }
    public PasswordStretch(SecureString password, int saltSize, int iterations)
    {
        Iterations = iterations;
        var temp = new byte[0];
        if (saltSize != 0)
        {
            var data = new byte[saltSize];
            new RNGCryptoServiceProvider().GetBytes(data);
            _salt   = data;
            _sha    = new SHA3Managed(512);
            _buffer = new byte[_sha.HashLength * PacketCount];
            _sha.TransformBlock(_salt, 0, _salt.Length, null, 0);
            var pwb = password.GetBytes();
            _sha.TransformBlock(pwb, 0, pwb.Length, null, 0);
            _sha.Finalize();
            temp = _sha.HashValue;
        }
        else
        {
            _sha    = new SHA3Managed(512);
            _buffer = new byte[_sha.HashLength * PacketCount];
            temp    = _sha.ComputeHash(password.GetBytes());
        }
        for (var i = 0; i < PacketCount; i++)
        {
            for (var j = 0; j < Iterations; j++)
                temp = _sha.ComputeHash(temp);
            Buffer.BlockCopy(temp, 0, _buffer, i * _sha.HashLength, _sha.HashLength);
        }
    }
    public PasswordStretch(SecureString password, byte[] salt) : this(password, salt, 1000)
    {
    }
    public PasswordStretch(SecureString password, byte[] salt, int iterations = 1000)
    {
        Iterations = iterations;
        _sha       = new SHA3Managed(512);
        _buffer    = new byte[_sha.HashLength * PacketCount];
        _sha.TransformBlock(salt, 0, salt.Length, null, 0);
        var pwb = password.GetBytes();
        _sha.TransformBlock(pwb, 0, pwb.Length, null, 0);
        _sha.Finalize();
        var temp = _sha.HashValue;
        for (var i = 0; i < PacketCount; i++)
        {
            for (var j = 0; j < Iterations; j++)
                temp = _sha.ComputeHash(temp);
            Buffer.BlockCopy(temp, 0, _buffer, i * _sha.HashLength, _sha.HashLength);
        }
    }
    public byte[] Salt
    {
        get
        {
            if (_salt != null)
                return (byte[]) _salt.Clone();
            return default;
        }
    }
    public int Iterations
    {
        get;
    } = 1000;
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    ~PasswordStretch()
    {
        Dispose();
    }
    public byte[] GetBytes(int offset, int psize)
    {
        if (offset + psize > _buffer.Length)
            throw new Exception("Offset and Size Exceed Buffer Length.");
        var passpart = new byte[psize];
        Buffer.BlockCopy(_buffer, offset, passpart, 0, passpart.Length);
        return passpart;
    }
    private void Dispose(bool disposing)
    {
        if (!disposing)
            return;
        if (_sha != null)
            _sha.Dispose();
        if (_buffer != null)
            Array.Clear(_buffer, 0, _buffer.Length);
        if (_salt == null)
            return;
        Array.Clear(_salt, 0, _salt.Length);
    }
}