Пример #1
0
        public static string GetHashSha3_512(string inputString)
        {
            var sb        = new StringBuilder();
            var alghoritm = new SHA3Managed(512);

            return(ByteArrayToString(alghoritm.ComputeHash(Encoding.UTF8.GetBytes(inputString))));
        }
Пример #2
0
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="plainText">
        /// Plaintext value to be hashed. The function does not check whether
        /// this parameter is null.
        /// </param>
        /// <returns>
        /// Hash value formatted as a base64-encoded string.
        /// </returns>
        public static string Hash(string plainText)
        {
            try
            {
                /*
                 * Initialize SHA-3 hash class and set up size for it.
                 * Accepted values are 224, 256, 384 and 512 bits.
                 */
                var hash     = new SHA3Managed(256);
                var encoding = new ASCIIEncoding();

                //Keep message bytes
                byte[] messageBytes = encoding.GetBytes(plainText);

                //Compute message hash
                byte[] computeHashBytes = hash.ComputeHash(messageBytes);

                //Convert to hexa and return all this shit
                var x = new StringBuilder();
                foreach (var item in computeHashBytes)
                {
                    x.Append(item.ToString("x2"));
                }

                return(x.ToString());
            }
            catch (Exception)
            {
                throw;
            }
        }
 //Erzeuge Pepper
 private static string SHA3Pepper(string password, string pepper)
 {
     var bytes = new ASCIIEncoding().GetBytes(string.Concat(password, pepper));
     var crypto = new SHA3Managed(256);
     var hash = crypto.ComputeHash(bytes);
     return BitConverter.ToString(hash).Replace("-", "").ToLower();
 }
Пример #4
0
        public BlockchainUnit(string path, IIndexedStorage <long> addressStorage)
        {
            disposed = false;

            blockStorage       = new JsonDriveAccessor <Block>(path, addressStorage);
            merkleRootComputer = new MerkleTreeBuilder();
            digest             = new SHA3Managed(512);
        }
Пример #5
0
 public Verify(string f, int bits)
 {
     byte[] data = File.ReadAllBytes(f);
     SHA3Managed sha = new SHA3Managed(bits);
     sha.Initialize();
     byte[] h = sha.ComputeHash(data);
     hash = BitConverter.ToString(h).Replace("-", "").ToLower();
     InitializeComponent();
 }
Пример #6
0
        public Verify(string f, int bits)
        {
            byte[]      data = File.ReadAllBytes(f);
            SHA3Managed sha  = new SHA3Managed(bits);

            sha.Initialize();
            byte[] h = sha.ComputeHash(data);
            hash = BitConverter.ToString(h).Replace("-", "").ToLower();
            InitializeComponent();
        }
 public Calculate(string f, int bits)
 {
     byte[] data = File.ReadAllBytes(f);
     SHA3Managed sha = new SHA3Managed(bits);
     file = f;
     sha.Initialize();
     byte[] h = sha.ComputeHash(data);
     hash = BitConverter.ToString(h).Replace("-","").ToLower();
     InitializeComponent();
     textBox1.Text = hash;
 }
        public Calculate(string f, int bits)
        {
            byte[]      data = File.ReadAllBytes(f);
            SHA3Managed sha  = new SHA3Managed(bits);

            file = f;
            sha.Initialize();
            byte[] h = sha.ComputeHash(data);
            hash = BitConverter.ToString(h).Replace("-", "").ToLower();
            InitializeComponent();
            textBox1.Text = hash;
        }
