public byte[] SHA256()
 {
     using (var sha256 = new SHA256Managed())
     {
         var strings = new[] { Str1, Str2, Str3, Str4 };
         for (int i = 0; i < strings.Length; i++)
         {
             string str = strings[i];
             if (str != null)
             {
                 // Commented lines are for using ToUpperInvariant()
                 //str = str.ToUpperInvariant()
                 byte[] length2 = BitConverter.GetBytes(str.Length);
                 sha256.TransformBlock(length2, 0, length2.Length, length2, 0);
                 // byte[] sortKeyBytes = Encoding.UTF8.GetBytes(str);
                 byte[] sortKeyBytes = CultureInfo.InvariantCulture.CompareInfo.GetSortKey(str, CompareOptions.IgnoreCase).KeyData;
                 sha256.TransformBlock(sortKeyBytes, 0, sortKeyBytes.Length, sortKeyBytes, 0);
             }
             else
             {
                 byte[] length2 = BitConverter.GetBytes(-1);
                 sha256.TransformBlock(length2, 0, length2.Length, length2, 0);
             }
         }
         sha256.TransformFinalBlock(new byte[0], 0, 0);
         byte[] hash = sha256.Hash;
         return(hash);
     }
 }
        /// <summary>
        /// Generates the play ready content key.
        /// </summary>
        /// <param name="keySeed">The key seed.</param>
        /// <param name="keyId">The key id.</param>
        /// <returns>The content key.</returns>
        public static byte[] GeneratePlayReadyContentKey(byte[] keySeed, Guid keyId)
        {
            if (keySeed == null)
            {
                throw new ArgumentNullException("keySeed");
            }

            byte[] contentKey = new byte[EncryptionUtils.KeySizeInBytesForAes128];

            // Truncate the key seed to 30 bytes.
            byte[] truncatedKeySeed = new byte[30];
            if (keySeed.Length < truncatedKeySeed.Length)
            {
                throw new ArgumentOutOfRangeException("keySeed", "KeySeed must be at least 30 bytes in length");
            }

            Array.Copy(keySeed, truncatedKeySeed, truncatedKeySeed.Length);

            // Get the keyId as a byte array.
            byte[] keyIdAsBytes = keyId.ToByteArray();

            using (SHA256Managed sha_A = new SHA256Managed())
                using (SHA256Managed sha_B = new SHA256Managed())
                    using (SHA256Managed sha_C = new SHA256Managed())
                    {
                        // Create sha_A_Output buffer.  It is the SHA of the truncatedKeySeed and the keyIdAsBytes.
                        sha_A.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
                        sha_A.TransformFinalBlock(keyIdAsBytes, 0, keyIdAsBytes.Length);
                        byte[] sha_A_Output = sha_A.Hash;

                        // Create sha_B_Output buffer.  It is the SHA of the truncatedKeySeed, the keyIdAsBytes, and
                        // the truncatedKeySeed again.
                        sha_B.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
                        sha_B.TransformBlock(keyIdAsBytes, 0, keyIdAsBytes.Length, keyIdAsBytes, 0);
                        sha_B.TransformFinalBlock(truncatedKeySeed, 0, truncatedKeySeed.Length);
                        byte[] sha_B_Output = sha_B.Hash;

                        // Create sha_C_Output buffer.  It is the SHA of the truncatedKeySeed, the keyIdAsBytes,
                        // the truncatedKeySeed again, and the keyIdAsBytes again.
                        sha_C.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
                        sha_C.TransformBlock(keyIdAsBytes, 0, keyIdAsBytes.Length, keyIdAsBytes, 0);
                        sha_C.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
                        sha_C.TransformFinalBlock(keyIdAsBytes, 0, keyIdAsBytes.Length);
                        byte[] sha_C_Output = sha_C.Hash;

                        for (int i = 0; i < EncryptionUtils.KeySizeInBytesForAes128; i++)
                        {
                            contentKey[i] = Convert.ToByte(sha_A_Output[i] ^ sha_A_Output[i + EncryptionUtils.KeySizeInBytesForAes128]
                                                           ^ sha_B_Output[i] ^ sha_B_Output[i + EncryptionUtils.KeySizeInBytesForAes128]
                                                           ^ sha_C_Output[i] ^ sha_C_Output[i + EncryptionUtils.KeySizeInBytesForAes128]);
                        }
                    }

            return(contentKey);
        }
        /*
         * Calculating PlayReady Content Key with Key Seed
         * https://docs.microsoft.com/en-us/playready/specifications/playready-key-seed
         *
         * Services implementing PlayReady must maintain a Key Management System (KMS) to store and manage content keys.
         * Specifically, the values of {KID, Content Key} are stored for each content asset that is managed by the service.
         * These values are stored at encryption time, and retrieved at license issuance time.
         *
         * PlayReady provides a convenient way to avoid a complex KMS.
         * The Content Key Seed algorithm allows derivation of different content keys for a collection of content assets,
         *  from a varying KID and a fixed Key Seed:
         *     Ck(KID) = f(KID, KeySeed)
         *
         * !!NOTE!!:
         *   The algorithm is expected to input KeyId as GUID.
         *   This means the byte data of the KeyId must be GUID LE Byte Array.
         *
         * The following is the PlayReady standard algorithm:
         */
        public static byte[] GeneratePlayReadyContentKey(byte[] keySeed, Guid keyId)
        {
            const int DRM_AES_KEYSIZE_128 = 16;

            byte[] contentKey = new byte[DRM_AES_KEYSIZE_128];
            //
            //  Truncate the key seed to 30 bytes, key seed must be at least 30 bytes long.
            //
            byte[] truncatedKeySeed = new byte[30];
            Array.Copy(keySeed, truncatedKeySeed, truncatedKeySeed.Length);
            //
            //  Get the keyId as a byte array
            //
            byte[] keyIdAsBytes = keyId.ToByteArray();
            //
            //  Create sha_A_Output buffer.  It is the SHA of the truncatedKeySeed and the keyIdAsBytes
            //
            SHA256Managed sha_A = new SHA256Managed();

            sha_A.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
            sha_A.TransformFinalBlock(keyIdAsBytes, 0, keyIdAsBytes.Length);
            byte[] sha_A_Output = sha_A.Hash;
            //
            //  Create sha_B_Output buffer.  It is the SHA of the truncatedKeySeed, the keyIdAsBytes, and
            //  the truncatedKeySeed again.
            //
            SHA256Managed sha_B = new SHA256Managed();

            sha_B.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
            sha_B.TransformBlock(keyIdAsBytes, 0, keyIdAsBytes.Length, keyIdAsBytes, 0);
            sha_B.TransformFinalBlock(truncatedKeySeed, 0, truncatedKeySeed.Length);
            byte[] sha_B_Output = sha_B.Hash;
            //
            //  Create sha_C_Output buffer.  It is the SHA of the truncatedKeySeed, the keyIdAsBytes,
            //  the truncatedKeySeed again, and the keyIdAsBytes again.
            //
            SHA256Managed sha_C = new SHA256Managed();

            sha_C.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
            sha_C.TransformBlock(keyIdAsBytes, 0, keyIdAsBytes.Length, keyIdAsBytes, 0);
            sha_C.TransformBlock(truncatedKeySeed, 0, truncatedKeySeed.Length, truncatedKeySeed, 0);
            sha_C.TransformFinalBlock(keyIdAsBytes, 0, keyIdAsBytes.Length);
            byte[] sha_C_Output = sha_C.Hash;
            for (int i = 0; i < DRM_AES_KEYSIZE_128; i++)
            {
                contentKey[i] = Convert.ToByte(sha_A_Output[i] ^ sha_A_Output[i + DRM_AES_KEYSIZE_128]
                                               ^ sha_B_Output[i] ^ sha_B_Output[i + DRM_AES_KEYSIZE_128]
                                               ^ sha_C_Output[i] ^ sha_C_Output[i + DRM_AES_KEYSIZE_128]);
            }

            return(contentKey);
        }
