Example #1
0
        public void ComputeHash_ExceptionsTest()
        {
            byte[] goodBa = { 1, 2, 3 };
            Sha256 sha    = new Sha256();

            Assert.Throws <ArgumentNullException>(() => sha.ComputeHash(null));

            sha.Dispose();
            Assert.Throws <ObjectDisposedException>(() => sha.ComputeHash(goodBa));
        }
Example #2
0
        public void ComputeHash_ReuseTest()
        {
            byte[] msg1 = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog");
            byte[] msg2 = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy cog");
            byte[] exp1 = Helper.HexToBytes("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592");
            byte[] exp2 = Helper.HexToBytes("e4c4d8f3bf76b692de791a173e05321150f7a345b46484fe427f6acc7ecc81be");

            using Sha256 sha = new Sha256();
            byte[] act1 = sha.ComputeHash(msg1);
            byte[] act2 = sha.ComputeHash(msg2);

            Assert.Equal(exp1, act1);
            Assert.Equal(exp2, act2);
        }
Example #3
0
        public void Test_QueueStream()
        {
            using (FileStream stream1 = new FileStream("QueueStream1.tmp", FileMode.Create))
                using (QueueStream queueStream = new QueueStream(stream1, StreamMode.Write, 1024 * 1024 * 4, _bufferManager))
                    using (FileStream stream2 = new FileStream("QueueStream2.tmp", FileMode.Create))
                    {
                        byte[] buffer = new byte[1024];

                        for (int i = 0; i < 1024 * 32; i++)
                        {
                            _random.NextBytes(buffer);

                            queueStream.Write(buffer, 0, buffer.Length);
                            stream2.Write(buffer, 0, buffer.Length);
                        }
                    }

            using (FileStream stream1 = new FileStream("QueueStream1.tmp", FileMode.Open))
                using (FileStream stream2 = new FileStream("QueueStream2.tmp", FileMode.Open))
                {
                    Assert.IsTrue(CollectionUtilities.Equals(Sha256.ComputeHash(stream1), Sha256.ComputeHash(stream2)), "QueueStream #1");
                }

            using (FileStream stream1 = new FileStream("QueueStream1.tmp", FileMode.Open))
                using (QueueStream queueStream = new QueueStream(stream1, StreamMode.Read, 1024 * 1024 * 4, _bufferManager))
                    using (FileStream stream2 = new FileStream("QueueStream2.tmp", FileMode.Open))
                    {
                        Assert.IsTrue(CollectionUtilities.Equals(Sha256.ComputeHash(queueStream), Sha256.ComputeHash(stream2)), "QueueStream #2");
                    }
        }
Example #4
0
 public void ComputeHashTwiceTest(byte[] message, byte[] expectedHash)
 {
     using Sha256 sha = new Sha256();
     byte[] actualHash = sha.ComputeHashTwice(message);
     expectedHash = sha.ComputeHash(expectedHash);
     Assert.Equal(expectedHash, actualHash);
 }
Example #5
0
        public void ComputeHash_NistMonteCarloTest()
        {
            byte[]  seed  = Helper.HexToBytes("6d1e72ad03ddeb5de891e572e2396f8da015d899ef0e79503152d6010a3fe691");
            JObject jObjs = Helper.ReadResources <JObject>("Sha256NistTestData");
            int     size  = 32;

            byte[] toHash = new byte[3 * size];

            byte[] M0 = seed;
            byte[] M1 = seed;
            byte[] M2 = seed;

            Sha256 sha = new Sha256(false);

            foreach (var item in jObjs["MonteCarlo"])
            {
                byte[] expected = Helper.HexToBytes(item.ToString());
                for (int i = 0; i < 1000; i++)
                {
                    Buffer.BlockCopy(M0, 0, toHash, 0, size);
                    Buffer.BlockCopy(M1, 0, toHash, size, size);
                    Buffer.BlockCopy(M2, 0, toHash, size * 2, size);

                    M0 = M1;
                    M1 = M2;
                    M2 = sha.ComputeHash(toHash);
                }
                M0 = M2;
                M1 = M2;

                Assert.Equal(expected, M2);
            }

            sha.Dispose();
        }
        public override void Close()
        {
            if (_disposed)
            {
                return;
            }

            if (_blockBufferPosition != 0)
            {
                Key key = null;

                if (_hashAlgorithm == HashAlgorithm.Sha256)
                {
                    key = new Key(Sha256.ComputeHash(_blockBuffer, 0, _blockBufferPosition), _hashAlgorithm);
                }
                else
                {
                    throw new NotSupportedException();
                }

                lock (_cacheManager.ThisLock)
                {
                    _cacheManager.Lock(key);
                    _cacheManager[key] = new ArraySegment <byte>(_blockBuffer, 0, _blockBufferPosition);
                }

                _keyList.Add(key);

                _blockBufferPosition = 0;
            }

            base.Close();
        }