Пример #9
0
        static void Main()
        {
            var stopwatch = new Stopwatch();


            byte[] data = { 0, 0, 5, 1, 1, 2 };
            string word = "abc";


            Sha1 hash = new Sha1();

            stopwatch.Start();
            Console.WriteLine("Proper HASH SHA1(data): " + UintArrayToString(hash.Hash(data)));
            stopwatch.Stop();
            Console.WriteLine($"Data hashed in: {stopwatch.Elapsed} s");
            stopwatch.Reset();
            stopwatch.Start();
            Console.WriteLine("Proper HASH SHA1 (word): " + UintArrayToString(hash.Hash(Encoding.ASCII.GetBytes(word))));
            stopwatch.Stop();
            Console.WriteLine($"Data hashed in: {stopwatch.Elapsed} s");
            Console.WriteLine($"Data hashed in: {stopwatch.ElapsedTicks} ticks");
            Console.WriteLine($"Speed of hashing: {Encoding.ASCII.GetBytes(word).Length * 1000000 / stopwatch.Elapsed.Ticks} bps");


            SHA3Managed hash5 = new SHA3Managed(512);

            //stopwatch.Start();
            //Console.WriteLine("Proper HASH SHA3-512(data): " + ToHexString(hash5.ComputeHash(data)));
            //stopwatch.Stop();
            //Console.WriteLine($"Data hashed in: {stopwatch.Elapsed} s");
            stopwatch.Reset();
            stopwatch.Start();
            Console.WriteLine("Proper HASH SHA3-512 (word): " + ByteArrayToString(hash5.ComputeHash(Encoding.UTF8.GetBytes(word))));
            stopwatch.Stop();
            Console.WriteLine($"Data hashed in: {stopwatch.Elapsed} s");
            Console.WriteLine($"Data hashed in: {stopwatch.ElapsedTicks} ticks");
            Console.WriteLine("Speed of hashing: {0:f2} bps", (double)(Encoding.ASCII.GetBytes(word).Length / 1024) * 1000L * 1000L * 10L / (stopwatch.ElapsedTicks));

            SHA2Managed hash6 = new SHA2Managed(512);

            stopwatch.Reset();
            Console.WriteLine("Proper HASH SHA-512(word): " + ByteArrayToString(hash6.ComputeHash(Encoding.UTF8.GetBytes(word))));

            SHA2Managed hash7 = new SHA2Managed(224);

            stopwatch.Reset();
            Console.WriteLine("Proper HASH SHA-224(word): " + ByteArrayToString(hash7.ComputeHash(Encoding.UTF8.GetBytes(word))));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new HashFunctionAnalizerForm());
        }
Пример #10
0
        private static bool VerifyChecksum(byte[] raw, XISFChecksumTypeEnum cksumType, string providedCksum)
        {
            string      computedCksum;
            SHA3Managed sha3;

            using (MyStopWatch.Measure($"XISF Checksum = {cksumType}")) {
                switch (cksumType)
                {
                case XISFChecksumTypeEnum.SHA1:
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    computedCksum = GetStringFromHash(sha1.ComputeHash(raw));
                    sha1.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA256:
                    SHA256 sha256 = new SHA256CryptoServiceProvider();
                    computedCksum = GetStringFromHash(sha256.ComputeHash(raw));
                    sha256.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA512:
                    SHA512 sha512 = new SHA512CryptoServiceProvider();
                    computedCksum = GetStringFromHash(sha512.ComputeHash(raw));
                    sha512.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA3_256:
                    sha3          = new SHA3Managed(256);
                    computedCksum = GetStringFromHash(sha3.ComputeHash(raw));
                    sha3.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA3_512:
                    sha3          = new SHA3Managed(512);
                    computedCksum = GetStringFromHash(sha3.ComputeHash(raw));
                    sha3.Dispose();
                    break;

                default:
                    return(false);
                }
            }
            if (computedCksum.Equals(providedCksum))
            {
                return(true);
            }
            else
            {
                Logger.Error($"XISF: Invalid data block checksum! Expected: {providedCksum} Got: {computedCksum}");
                return(false);
            }
        }
Пример #11
0
        private Task HashSha3_512(string fileName, CancellationToken token, TextBox tb)
        {
            return(Task.Factory.StartNew(() =>
            {
                token.ThrowIfCancellationRequested();

                using (var stream = File.OpenRead(fileName))
                    using (var sha3 = new SHA3Managed(512))
                    {
                        string res = BitConverter.ToString(sha3.ComputeHash(stream)).Replace("-", string.Empty);
                        SetOutputText(tb, res);
                    }
            }));
        }