Exemplo n.º 4
0
        public byte[] CalculateHash()
        {
            using (var sha256 = new SHA256Managed())
            {
                sha256.Initialize();
                sha256.TransformBlock(this.Index);
                sha256.TransformBlock(this.PreviousHash);
                sha256.TransformBlock(this.TimeStamp.ToBinary());
                sha256.TransformBlock(this.Data);
                sha256.TransformFinalBlock(this.Nonce);

                return(sha256.Hash);
            }
        }
Exemplo n.º 5
0
        public void TestSha256()
        {
            var r      = CryptoRandom.NewWeakRandom();
            var pbData = new byte[517];

            r.NextBytes(pbData);

            byte[] pbH1;
            using (var h1 = new SHA256Managed())
            {
                var i = 0;
                while (i != pbData.Length)
                {
                    var cb = r.Next(pbData.Length - i) + 1;
                    h1.TransformBlock(pbData, i, cb, pbData, i);
                    i += cb;
                }
                h1.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);
                pbH1 = h1.Hash;
            }

            byte[] pbH2;
            using (var h2 = new SHA256Managed())
            {
                pbH2 = h2.ComputeHash(pbData);
            }

            Assert.That(MemUtil.ArraysEqual(pbH1, pbH2), Is.True);
        }
Exemplo n.º 6
0
        private static string GetSha512Buffered(Stream p_streamIn)
        {
            string _result;

            Process.GetCurrentProcess();
            const int _bufferSizeForMd5Hash = 1024 * 1024 * 8;

            using (var _md5Prov = new SHA256Managed())
            {
                int _readCount;
                var _bytesTransfered = 0;
                var _buffer          = new byte[_bufferSizeForMd5Hash];

                while ((_readCount = p_streamIn.Read(_buffer, 0, _buffer.Length)) != 0)
                {
                    if (_bytesTransfered + _readCount == p_streamIn.Length)
                    {
                        _md5Prov.TransformFinalBlock(_buffer, 0, _readCount);
                    }
                    else
                    {
                        _md5Prov.TransformBlock(_buffer, 0, _bufferSizeForMd5Hash, _buffer, 0);
                    }
                    _bytesTransfered += _readCount;
                }

                _result = BitConverter.ToString(_md5Prov.Hash).Replace("-", String.Empty).ToLower();
                _md5Prov.Clear();
            }

            return(_result);
        }