Example #7
0
        private static Stream RemoveHash(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            int type = (int)Varint.GetUInt64(stream);

            if (type == (int)ConvertHashAlgorithm.Sha256)
            {
                var value = new byte[32];
                stream.Read(value, 0, value.Length);

                var dataStream = new RangeStream(stream, true);
                if (!Unsafe.Equals(value, Sha256.ComputeHash(new WrapperStream(dataStream, true))))
                {
                    throw new ArgumentException("Hash");
                }

                dataStream.Seek(0, SeekOrigin.Begin);
                return(dataStream);
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Example #8
0
        private static Stream AddHash(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            try
            {
                var targetStream = new RangeStream(stream, true);

                BufferStream metadataStream = new BufferStream(_bufferManager);
                metadataStream.WriteByte((byte)ConvertHashAlgorithm.Sha256);

                targetStream.Seek(0, SeekOrigin.Begin);
                var hash = Sha256.ComputeHash(targetStream);

                BufferStream hashStream = new BufferStream(_bufferManager);
                hashStream.Write(hash, 0, hash.Length);

                return(new UniteStream(metadataStream, targetStream, hashStream));
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message, e);
            }
        }
Example #9
0
        public void ComputeHashTest()
        {
            var input  = StringHelper.GetRandomString(100);
            var result = Sha256.ComputeHash(input);

            Assert.IsNotNull(result);
            Assert.AreNotEqual(result, input);
        }
Example #10
0
        public void ComputeHash_AMillionATest()
        {
            using Sha256 sha = new Sha256();
            byte[] actualHash   = sha.ComputeHash(HashTestCaseHelper.GetAMillionA());
            byte[] expectedHash = Helper.HexToBytes("cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0");

            Assert.Equal(expectedHash, actualHash);
        }
Example #11
0
        public void ComputeHash_WithIndexTest()
        {
            using Sha256 sha = new Sha256();
            byte[] data         = Helper.HexToBytes("123fab54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67f3a25c92");
            byte[] actualHash   = sha.ComputeHash(data, 3, 43);
            byte[] expectedHash = Helper.HexToBytes("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592");

            Assert.Equal(expectedHash, actualHash);
        }
Example #12
0
        private uint[] Convert8To11(FastStream stream)
        {
            using Sha256 sha = new Sha256();
            byte[] hash = sha.ComputeHash(stream.ToByteArray());

            int bitSize = stream.GetSize() * 8;
            int cs      = 11 - (bitSize % 11);

            if (cs < 4)
            {
                cs += 11;
            }
            Debug.Assert(cs >= 4 && cs <= 14);
            stream.Write(hash, 0, cs > 8 ? 2 : 1);

            bitSize += cs;
            int wordCount = bitSize / 11;

            Debug.Assert(bitSize % 11 == 0);

            byte[] ba   = stream.ToByteArray();
            uint[] bits = new uint[(int)Math.Ceiling((double)bitSize / 32)];
            for (int i = 0, j = 0; j < bits.Length; i += 4, j++)
            {
                bits[j] = (uint)(ba[i + 3] | (ba[i + 2] << 8) | (ba[i + 1] << 16) | (ba[i] << 24));
            }

            int itemIndex = 0;
            int bitIndex  = 0;
            // Number of bits in a word
            int toTake = 11;
            // UInt32 is 32 bit!
            int maxBits = 32;

            uint[] wordIndexes = new uint[wordCount];
            for (int i = 0; i < wordIndexes.Length; i++)
            {
                if (bitIndex + toTake <= maxBits)
                {
                    wordIndexes[i] = (bits[itemIndex] << bitIndex) >> (maxBits - toTake);
                }
                else
                {
                    wordIndexes[i] = ((bits[itemIndex] << bitIndex) >> (maxBits - toTake)) |
                                     (bits[itemIndex + 1] >> (maxBits - toTake + maxBits - bitIndex));
                }

                bitIndex += toTake;
                if (bitIndex >= maxBits)
                {
                    bitIndex -= maxBits;
                    itemIndex++;
                }
            }

            return(wordIndexes);
        }
Example #13
0
        public void ComputeHash_DoubleTest()
        {
            using Sha256 sha = new Sha256(true);
            var data = Helper.HexToBytes("fb8049137747e712628240cf6d7056ea2870170cb7d9bc713d91e901b514c6ae7d7dda3cd03ea1b99cf85046a505f3590541123d3f8f2c22c4d7d6e65de65c4ebb9251f09619");

            byte[] actualHash   = sha.ComputeHash(data);
            byte[] expectedHash = Helper.HexToBytes("d2cee8d3cfaf1819c55cce1214d01cdef1d97446719ccfaad4d76d912a8126f9");

            Assert.Equal(expectedHash, actualHash);
        }
Example #14
0
        public void TestInformalAbc()
        {
            byte[] bytes = Encoding.ASCII.GetBytes("abc");

            Sha256 hash = New <Sha256>();

            byte[] actual;
            actual = hash.ComputeHash(bytes);
            Assert.That(actual, Is.EquivalentTo("BA7816BF 8F01CFEA 414140DE 5DAE2223 B00361A3 96177A9C B410FF61 F20015AD".FromHex()));
        }
Example #15
0
        public void TestSha256()
        {
            var sha256 = new Sha256();
            var bytes  = Encoding.UTF8.GetBytes("abc");

            var hash      = sha256.ComputeHash(bytes);
            var sha256str = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();

            Assert.AreEqual(sha256str, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
        }
Example #16
0
        public void TestInformalLongerText()
        {
            byte[] bytes = Encoding.ASCII.GetBytes("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq");

            Sha256 hash = New <Sha256>();

            byte[] actual;
            actual = hash.ComputeHash(bytes);
            Assert.That(actual, Is.EquivalentTo("248D6A61 D20638B8 E5C02693 0C3E6039 A33CE459 64FF2167 F6ECEDD4 19DB06C1".FromHex()));
        }
Example #17
0
 private static bool VerifyHash()
 {
     try
     {
         var csp = (RSACryptoServiceProvider)ServerCertificate.PublicKey.Key;
         return(csp.VerifyHash(Sha256.ComputeHash(Encoding.UTF8.GetBytes(Key)), CryptoConfig.MapNameToOID("SHA256"), Convert.FromBase64String(Serversignature)));
     }
     catch (Exception)
     {
         return(false);
     }
 }
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (offset < 0 || buffer.Length < offset)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (count < 0 || (buffer.Length - offset) < count)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            int writeLength = 0;

            while (count > 0)
            {
                int length = Math.Min(_blockBufferLength - _blockBufferPosition, count);
                Unsafe.Copy(buffer, offset, _blockBuffer, _blockBufferPosition, length);
                _blockBufferPosition += length;
                offset      += length;
                count       -= length;
                writeLength += length;

                if (_blockBufferLength == _blockBufferPosition)
                {
                    Key key = null;

                    if (_hashAlgorithm == HashAlgorithm.Sha256)
                    {
                        key = new Key(Sha256.ComputeHash(_blockBuffer, 0, _blockBufferPosition), _hashAlgorithm);
                    }
                    else
                    {
                        throw new NotSupportedException();
                    }

                    lock (_cacheManager.ThisLock)
                    {
                        _cacheManager.Lock(key);
                        _cacheManager[key] = new ArraySegment <byte>(_blockBuffer, 0, _blockBufferPosition);
                    }

                    _keyList.Add(key);

                    _blockBufferPosition = 0;
                }
            }

            _length += writeLength;
        }
Example #19
0
        public static string CreateToken(string token, string dsId)
        {
            if (string.IsNullOrEmpty(token))
            {
                throw new ArgumentException("Invalid token");
            }

            var tokenHash = dsId + token;

            tokenHash = UrlBase64.Encode(Sha256.ComputeHash(Encoding.UTF8.GetBytes(tokenHash)));
            return(token.Substring(0, 16) + tokenHash);
        }
 static bool VerifyHash()
 {
     try
     {
         var csp = (RSACryptoServiceProvider)SERVERCERTIFICATE.PublicKey.Key;
         return(csp.VerifyHash(Sha256.ComputeHash(Encoding.UTF8.GetBytes(ENCRYPTIONKEY)), CryptoConfig.MapNameToOID("SHA256"),
                               Convert.FromBase64String(SERVERSIGNATURE)));
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #21
0
        public void Hash(int count, string value)
        {
            Assert.Equal(count, value.Length);
            var shaClr       = SHA256.Create();
            var sha          = new Sha256();
            var data         = Encoding.UTF8.GetBytes(value);
            var expectedHash = shaClr.ComputeHash(data);

            var result = new byte[32];

            sha.ComputeHash(data, result);
            Assert.Equal(expectedHash, result);
        }
Example #22
0
        /// <summary>
        /// Replaces top stack item with its hash digest. Return value indicates success.
        /// </summary>
        /// <param name="opData">Data to use</param>
        /// <param name="error">Error message (null if sucessful, otherwise will contain information about the failure)</param>
        /// <returns>True if operation was successful, false if otherwise</returns>
        public override bool Run(IOpData opData, out string error)
        {
            if (opData.ItemCount < 1)
            {
                error = Err.OpNotEnoughItems;
                return(false);
            }

            using Sha256 hash = new Sha256();
            opData.Push(hash.ComputeHash(opData.Pop()));

            error = null;
            return(true);
        }
Example #23
0
        //[InlineData(0x5a, 0x20000000, "15a1868c12cc53951e182344277447cd0979536badcc512ad24c67e9b2d4f3dd")]
        //[InlineData(0x00, 0x41000000, "461c19a93bd4344f9215f5ec64357090342bc66b15a148317d276e31cbc20b53")]
        //[InlineData(0x42, 0x6000003e, "c23ce8a7895f4b21ec0daf37920ac0a262a220045a03eb2dfed48ef9b05aabea")]
        public void HashNist(byte value, int byteCount, string expectedHex)
        {
            Assert.Equal(64, expectedHex.Length);
            var sha = new Sha256();
            //var sha = SHA256.Create();
            var expectedHash = ToBin(expectedHex);
            var data         = new byte[byteCount];

            Array.Fill(data, value);
            var result = new byte[32];

            sha.ComputeHash(data, result);
            Assert.Equal(expectedHash, result);
        }
Example #24
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            lblError.Text = "";

            Employee = null;

            int id;

            if (!Int32.TryParse(txtId.Text, out id))
            {
                lblError.Text = "Employee id must be integer";
                return;
            }

            var bytes   = Sha256.ComputeHash(Encoding.UTF8.GetBytes(txtPassword.Text));
            var builder = new StringBuilder();

            foreach (byte b in bytes)
            {
                builder.Append(b.ToString("x2"));
            }

            string password = builder.ToString();

            var employee = Entities.Employee
                           .Where(v => v.id == id)
                           .FirstOrDefault();

            if (employee == null)
            {
                lblError.Text = "Invalid ID";
                return;
            }

            if (!employee.password.Equals(password))
            {
                lblError.Text = "Wrong Password";
                return;
            }

            Employee = employee;

            Hide();
            new FormMain().ShowDialog();
            Close();
        }
Example #25
0
        public byte[] CreateHash(HashAlgorithm hashAlgorithm)
        {
            if (_Sha256_hash == null)
            {
                using (var stream = this.Export(BufferManager.Instance))
                {
                    _Sha256_hash = Sha256.ComputeHash(stream);
                }
            }

            if (hashAlgorithm == HashAlgorithm.Sha256)
            {
                return(_Sha256_hash);
            }

            return(null);
        }
Example #26
0
        private static Stream AddHash(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            var hashStream = new BufferStream(_bufferManager);

            {
                Varint.SetUInt64(hashStream, (uint)ConvertHashAlgorithm.Sha256);
                var value = Sha256.ComputeHash(new WrapperStream(stream, true));
                hashStream.Write(value, 0, value.Length);
            }

            return(new UniteStream(hashStream, stream));
        }
        public PublicKeyThumbprint(byte[] modulus, byte[] exponent)
        {
            if (modulus == null)
            {
                throw new ArgumentNullException("modulus");
            }
            if (exponent == null)
            {
                throw new ArgumentNullException("exponent");
            }

            Sha256 sha256 = New <Sha256>();

            byte[] bytes = modulus.Append(exponent);
            byte[] hash  = sha256.ComputeHash(bytes);
            _thumbprint = hash.Reduce(16);
        }
Example #28
0
        private static Stream RemoveHash(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            byte type = (byte)stream.ReadByte();

            if (type == (byte)ConvertHashAlgorithm.Sha256)
            {
                Stream dataStream = null;

                try
                {
                    byte[] hash = new byte[32];

                    using (RangeStream hashStream = new RangeStream(stream, stream.Length - 32, 32, true))
                    {
                        hashStream.Read(hash, 0, hash.Length);
                    }

                    dataStream = new RangeStream(stream, 1, stream.Length - (1 + 32));
                    if (!Unsafe.Equals(hash, Sha256.ComputeHash(dataStream)))
                    {
                        throw new FormatException();
                    }

                    dataStream.Seek(0, SeekOrigin.Begin);

                    return(dataStream);
                }
                catch (Exception)
                {
                    if (dataStream != null)
                    {
                        dataStream.Dispose();
                    }

                    throw;
                }
            }

            throw new NotSupportedException();
        }
        /// <summary>
        /// Returns the 256-bit result of double SHA-256 hash of the message with the added constant used in signing operation.
        /// </summary>
        /// <exception cref="ArgumentNullException"/>
        /// <param name="message">
        /// UTF-8 encoded message to sign (will be normalized using full compatibility decomposition form).
        /// <para/>Note that trailing spaces, new line character,... will not be changed here.
        /// Caller has to decide whether to change those
        /// </param>
        /// <returns>256-bit hash</returns>
        public byte[] GetBytesToSign(string message)
        {
            if (message is null)
            {
                throw new ArgumentNullException(nameof(message), "Message can not be null.");
            }

            using Sha256 hash = new Sha256(true);
            FastStream stream = new FastStream();

            stream.Write((byte)Constants.MsgSignConst.Length);
            stream.Write(Encoding.UTF8.GetBytes(Constants.MsgSignConst));
            byte[] messageBytes = Encoding.UTF8.GetBytes(message.Normalize(NormalizationForm.FormKD));
            stream.WriteWithCompactIntLength(messageBytes);

            byte[] result = hash.ComputeHash(stream.ToByteArray());
            return(result);
        }
Example #30
0
        private bool CheckMessage(string message, out byte[] toSign)
        {
            try
            {
                FastStream stream = new FastStream();
                byte[]     msgBa  = Encoding.UTF8.GetBytes(message);
                stream.Write((byte)MessageSignConstant.Length);
                stream.Write(Encoding.UTF8.GetBytes(MessageSignConstant));
                new CompactInt((ulong)msgBa.Length).WriteToStream(stream);
                stream.Write(msgBa);

                toSign = hash.ComputeHash(stream.ToByteArray());

                return(true);
            }
            catch (Exception)
            {
                toSign = null;
                return(false);
            }
        }