Пример #12
0
        /// <summary>
        /// Generates a SHA3 512 bit Hash of the given input
        /// </summary>
        /// <param name="input">the byte[] to hash</param>
        /// <returns>the hash as byte[]</returns>
        public static byte[] GetComplexHash(byte[] input)
        {
            if (_sha3 == null)
            {
                _sha3 = new SHA3Managed(512);
            }

            Sha3HashMutex.WaitOne();

            byte[] bytes = _sha3.ComputeHash(input);

            Sha3HashMutex.ReleaseMutex();

            return(bytes);
        }
Пример #13
0
        /// <summary>
        ///     take any string and encrypt it using SHA3 then
        ///     return the encrypted data
        /// </summary>
        /// <param name="data">input text you will enterd to encrypt it</param>
        /// <returns>return the encrypted text as hexadecimal string</returns>
        public static string Encrypted(string data)
        {
            var sha3 = new SHA3Managed(512);

            //convert the input text to array of bytes
            var hashData = sha3.ComputeHash(Encoding.Default.GetBytes(data));

            //create new instance of StringBuilder to save hashed data
            var returnValue = new StringBuilder();

            //loop for each byte and add it to StringBuilder
            for (var i = 0; i < hashData.Length; i++)
            {
                returnValue.Append(hashData[i].ToString());
            }

            // return hexadecimal string
            return returnValue.ToString();
        }
Пример #14
0
        /// <summary>
        ///     take any string and encrypt it using SHA3 then
        ///     return the encrypted data
        /// </summary>
        /// <param name="data">input text you will enterd to encrypt it</param>
        /// <returns>return the encrypted text as hexadecimal string</returns>
        public static string Encrypted(string data)
        {
            var sha3 = new SHA3Managed(512);

            //convert the input text to array of bytes
            var hashData = sha3.ComputeHash(Encoding.Default.GetBytes(data));

            //create new instance of StringBuilder to save hashed data
            var returnValue = new StringBuilder();

            //loop for each byte and add it to StringBuilder
            for (var i = 0; i < hashData.Length; i++)
            {
                returnValue.Append(hashData[i].ToString());
            }

            // return hexadecimal string
            return(returnValue.ToString());
        }