Exemplo n.º 7
0
 /// <summary>
 /// Computes a SHA256 hash
 /// </summary>
 /// <param name="text">String or filename of file hash</param>
 /// <returns>Hexadecimal SHA256 hash string</returns>
 public static string SHA256(string s)
 {
     if (System.IO.File.Exists(s))
     {
         int    offset = 0;
         byte[] block  = new byte[ZefieLib.Data.BlockSize];
         byte[] hash;
         using (BufferedStream f = new BufferedStream(new FileStream(s, FileMode.Open, FileAccess.Read)))
         {
             using (SHA256 shaM = new SHA256Managed())
             {
                 // For each block:
                 while (offset + block.Length < f.Length)
                 {
                     f.Position = offset;
                     f.Read(block, 0, ZefieLib.Data.BlockSize);
                     offset += shaM.TransformBlock(block, 0, block.Length, null, 0);
                 }
                 int remain = (int)(f.Length - (long)offset);
                 block      = new byte[remain];
                 f.Position = offset;
                 _          = f.Read(block, 0, remain);
                 _          = shaM.TransformFinalBlock(block, 0, block.Length);
                 hash       = shaM.Hash;
             }
         }
         return(ZefieLib.Data.BytesToHex(hash));
     }
     else
     {
         return(SHA256(Encoding.UTF8.GetBytes(s)));
     }
 }
Exemplo n.º 8
0
        /**
         * Method to compute the hash value
         * */
        public static byte[] ComputeHash(BinaryReader reader, ulong dataSize)
        {
            // embadding of the SHA256 algorithm
            SHA256Managed sha    = new SHA256Managed();
            int           offset = 0;

            byte[] output = new byte[512];             // buffer size
            byte[] input;

            // with the buffer, we are possible to process large file with small memory usage.
            // increasing of the buffer size will speed up the process.

            // read and transform a block at a time according to the buffer size
            while ((ulong)output.Length - (ulong)offset < dataSize)
            {
                input   = reader.ReadBytes(output.Length);
                offset += sha.TransformBlock(input, 0, output.Length, output, 0);
            }

            // transform final block
            input = reader.ReadBytes((int)(dataSize - (ulong)offset));
            sha.TransformFinalBlock(input, 0, input.Length);

            return(sha.Hash);
        }
        /// <summary>
        ///     Stretches the key by first hashing passphrase|salt, then iteratively hashing
        ///     the hash, for the specified number of iterations. 'Stretching' in this context
        ///     means artificially applying an extra work-factor so as to effectively lengthen
        ///     the effective bit-length of the provided passphrase.
        /// </summary>
        /// <param name="salt">The salt.</param>
        /// <param name="passphrase">The passphrase.</param>
        /// <param name="iterations">The iterations.</param>
        /// <returns></returns>
        private static byte[] StretchKey(
            byte[] salt,
            string passphrase,
            int iterations)
        {
            var ansiEncodedPassphrase =
                passphrase.Select(x => (byte)x).ToArray(); //SHA256.ASCIIEncoder(passphrase);

            byte[] iteratedHashValue;
            using (SHA256 hash = new SHA256Managed())
            {
                hash.TransformBlock(ansiEncodedPassphrase, 0, ansiEncodedPassphrase.Length, null, 0);
                hash.TransformFinalBlock(salt, 0, salt.Length);
                iteratedHashValue = hash.Hash;
            }

            for (var i = 0; i < iterations; ++i)
            {
                using SHA256 iterationHash = new SHA256Managed();

                iteratedHashValue = iterationHash.ComputeHash(iteratedHashValue);
            }

            return(iteratedHashValue);
        }
Exemplo n.º 10
0
 private byte[] ComputeBinding(ChannelHeader channelHeader, SignatureHeader signatureHeader)
 {
     using (SHA256Managed digest = new SHA256Managed())
     {
         digest.Initialize();
         digest.TransformBlock(signatureHeader.Nonce.ToByteArray(), 0, signatureHeader.Nonce.Length, null, 0);
         digest.TransformBlock(creator.ToByteArray(), 0, creator.Length, null, 0);
         byte[] epoch = BitConverter.GetBytes(channelHeader.Epoch);
         if (!BitConverter.IsLittleEndian)
         {
             epoch = epoch.Reverse().ToArray();
         }
         digest.TransformFinalBlock(epoch, 0, epoch.Length);
         return(digest.Hash);
     }
 }
Exemplo n.º 11
0
        /// <summary>
        /// Hashes data from a stream.
        /// </summary>
        /// <param name="es">The input stream.</param>
        /// <param name="length">The number of bytes to hash.</param>
        /// <returns>The hashed digest.</returns>
        /// <remarks>
        /// The method will hash length bytes of the stream from the current position
        /// and the stream position will be restored before the method
        /// returns.
        /// </remarks>
        public static byte[] Compute(EnhancedStream es, long length)
        {
            var  sha256 = new SHA256Managed();
            long streamPos;

            byte[] buf;
            int    cb;

            streamPos = es.Position;
            buf       = new byte[8192];

            while (length > 0)
            {
                cb = (int)(length > buf.Length ? buf.Length : length);
                if (es.Read(buf, 0, cb) < cb)
                {
                    throw new InvalidOperationException("Read past end of stream.");
                }

                sha256.TransformBlock(buf, 0, cb, buf, 0);
                length -= cb;
            }

            sha256.TransformFinalBlock(buf, 0, 0);
            es.Seek(streamPos, SeekOrigin.Begin);

            return(sha256.Hash);
        }
