Exemple #1
0
        public static byte[] HexToBinary(string hex)
        {
            const string IGNORED_CHARS = ":- ";

            var arr = new byte[hex.Length >> 1];
            var bin = Marshal.AllocHGlobal(arr.Length);
            int binLength;

            //we call sodium_hex2bin with some chars to be ignored
            var ret = NativeLibsodium.sodium_hex2bin(bin, arr.Length, hex, hex.Length, IGNORED_CHARS, out binLength, null);

            Marshal.Copy(bin, arr, 0, binLength);
            Marshal.FreeHGlobal(bin);

            if (ret != 0)
            {
                throw new Exception("Internal error, decoding failed.");
            }

            //remove the trailing nulls from the array, if there were some format characters in the hex string before
            if (arr.Length != binLength)
            {
                var tmp = new byte[binLength];
                Array.Copy(arr, 0, tmp, 0, binLength);
                return(tmp);
            }

            return(arr);
        }
        unsafe public static byte[] HexToBinary(string hex)
        {
            const string IGNORED_CHARS = ":- ";

            byte[] arr      = new byte[hex.Length >> 1];
            byte[] hexBytes = Encoding.ASCII.GetBytes(hex);
            int    binLength;

            fixed(byte *arrPtr = arr)
            {
                //we call sodium_hex2bin with some chars to be ignored
                int ret = NativeLibsodium.sodium_hex2bin(
                    arrPtr, arr.Length,
                    hex, hexBytes.Length,
                    IGNORED_CHARS,
                    out binLength,
                    null
                    );

                if (ret != 0)
                {
                    throw new Exception("Internal error, decoding failed.");
                }
            }

            //remove the trailing nulls from the array, if there were some format characters in the hex string before
            if (arr.Length != binLength)
            {
                byte[] tmp = new byte[binLength];
                Array.Copy(arr, 0, tmp, 0, binLength);
                return(tmp);
            }

            return(arr);
        }