Пример #15
0
 /// <summary>
 /// Creates a hash algorithm instance.
 /// </summary>
 /// <param name="name">The hash algorithm name,</param>
 /// <returns>A hash algorithm instance.</returns>
 /// <exception cref="ArgumentNullException">name was null.</exception>
 /// <exception cref="ArgumentException">name.Name was null or empty.</exception>
 /// <exception cref="NotSupportedException">The hash algorithm name is not supported.</exception>
 public static HashAlgorithm Create(HashAlgorithmName name)
 {
     if (name == HashAlgorithmName.SHA512)
     {
         return(SHA512.Create());
     }
     if (name == HashAlgorithmName.MD5)
     {
         return(MD5.Create());
     }
     if (name == HashAlgorithmName.SHA256)
     {
         return(SHA256.Create());
     }
     if (name == HashAlgorithmName.SHA1)
     {
         return(SHA1.Create());
     }
     if (name == HashAlgorithmName.SHA384)
     {
         return(SHA384.Create());
     }
     if (string.IsNullOrWhiteSpace(name.Name))
     {
         throw new ArgumentException("name.Name should not be null or empty.", nameof(name));
     }
     return((name.Name.ToUpperInvariant().Replace("-", string.Empty)) switch
     {
         "SHA3512" or "KECCAK512" or "SHA3" => SHA3Managed.Create512(),
         "SHA3384" or "KECCAK384" => SHA3Managed.Create384(),
         "SHA3256" or "KECCAK256" => SHA3Managed.Create256(),
         "SHA3224" or "KECCAK224" => SHA3Managed.Create224(),
         "SHA256" => SHA256.Create(),
         "SHA384" => SHA384.Create(),
         "SHA512" or "SHA2" => SHA512.Create(),
         "MD5" => MD5.Create(),
         "SHA1" => SHA1.Create(),
         _ => HashAlgorithm.Create(name.Name),
     });
Пример #16
0
        /**********************************************************************************************************
        *	HashedPassword GeneratePassword(string MasterPassword)
        *       Purpose:	The name of the application the HashedPass's are for. This is used when generating
        *					unique HashedPasses.
        *		Parameters:
        *				string MasterPassword
        *					The master password to generate the hash with.
        *
        *		Return:
        *			Returns the HashedPassword generated.
        **********************************************************************************************************/
        public HashedPassword GeneratePassword(string MasterPassword)
        {
            //Create character alphabet.
            List <char> alphabetList = new List <char>();

            if (LowerCaseAllowed)
            {
                alphabetList.AddRange(LOWERCASEALPHABET);
            }
            if (CapitalsAllowed)
            {
                alphabetList.AddRange(UPPERCASEALPHABET);
            }
            if (NumbersAllowed)
            {
                alphabetList.AddRange(NUMBERALPHABET);
            }
            if (SpecialCharactersAllowed)
            {
                alphabetList.AddRange(SPECIALCHARACTERALPHABET);
            }

            char[] alphabet = alphabetList.ToArray();

            SHA3Managed SHAHasher = new SHA3Managed(256);

            // master password in bytes
            byte[] ByteMasterPass = Encoding.Unicode.GetBytes(MasterPassword);

            // application name in bytes.
            byte[] applicationShift = Encoding.Unicode.GetBytes(ApplicationName);

            // the set of master password + application name + seed
            byte[] mangledBytes = new byte[PasswordLength * sizeof(char)];
            // Modify the bytes so that they are website and instance dependent.
            for (int i = 0; i < mangledBytes.Length; i++)
            {
                // Modify the password to be unique for the website.
                mangledBytes[i]  = ByteMasterPass[i % ByteMasterPass.Length];
                mangledBytes[i] += applicationShift[i % applicationShift.Length];
                // Modify the password to be unique from each other for the website.
                mangledBytes[i] += CurrentSeed;
            }

            byte[] hashedPassword = new byte[PasswordLength * sizeof(char)];
            // mangled bytes fed through a secure hash.
            for (int i = 0; i < mangledBytes.Length;)
            {
                int    bytesHashed = Math.Min(mangledBytes.Length - i, 32);
                byte[] hashedChunk = SHAHasher.ComputeHash(mangledBytes, i, bytesHashed);
                Array.Copy(hashedChunk, 0, hashedPassword, i, bytesHashed);
                i += bytesHashed;
            }



            StringBuilder languageCompliantPass = new StringBuilder();

            for (int i = 0, value = 0; i < hashedPassword.Length; i += sizeof(char))
            {
                for (int j = i; j < i + sizeof(char); j++)
                {
                    value += hashedPassword[j];
                }

                languageCompliantPass.Append(alphabet[value % alphabet.Length]);
            }

            HashedPassword newPassword = new HashedPassword(languageCompliantPass.ToString(), DateTime.Now, CurrentSeed);

            m_currentSeed++;

            m_passwords.Add(newPassword);

            return(newPassword);
        }
Пример #17
0
 /// <summary>
 /// Creates a hash signature provider using SHA-3-256 hash algorithm.
 /// </summary>
 /// <param name="shortName">true if use short name; otherwise, false.</param>
 /// <returns>A keyed hash signature provider.</returns>
 public static HashSignatureProvider CreateSHA3256(bool shortName = false)
 {
     return(new HashSignatureProvider(SHA3Managed.Create256(), shortName ? "S3256" : "SHA3256", true));
 }
Пример #18
0
        private void generateFileHashBtn_Click(object sender, EventArgs e)
        {
            var stopwatch       = new Stopwatch();
            var stopwatchSHA224 = new Stopwatch();
            var stopwatchSHA256 = new Stopwatch();
            var stopwatchSHA384 = new Stopwatch();
            var stopwatchSHA512 = new Stopwatch();


            Stream fileStream     = null;
            var    openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = "\\";
            openFileDialog.Filter           = @"All files (*.*)|*.*";
            openFileDialog.FilterIndex      = 2;
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if (!((fileStream = openFileDialog.OpenFile()) == null))
                    {
                        using (fileStream)
                        {
                            var imageData = new byte[fileStream.Length];

                            fileStream.Read(imageData, 0, Convert.ToInt32(fileStream.Length));
                            var fs = fileStream as FileStream;


                            var hashSha1   = new Sha1();
                            var hashSha224 = new SHA2Managed(224);
                            var hashSha256 = new SHA2Managed(256);
                            var hashSha384 = new SHA2Managed(384);
                            var hashSha512 = new SHA2Managed(512);
                            var hashSha3   = new SHA3Managed();

                            stopwatch.Start();
                            Console.WriteLine("FILE HASH SHA1: " +
                                              UintArrayToString(hashSha1.Hash(FileToByteArray(fs.Name))));
                            stopwatch.Stop();
                            Console.WriteLine($"Data hashed in: {stopwatch.Elapsed} s");

                            stopwatchSHA224.Start();
                            Console.WriteLine("FILE HASH SHA224: " +
                                              ByteArrayToString(hashSha224.ComputeHash(FileToByteArray(fs.Name))));
                            stopwatchSHA224.Stop();
                            Console.WriteLine($"Data hashed in: {stopwatchSHA224.Elapsed} s");

                            stopwatchSHA256.Start();
                            Console.WriteLine("FILE HASH SHA256: " +
                                              ByteArrayToString(hashSha256.ComputeHash(FileToByteArray(fs.Name))));
                            stopwatchSHA256.Stop();
                            Console.WriteLine($"Data hashed in: {stopwatchSHA256.Elapsed} s");

                            stopwatchSHA384.Start();
                            Console.WriteLine("FILE HASH SHA384: " +
                                              ByteArrayToString(hashSha384.ComputeHash(FileToByteArray(fs.Name))));
                            stopwatchSHA384.Stop();
                            Console.WriteLine($"Data hashed in: {stopwatchSHA384.Elapsed} s");


                            stopwatchSHA512.Start();
                            Console.WriteLine("FILE HASH SHA512: " +
                                              ByteArrayToString(hashSha512.ComputeHash(FileToByteArray(fs.Name))));
                            stopwatchSHA512.Stop();
                            Console.WriteLine($"Data hashed in: {stopwatchSHA512.Elapsed} s");


                            stopwatchSHA512.Reset();
                            stopwatchSHA512.Start();
                            Console.WriteLine("FILE HASH SHA3-512: " +
                                              ByteArrayToString(hashSha3.ComputeHash(FileToByteArray(fs.Name))));
                            stopwatchSHA512.Stop();
                            Console.WriteLine($"Data hashed in: {stopwatchSHA512.Elapsed} s");

                            //Write length of file
                            Console.WriteLine($"File Length: {fileStream.Length}");

                            //Close the File Stream
                            fileStream.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }
Пример #19
0
        private double speedTestOfHashFunctions(string hashName)
        {
            var someData = new byte[1000000];


            //randomize data
            for (int i = 0; i < someData.Length; i++)
            {
                someData[i] = Convert.ToByte(randomizeValue());
            }

            var    times     = 100;
            var    stopWatch = new Stopwatch();
            double result;
            int    collumnCounter;


            for (int i = 0; i < times; i++)
            {
                if (i % 5 == 0)
                {
                    dataGridView1.Columns.Add($"{i} Mb", $"{i} Mb");
                }
            }


            switch (hashName)
            {
            case "SHA1":
                var alghorithmSha1 = new Sha1();
                dataGridView1.Rows.Add();
                collumnCounter = 2;
                stopWatch.Reset();
                stopWatch.Start();
                for (int i = 0; i < times; i++)
                {
                    alghorithmSha1.Hash(someData);

                    if (i % 5 == 0)
                    {
                        double secondsy = (double)stopWatch.ElapsedMilliseconds / 1000;
                        result = (double)(i / secondsy);
                        dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex + (dataGridView1.RowCount - 1)].Cells[collumnCounter++].Value = $"{result:f2}";
                    }
                }
                stopWatch.Stop();
                break;

            case "SHA224":
                var alghorithmSha224 = new SHA2Managed(224);
                stopWatch.Reset();
                stopWatch.Start();
                for (int i = 0; i < times; i++)
                {
                    alghorithmSha224.ComputeHash(someData);
                }
                stopWatch.Stop();
                break;

            case "SHA256":
                var alghorithmSha256 = new SHA2Managed(256);
                stopWatch.Reset();
                stopWatch.Start();
                for (int i = 0; i < times; i++)
                {
                    alghorithmSha256.ComputeHash(someData);
                }
                stopWatch.Stop();
                break;

            case "SHA384":
                var alghorithmSha384 = new SHA2Managed(384);
                stopWatch.Reset();
                stopWatch.Start();
                for (int i = 0; i < times; i++)
                {
                    alghorithmSha384.ComputeHash(someData);
                }
                stopWatch.Stop();
                break;

            case "SHA512":
                var alghorithmSha512 = new SHA2Managed(512);
                dataGridView1.Rows.Add();
                collumnCounter = 2;
                stopWatch.Reset();
                stopWatch.Start();
                for (int i = 0; i < times; i++)
                {
                    alghorithmSha512.ComputeHash(someData);

                    if (i % 5 == 0)
                    {
                        double secondsy = (double)stopWatch.ElapsedMilliseconds / 1000;
                        result = (double)(i / secondsy);
                        dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex + (dataGridView1.RowCount - 1)].Cells[collumnCounter++].Value = $"{result:f2}";
                    }
                }
                stopWatch.Stop();
                break;

            case "SHA3-512":
                var alghorithmSha3_512 = new SHA3Managed();
                dataGridView1.Rows.Add();
                collumnCounter = 2;
                stopWatch.Reset();
                stopWatch.Start();
                for (int i = 0; i < times; i++)
                {
                    alghorithmSha3_512.ComputeHash(someData);

                    if (i % 5 == 0)
                    {
                        double secondsy = (double)stopWatch.ElapsedMilliseconds / 1000;
                        result = (double)(i / secondsy);
                        dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex + (dataGridView1.RowCount - 1)].Cells[collumnCounter++].Value = $"{result:f2}";
                    }
                }
                stopWatch.Stop();
                break;

            default:

                break;
            }


            double seconds = (double)stopWatch.ElapsedMilliseconds / 1000;

            Console.WriteLine("HASH {0} with speed: {1} Mb data in {2:f2}", hashName, times, seconds);

            result = (double)(times / seconds);

            return(result);
        }