Exemplo n.º 12
0
    public static void Main()
    {
        FileStream    fs     = File.OpenRead("App.ico");
        SHA256Managed sha256 = new SHA256Managed();

        byte[] b = sha256.ComputeHash(fs);
        fs.Close();
        PB(b);
        fs     = File.OpenRead("App.ico");
        sha256 = new SHA256Managed();
        byte[] buffer = new byte[0x1000];
        while (true)
        {
            int n = fs.Read(buffer, 0, 0x1000);
            if (n == 0x1000)
            {
                sha256.TransformBlock(buffer, 0, 0x1000, buffer, 0);
            }
            else
            {
                sha256.TransformFinalBlock(buffer, 0, n);
                break;
            }
        }
        fs.Close();
        PB(sha256.Hash);
    }
Exemplo n.º 13
0
        private string ReadFileHash256(string filepath)
        {
            string h256s   = "";
            long   hadRead = 0;

            using (FileStream fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                const int     bufferlength = 1024 * 1024;
                byte[]        bytetoread   = new byte[bufferlength];
                SHA256Managed sha256       = new SHA256Managed();
                while (true)
                {
                    int rint = fileStream.Read(bytetoread, 0, bufferlength);
                    sha256.TransformBlock(bytetoread, 0, rint, bytetoread, 0);
                    hadRead += rint;

                    if (hadRead >= fileStream.Length)
                    {
                        break;
                    }
                }

                sha256.TransformFinalBlock(bytetoread, 0, 0);
                h256s = ToBitString(sha256.Hash);
            }

            return(h256s);
        }
Exemplo n.º 14
0
        public void Add_part(byte[] text) // voeg een deel van de hash toe
        {
            int hulp = text.Length;

            totalBytes += hulp;
            sha.TransformBlock(text, 0, hulp, null, 0);
        }
Exemplo n.º 15
0
        private static BigInteger Hash(params BigInteger[] integers)
        {
            using (var sha256 = new SHA256Managed())
            {
                sha256.Initialize();

                for (int i = 0; i < integers.Length; i++)
                {
                    byte[] buffer  = integers[i].ToByteArray(true);
                    int    padding = buffer.Length % 4;
                    if (padding != 0)
                    {
                        Array.Resize(ref buffer, buffer.Length + (4 - padding));
                    }

                    if (i == integers.Length - 1)
                    {
                        sha256.TransformFinalBlock(buffer, 0, buffer.Length);
                    }
                    else
                    {
                        sha256.TransformBlock(buffer, 0, buffer.Length, null, 0);
                    }
                }

                byte[] hash = sha256.Hash;
                ReverseBytesAsUInt32(hash);
                return(new BigInteger(hash, true));
            }
        }
Exemplo n.º 16
0
        public void Partial()
        {
            var     data = "Some random stuff for testing purposes.".AsciiToBytes();
            UInt256 h1;

            UInt256 refOnce;
            UInt256 refTwice;

            using (var alg = new SHA256Managed()) {
                alg.TransformFinalBlock(data, 0, data.Length);
                refOnce = h1 = (UInt256)alg.Hash;
                alg.TransformFinalBlock(data, 0, data.Length);
                UInt256 h2 = (UInt256)alg.Hash;
                Assert.Equal(h1, h2);

                alg.TransformFinalBlock(h1, 0, 32);
                refTwice = (UInt256)alg.Hash;
            }

            using (var alg = new SHA256Managed()) {
                alg.TransformBlock(data, 0, data.Length - 12, null, 0);
                alg.TransformFinalBlock(data, data.Length - 12, 12);
                h1 = (UInt256)alg.Hash;
                Assert.Equal(refOnce, h1);
            }

            using (var alg = new SHA256Managed()) {
                alg.TransformBlock(data, 0, data.Length, null, 0);
                alg.TransformFinalBlock(data, 0, 0);
                h1 = (UInt256)alg.Hash;
                Assert.Equal(refOnce, h1);
            }

            using var hw = new HashWriter();
            hw.Add(data[..12]);
Exemplo n.º 17
0
        private string GetSha256Hash_BigFile(Stream fileStream)
        {
            string result = string.Empty;

            using (SHA256Managed hashAlgorithm = new SHA256Managed())
            {
                long bytesToHash = fileStream.Length;

                byte[] buffer     = new byte[bigChunkSize];
                int    sizeToRead = buffer.Length;
                while (bytesToHash > 0)
                {
                    if (bytesToHash < (long)sizeToRead)
                    {
                        sizeToRead = (int)bytesToHash;
                    }

                    int bytesRead = fileStream.ReadAsync(buffer, 0, sizeToRead, CancellationHelper.GetCancellationToken()).Result;
                    CancellationHelper.ThrowIfCancelled();
                    hashAlgorithm.TransformBlock(buffer, 0, bytesRead, null, 0);
                    bytesToHash -= (long)bytesRead;
                    if (bytesRead == 0)
                    {
                        throw new InvalidOperationException("Unexpected end of stream");
                        // or break;
                    }
                }
                hashAlgorithm.TransformFinalBlock(buffer, 0, 0);
                buffer = null;
                result = ByteArrayConverter.ToHexString(hashAlgorithm.Hash);
            }

            return(result);
        }
Exemplo n.º 18
0
        internal static byte[] CreateSaltedHash(byte[] password, byte[] salt, Int32 hashIterations)
        {
            // Seed for the pseudo-random fcn: salt + block index.
            byte[] saltAndIndex = new byte[salt.Length + BLOCK_INDEX];
            Array.Copy(salt, 0, saltAndIndex, 0, salt.Length);

            byte[] hashOutput       = new byte[BLOCK_COUNT * SHA2_256_HASH_SIZE_IN_BYTES];
            int    hashOutputOffset = 0;

            SHA256Managed hashInner = new SHA256Managed();
            SHA256Managed hashOuter = new SHA256Managed();

            // For HMAC the key must be hashed or padded with zeros so
            // that it fits into a single block of the hash algorithm being used.
            if (password.Length > SHA2_256_BLOCK_SIZE_IN_BYTES)
            {
                password = hashInner.ComputeHash(password);
            }
            byte[] key = new byte[SHA2_256_BLOCK_SIZE_IN_BYTES];
            Array.Copy(password, 0, key, 0, password.Length);

            byte[] keyInner = new byte[SHA2_256_BLOCK_SIZE_IN_BYTES];
            byte[] keyOuter = new byte[SHA2_256_BLOCK_SIZE_IN_BYTES];
            for (Int32 i = 0; i < SHA2_256_BLOCK_SIZE_IN_BYTES; i++)
            {
                keyInner[i] = (byte)(key[i] ^ INNER_HASH_PADDING);
                keyOuter[i] = (byte)(key[i] ^ OUTER_HASH_PADDING);
            }

            // For each block of desired output...
            for (Int32 hashBlock = 0; hashBlock < BLOCK_COUNT; hashBlock++)
            {
                // Seed HMAC with salt & block index.
                IncrementInteger(saltAndIndex, salt.Length);
                byte[] hmacResult = saltAndIndex;

                for (Int32 i = 0; i < hashIterations; i++)
                {
                    // Simple implementation of HMAC-SHA2-256.
                    hashInner.Initialize();
                    hashInner.TransformBlock(keyInner, 0, SHA2_256_BLOCK_SIZE_IN_BYTES, keyInner, 0);
                    hashInner.TransformFinalBlock(hmacResult, 0, hmacResult.Length);

                    byte[] temp = hashInner.Hash;

                    hashOuter.Initialize();
                    hashOuter.TransformBlock(keyOuter, 0, SHA2_256_BLOCK_SIZE_IN_BYTES, keyOuter, 0);
                    hashOuter.TransformFinalBlock(temp, 0, temp.Length);
                    hmacResult = hashOuter.Hash;

                    // XOR result into output buffer.
                    XorByteArray(hmacResult, 0, hashOutput, hashOutputOffset);
                }
                hashOutputOffset += SHA2_256_HASH_SIZE_IN_BYTES;
            }
            byte[] result = new byte[SHA2_256_HASH_SIZE_IN_BYTES];
            Array.Copy(hashOutput, 0, result, 0, SHA2_256_HASH_SIZE_IN_BYTES);
            return(result);
        }
Exemplo n.º 19
0
        private void OnRandomMouseMove(object sender, MouseEventArgs e)
        {
            if (m_h == null)
            {
                Debug.Assert(false); return;
            }

            byte[] pb = new byte[8 + 4 + 4];
            MemUtil.Int64ToBytesEx(DateTime.UtcNow.ToBinary(), pb, 0);
            MemUtil.Int32ToBytesEx(e.X, pb, 8);
            MemUtil.Int32ToBytesEx(e.Y, pb, 12);
            m_h.TransformBlock(pb, 0, pb.Length, pb, 0);

            m_fBits += 0.125f;

            UpdateUIState();
        }
Exemplo n.º 20
0
        public override void Close()
        {
            if (m_sBaseStream == null)
            {
                return;
            }

            if (m_bWriting)
            {
                int blockremainder = 32 - (m_ContentLength % 32);
                if (blockremainder < 32)
                {
                    // keep in block boundary
                    byte[] randombytes = CryptoRandom.Instance.GetRandomBytes((uint)blockremainder);
                    m_CryptoStreamAES.Write(randombytes, 0, blockremainder);
                    m_CryptoStreamAES.FlushFinalBlock();
                    m_hash.TransformBlock(randombytes, 0, blockremainder, randombytes, 0);

                    randombytes = CryptoRandom.Instance.GetRandomBytes((uint)blockremainder);
                    m_RandomStream.Write(randombytes, 0, blockremainder);
                }

                m_hash.TransformFinalBlock(new byte[0], 0, 0);


                ///////  Start writing to base stream //////////
                m_sBaseStream.Write(Extensions.GetLittleEndianBytes(m_ContentLength), 0, 4); // write the length

                m_AESStream.WriteTo(m_sBaseStream);

                CryptoStream CryptoStream3DES;

                CryptoStream3DES = new CryptoStream(m_sBaseStream, Get3DES().CreateEncryptor(), CryptoStreamMode.Write);

                m_RandomStream.WriteTo(CryptoStream3DES);
                CryptoStream3DES.FlushFinalBlock();
                CryptoStream3DES.Close();

                m_CryptoStreamAES.Close();
            }
            m_sBaseStream.Close();
            m_sBaseStream = null;
        }
Exemplo n.º 21
0
        static byte[] sha256(byte[] seed, byte[] packet)
        {
            using (SHA256Managed signit = new SHA256Managed())
            {
                signit.TransformBlock(seed, 0, seed.Length, null, 0);
                signit.TransformFinalBlock(packet, 0, packet.Length);
                var ctx = signit.Hash;

                return(ctx);
            }
        }
Exemplo n.º 22
0
 private static byte[] GetSha256Hash(params byte[][] buffers)
 {
     using (var hash = new SHA256Managed()) {
         foreach (var buffer in buffers)
         {
             hash.TransformBlock(buffer, 0, buffer.Length, buffer, 0);
         }
         hash.TransformFinalBlock(new byte[] { }, 0, 0);
         return(hash.Hash);
     }
 }
Exemplo n.º 23
0
 private static byte[] GetBytes(byte[] password, byte[] salt, int iterations, int howManyBytes)
 {
     // round up
     uint cBlocks = (uint)((howManyBytes + HASH_SIZE_IN_BYTES - 1) / HASH_SIZE_IN_BYTES);
     // seed for the pseudo-random fcn: salt + block index
     byte[] saltAndIndex = new byte[salt.Length + 4];
     Array.Copy(salt, 0, saltAndIndex, 0, salt.Length);
     byte[] output = new byte[cBlocks * HASH_SIZE_IN_BYTES];
     int outputOffset = 0;
     SHA256Managed innerHash = new SHA256Managed();
     SHA256Managed outerHash = new SHA256Managed();
     // HMAC says the key must be hashed or padded with zeros
     // so it fits into a single block of the hash in use
     if (password.Length > BLOCK_SIZE_IN_BYTES)
     {
         password = innerHash.ComputeHash(password);
     }
     byte[] key = new byte[BLOCK_SIZE_IN_BYTES];
     Array.Copy(password, 0, key, 0, password.Length);
     byte[] InnerKey = new byte[BLOCK_SIZE_IN_BYTES];
     byte[] OuterKey = new byte[BLOCK_SIZE_IN_BYTES];
     for (int i = 0; i < BLOCK_SIZE_IN_BYTES; ++i)
     {
         InnerKey[i] = (byte)(key[i] ^ IPAD);
         OuterKey[i] = (byte)(key[i] ^ OPAD);
     }
     // for each block of desired output
     for (int iBlock = 0; iBlock < cBlocks; ++iBlock)
     {
         // seed HMAC with salt & block index
         _incrementBigEndianIndex(saltAndIndex, salt.Length);
         byte[] U = saltAndIndex;
         for (int i = 0; i < iterations; ++i)
         {
             // simple implementation of HMAC-SHA-256
             innerHash.Initialize();
             innerHash.TransformBlock(InnerKey, 0, BLOCK_SIZE_IN_BYTES, InnerKey, 0);
             innerHash.TransformFinalBlock(U, 0, U.Length);
             byte[] temp = innerHash.Hash; outerHash.Initialize();
             outerHash.TransformBlock(OuterKey, 0, BLOCK_SIZE_IN_BYTES, OuterKey, 0);
             outerHash.TransformFinalBlock(temp, 0, temp.Length);
             U = outerHash.Hash;
             // U = result of HMAC
             // xor result into output buffer
             _xorByteArray(U, 0, HASH_SIZE_IN_BYTES, output, outputOffset);
         }
         outputOffset += HASH_SIZE_IN_BYTES;
     }
     byte[] result = new byte[howManyBytes];
     Array.Copy(output, 0, result, 0, howManyBytes);
     return result;
 }
Exemplo n.º 24
0
 public byte[] SHA256()
 {
     using (var sha256 = new SHA256Managed())
     {
         var strings = new[] { Str1, Str2, Str3, Str4 };
         for (int i = 0; i < strings.Length; i++)
         {
             string str     = strings[i];
             int    length  = str != null ? str.Length : -1;
             byte[] length2 = BitConverter.GetBytes(length);
             sha256.TransformBlock(length2, 0, length2.Length, length2, 0);
             if (str != null)
             {
                 byte[] sortKeyBytes = CultureInfo.InvariantCulture.CompareInfo.GetSortKey(str, CompareOptions.IgnoreCase).KeyData;
                 sha256.TransformBlock(sortKeyBytes, 0, sortKeyBytes.Length, sortKeyBytes, 0);
             }
         }
         sha256.TransformFinalBlock(new byte[0], 0, 0);
         byte[] hash = sha256.Hash;
         return(hash);
     }
 }
Exemplo n.º 25
0
        public static void PrintHashMultiBlock(byte[] input, int size)
        {
            SHA256Managed sha    = new SHA256Managed();
            int           offset = 0;

            while (input.Length - offset >= size)
            {
                offset += sha.TransformBlock(input, offset, size, input, offset);
            }

            sha.TransformFinalBlock(input, offset, input.Length - offset);
            Console.WriteLine("MultiBlock {0:00}: {1}", size, BytesToStr(sha.Hash));
        }
Exemplo n.º 26
0
        public static UInt256 ComputeHash(IChainState chainState)
        {
            using (var sha256 = new SHA256Managed())
            {
                // add each unspent tx to hash
                foreach (var unspentTx in chainState.ReadUnspentTransactions())
                {
                    var unspentTxBytes = DataEncoder.EncodeUnspentTx(unspentTx);
                    sha256.TransformBlock(unspentTxBytes, 0, unspentTxBytes.Length, unspentTxBytes, 0);
                }
                // finalize hash
                sha256.TransformFinalBlock(new byte[0], 0, 0);

                // hash again to return double-hashed utxo committment
                return(new UInt256(SHA256Static.ComputeHash(sha256.Hash)));
            }
        }
Exemplo n.º 27
0
        public static string Calculate_Hash(string fileName)
        {
            long       read        = 0;
            var        r           = -1;
            const long bytesToRead = 100 * 1024 * 1024;
            const int  bufferSize  = 4096;
            var        buffer      = new byte[bufferSize];
            var        sha         = new SHA256Managed();

            using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                while (read <= bytesToRead && r != 0)
                {
                    read += r = stream.Read(buffer, 0, bufferSize);
                    sha.TransformBlock(buffer, 0, r, null, 0);
                }
            }
            sha.TransformFinalBlock(buffer, 0, 0);
            return(string.Join("", sha.Hash.Select(x => x.ToString("x2"))));
        }