Пример #20
0
        /// <summary>
        /// Convert the ushort array to a byte arraay, compressing with the requested algorithm if required
        /// </summary>
        /// <param name="data"></param>
        /// <returns>Uncompressed or compressed byte array</returns>
        private byte[] PrepareArray(ushort[] data)
        {
            byte[] outArray;

            /*
             * Convert the ushort[] into a byte[]
             * From here onwards we deal in byte arrays only
             */
            byte[] byteArray = new byte[data.Length * ShuffleItemSize];
            Buffer.BlockCopy(data, 0, byteArray, 0, data.Length * ShuffleItemSize);

            /*
             * Compress the data block as configured.
             */
            using (MyStopWatch.Measure($"XISF Compression = {CompressionType}")) {
                if (CompressionType == XISFCompressionTypeEnum.LZ4)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "lz4+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "lz4";
                    }

                    byte[] tmpArray       = new byte[LZ4Codec.MaximumOutputSize(byteArray.Length)];
                    int    compressedSize = LZ4Codec.Encode(byteArray, 0, byteArray.Length, tmpArray, 0, tmpArray.Length, LZ4Level.L00_FAST);

                    outArray = new byte[compressedSize];
                    Array.Copy(tmpArray, outArray, outArray.Length);
                    tmpArray = null;
                }
                else if (CompressionType == XISFCompressionTypeEnum.LZ4HC)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "lz4hc+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "lz4hc";
                    }

                    byte[] tmpArray       = new byte[LZ4Codec.MaximumOutputSize(byteArray.Length)];
                    int    compressedSize = LZ4Codec.Encode(byteArray, 0, byteArray.Length, tmpArray, 0, tmpArray.Length, LZ4Level.L06_HC);

                    outArray = new byte[compressedSize];
                    Array.Copy(tmpArray, outArray, outArray.Length);
                    tmpArray = null;
                }
                else if (CompressionType == XISFCompressionTypeEnum.ZLIB)
                {
                    if (ByteShuffling)
                    {
                        CompressionName = "zlib+sh";
                        byteArray       = Shuffle(byteArray, ShuffleItemSize);
                    }
                    else
                    {
                        CompressionName = "zlib";
                    }

                    outArray = ZlibStream.CompressBuffer(byteArray);
                }
                else
                {
                    outArray = new byte[byteArray.Length];
                    Array.Copy(byteArray, outArray, outArray.Length);
                    CompressionName = null;
                }
            }

            // Revert to the original data array in case the compression is bigger than uncompressed
            if (outArray.Length > byteArray.Length)
            {
                if (ByteShuffling)
                {
                    //As the original array is shuffled it needs to be unshuffled again - this scenario should be highly unlikely anyways
                    outArray = Unshuffle(byteArray, ShuffleItemSize);
                }
                else
                {
                    outArray = byteArray;
                }
                CompressionType = XISFCompressionTypeEnum.NONE;

                Logger.Debug("XISF output array is larger after compression. Image will be prepared uncompressed instead.");
            }

            if (CompressionType != XISFCompressionTypeEnum.NONE)
            {
                double percentChanged = (1 - ((double)outArray.Length / (double)byteArray.Length)) * 100;
                Logger.Debug($"XISF: {CompressionType} compressed {byteArray.Length} bytes to {outArray.Length} bytes ({percentChanged.ToString("#.##")}%)");
            }

            /*
             * Checksum the data block as configured.
             * If the data block is compressed, we always checksum the compressed form, not the uncompressed form.
             */
            using (MyStopWatch.Measure($"XISF Checksum = {ChecksumType}")) {
                SHA3Managed sha3;

                switch (ChecksumType)
                {
                case XISFChecksumTypeEnum.SHA1:
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha1.ComputeHash(outArray));
                    ChecksumName = "sha-1";
                    sha1.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA256:
                    SHA256 sha256 = new SHA256CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha256.ComputeHash(outArray));
                    ChecksumName = "sha-256";
                    sha256.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA512:
                    SHA512 sha512 = new SHA512CryptoServiceProvider();
                    Checksum     = GetStringFromHash(sha512.ComputeHash(outArray));
                    ChecksumName = "sha-512";
                    sha512.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA3_256:
                    sha3         = new SHA3Managed(256);
                    Checksum     = GetStringFromHash(sha3.ComputeHash(outArray));
                    ChecksumName = "sha3-256";
                    sha3.Dispose();
                    break;

                case XISFChecksumTypeEnum.SHA3_512:
                    sha3         = new SHA3Managed(512);
                    Checksum     = GetStringFromHash(sha3.ComputeHash(outArray));
                    ChecksumName = "sha3-512";
                    sha3.Dispose();
                    break;

                case XISFChecksumTypeEnum.NONE:
                default:
                    Checksum     = null;
                    ChecksumName = null;
                    break;
                }
            }

            return(outArray);
        }
Пример #21
0
 public KeccakDigest(int hashLengthInBits)
 {
     digest = new SHA3Managed(hashLengthInBits);
 }
Пример #22
0
 public string GetHash(string data)
 {
     var b = System.Text.Encoding.UTF8.GetBytes(data);
     var hash = new SHA3Managed(512).ComputeHash(b);
     return BitConverter.ToString(hash).Replace("-", "");
 }
 public KeccakMerkleRootComputer(int hashLengthInBits)
 {
     merkleBuilder = new MerkleTreeBuilder();
     digest        = new SHA3Managed(hashLengthInBits);
 }
Пример #24
0
 public static byte[] DoubleDigestNew(byte[] input)
 {
     var alg2 = new SHA3Managed(256);
     var first = alg2.ComputeHash(input);
     return alg2.ComputeHash(first);
 }