Exemplo n.º 28
0
        private void sha256Hash_DoWork(object sender, DoWorkEventArgs e)
        {
            string[] arg = e.Argument as string[];

            SHA256Managed sha = new SHA256Managed();

            using (FileStream fs = File.OpenRead(arg[0]))
            {
                byte[] data = new byte[1024 * 1024];
                int    len  = fs.Read(data, 0, data.Length);
                while (fs.Position < fs.Length)
                {
                    sha256Hash.ReportProgress(Convert.ToInt32(fs.Position * 100 / fs.Length) + 1);
                    sha.TransformBlock(data, 0, len, data, 0);
                    len = fs.Read(data, 0, data.Length);
                }
                sha.TransformFinalBlock(data, 0, len);
            }
            e.Result = new string[] { BitConverter.ToString(sha.Hash).Replace("-", String.Empty), arg[1] };
        }
        public static string GetSha256Hash_IEnumerable(IEnumerable <byte[]> fileChunks, ulong fileSize)
        {
            string result = string.Empty;

            try
            {
                using (SHA256Managed hashAlgorithm = new SHA256Managed())
                {
                    foreach (byte[] chunk in fileChunks)
                    {
                        hashAlgorithm.TransformBlock(chunk, 0, chunk.Length, null, 0);
                    }

                    hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0);

                    result = ByteArrayConverter.ToHexString(hashAlgorithm.Hash);
                }
            }
            catch
            { }

            return(result);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Creates a name-based UUID using the algorithm from RFC 4122 §4.3.
        /// </summary>
        /// <param name="namespaceId">The ID of the namespace.</param>
        /// <param name="name">The name (within that namespace).</param>
        /// <param name="version">The version number of the UUID to create; this value must be either
        /// <returns>A UUID derived from the namespace and name.</returns>
        public static Guid CreateGuid(Guid namespaceId, string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }
            // convert the name to a sequence of octets (as defined by the standard or conventions of its namespace) (step 3)
            // ASSUME: UTF-8 encoding is always appropriate
            byte[] nameBytes = Encoding.UTF8.GetBytes(name);

            // convert the namespace UUID to network order (step 3)
            byte[] namespaceBytes = namespaceId.ToByteArray();
            SwapByteOrder(namespaceBytes);

            // compute the hash of the name space ID concatenated with the name (step 4)
            byte[] hash = namespaceId.ToByteArray();
            using (SHA256 algorithm = new SHA256Managed())
            {
                algorithm.TransformBlock(namespaceBytes, 0, namespaceBytes.Length, hash, 0);
                algorithm.TransformFinalBlock(nameBytes, 0, nameBytes.Length);
                hash = algorithm.Hash;
            }

            // most bytes from the hash are copied straight to the bytes of the new GUID (steps 5-7, 9, 11-12)
            byte[] newGuid = new byte[16];
            Array.Copy(hash, 0, newGuid, 0, 16);

            // set the four most significant bits (bits 12 through 15) of the time_hi_and_version field to the appropriate 4-bit version number from Section 4.1.3 (step 8)
            newGuid[6] = (byte)((newGuid[6] & 0x0F) | (5 << 4));

            // set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively (step 10)
            newGuid[8] = (byte)((newGuid[8] & 0x3F) | 0x80);

            // convert the resulting UUID to local byte order (step 13)
            SwapByteOrder(newGuid);
            return(new Guid(newGuid));
        }
Exemplo n.º 31
0
        public void Partial()
        {
            var       data = "Some random stuff for testing purposes.".ASCIIToBytes();
            KzUInt256 h1;
            KzUInt256 h2;

            KzUInt256 refonce;
            KzUInt256 reftwice;

            using (var alg = new SHA256Managed()) {
                alg.TransformFinalBlock(data, 0, data.Length);
                refonce = h1 = alg.Hash.ToKzUInt256();
                alg.TransformFinalBlock(data, 0, data.Length);
                h2 = alg.Hash.ToKzUInt256();
                Assert.Equal(h1, h2);

                alg.TransformFinalBlock(h1.ToBytes(), 0, 32);
                reftwice = alg.Hash.ToKzUInt256();
            }

            using (var alg = new SHA256Managed()) {
                alg.TransformBlock(data, 0, data.Length - 12, null, 0);
                alg.TransformFinalBlock(data, data.Length - 12, 12);
                h1 = alg.Hash.ToKzUInt256();
                Assert.Equal(refonce, h1);
            }

            using (var alg = new SHA256Managed()) {
                alg.TransformBlock(data, 0, data.Length, null, 0);
                alg.TransformFinalBlock(data, 0, 0);
                h1 = alg.Hash.ToKzUInt256();
                Assert.Equal(refonce, h1);
            }

            using (var hw = new KzWriterHash()) {
                hw.Add(data[..12]);
Exemplo n.º 32
0
        public byte[] GenerateMAVLinkPacket20(MAVLINK_MSG_ID messageType, object indata, bool sign = false)
        {
            byte[] data;

            data = MavlinkUtil.StructureToByteArray(indata);

            MavlinkUtil.trim_payload(ref data);

            int extra = 0;
            if (sign)
                extra = MAVLINK_SIGNATURE_BLOCK_LEN;

            byte[] packet = new byte[data.Length + MAVLINK_NUM_NON_PAYLOAD_BYTES + extra];

            packet[0] = MAVLINK_STX;
            packet[1] = (byte)data.Length;
            packet[2] = 0;//incompat  signing
            if (sign)
                packet[2] |= MAVLINK_IFLAG_SIGNED;
            packet[3] = 0;//compat
            packet[4] = (byte)packetcount;

            packetcount++;

            packet[5] = 255; // this is always 255 - MYGCS
            packet[6] = (byte)MAV_COMPONENT.MAV_COMP_ID_MISSIONPLANNER;
            packet[7] = (byte)((UInt32)messageType);
            packet[8] = (byte)((UInt32)messageType >> 8);
            packet[9] = (byte)((UInt32)messageType >> 16);

            int i = MAVLINK_NUM_HEADER_BYTES;
            foreach (byte b in data)
            {
                packet[i] = b;
                i++;
            }

            ushort checksum = MavlinkCRC.crc_calculate(packet, data.Length + MAVLINK_NUM_HEADER_BYTES);

            checksum = MavlinkCRC.crc_accumulate(MAVLINK_MESSAGE_INFOS.GetMessageInfo((uint)messageType).crc, checksum);

            byte ck_a = (byte)(checksum & 0xFF); ///< High byte
            byte ck_b = (byte)(checksum >> 8); ///< Low byte

            packet[i] = ck_a;
            i += 1;
            packet[i] = ck_b;
            i += 1;

            if (sign)
            {
                //https://docs.google.com/document/d/1ETle6qQRcaNWAmpG2wz0oOpFKSF_bcTmYMQvtTGI8ns/edit

                /*
                8 bits of link ID
                48 bits of timestamp
                48 bits of signature
                */

                // signature = sha256_48(secret_key + header + payload + CRC + link-ID + timestamp)

                var timestamp = (UInt64)((DateTime.UtcNow - new DateTime(2015, 1, 1)).TotalMilliseconds * 100);

                if (timestamp == lasttimestamp)
                    timestamp++;

                lasttimestamp = timestamp;

                var timebytes = BitConverter.GetBytes(timestamp);

                var sig = new byte[7]; // 13 includes the outgoing hash
                sig[0] = sendlinkid;
                Array.Copy(timebytes, 0, sig, 1, 6); // timestamp

                //Console.WriteLine("gen linkid {0}, time {1} {2} {3} {4} {5} {6} {7}", sig[0], sig[1], sig[2], sig[3], sig[4], sig[5], sig[6], timestamp);
                
                if (signingKey == null || signingKey.Length != 32)
                {
                    signingKey = new byte[32];
                }

                using (SHA256Managed signit = new SHA256Managed())
                {
                    signit.TransformBlock(signingKey, 0, signingKey.Length, null, 0);
                    signit.TransformBlock(packet, 0, i, null, 0);
                    signit.TransformFinalBlock(sig, 0, sig.Length);
                    var ctx = signit.Hash;
                    // trim to 48
                    Array.Resize(ref ctx, 6);

                    foreach (byte b in sig)
                    {
                        packet[i] = b;
                        i++;
                    }

                    foreach (byte b in ctx)
                    {
                        packet[i] = b;
                        i++;
                    }
                }
            }

            return packet;
        }