Ejemplo n.º 1
0
        /// <summary>
        /// Generates db tables and inserts some dummy data.
        /// </summary>
        /// <param name="app"></param>
        public static void Seed(IApplicationBuilder app)
        {
            AppDbContext context = app.ApplicationServices.GetRequiredService <AppDbContext>();

            context.Database.Migrate();

            if (!context.Users.Any())
            {
                var hash     = new Sha512Hash();
                var salt     = hash.GetSalt();
                var userHash = hash.GetHash("*****@*****.**" + "password", salt);

                context.Users.Add(new User()
                {
                    IsActive  = true,
                    Salt      = salt,
                    Hash      = userHash,
                    Created   = DateTime.Now,
                    Email     = "*****@*****.**",
                    FirstName = "Ahmet",
                    LastName  = "Sönmez",
                    UserName  = "******",
                });

                context.SaveChanges();
            }
        }
Ejemplo n.º 2
0
 public void FromEmptyArray_Should_Succeed()
 {
     // Arrange
     // Act
     // Assert
     Sha512Hash.Compute(new byte[0]).Hash
     .SequenceEqual(Sha512Hash.Compute(new byte[0]).Hash).Should().BeTrue();
 }
Ejemplo n.º 3
0
        public void Sha512Hash_GetHash_Null_3()
        {
            IHash hashAlgo = new Sha512Hash();

            Action action = () => hashAlgo.GetHash(null as FileInfo);

            action.Should().Throw <ArgumentNullException>();
        }
Ejemplo n.º 4
0
        public void Sha512Hash_GetHash_Empty()
        {
            IHash hashAlgo = new Sha512Hash();

            Action action = () => hashAlgo.GetHash(string.Empty);

            action.Should().Throw <ArgumentNullException>();
        }
Ejemplo n.º 5
0
            public void CreateInstance_Should_CreateInstance()
            {
                // Arrange
                // Act
                var obj = new Sha512Hash(hash: new byte[64]).CreateAlgorithm();

                // Assert
                obj.Should().BeAssignableTo <SHA512>();
            }
Ejemplo n.º 6
0
        /// <exception cref="System.ArgumentNullException"></exception>
        public static string ComputeHash(string password, string salt)
        {
            Expect.ArgumentNotNull(password, nameof(password));
            Expect.ArgumentNotNull(salt, nameof(salt));

            IHashAlgorithm hashAlgorithm = new Sha512Hash();

            return(hashAlgorithm.CalculateHash(password + salt));
        }
Ejemplo n.º 7
0
        public void Sha512Hash_GetHash_Valid_2()
        {
            IHash hashAlgo = new Sha512Hash();

            HashResult hashResult = hashAlgo.GetHash(Data.ExpectedHashFilePath);

            hashResult.Algorithm.Should().Be(Hashing.ExpectedSha512Algorithm);
            hashResult.Value.Should().Be(Hashing.ExpectedSha512Hash);
        }
Ejemplo n.º 8
0
            public void FromArray_Should_Succeed()
            {
                // Arrange
                // Act
                var obj = Sha512Hash.Compute(Encoding.UTF8.GetBytes("test"));

                // Assert
                obj.Hash.SequenceEqual(Sha512Hash.Compute(Encoding.UTF8.GetBytes("test")).Hash).Should().BeTrue();
                obj.Name.Should().Be(HashAlgorithmName.SHA512);
            }
Ejemplo n.º 9
0
            public void DifferentHashes_ShouldReturn_DifferentHashCodes()
            {
                // Arrange
                var hash1 = Sha512Hash.Compute(Encoding.UTF8.GetBytes("test"));
                var hash2 = Sha512Hash.Compute(Encoding.UTF8.GetBytes("TEST"));

                // Act
                // Assert
                hash1.GetHashCode().Should().NotBe(hash2.GetHashCode());
            }
Ejemplo n.º 10
0
            public void DifferentHashes_ShouldReturn_False()
            {
                // Arrange
                var hash1 = Sha512Hash.Compute(Encoding.UTF8.GetBytes("test"));
                var hash2 = Sha512Hash.Compute(Encoding.UTF8.GetBytes("TEST"));

                // Act
                // Assert
                hash1.Equals((IHash)hash2).Should().BeFalse();
                hash1.Equals((object)hash2).Should().BeFalse();
            }
Ejemplo n.º 11
0
            public void SameHashes_ShouldReturn_True()
            {
                // Arrange
                var hash1 = Sha512Hash.Compute(Encoding.UTF8.GetBytes("test"));
                var hash2 = Sha512Hash.Compute(Encoding.UTF8.GetBytes("test"));

                // Act
                // Assert
                hash1.Equals((IHash)hash2).Should().BeTrue();
                hash1.Equals((object)hash2).Should().BeTrue();
            }
Ejemplo n.º 12
0
        public void Sha512Hash_GetHash_Valid_1()
        {
            IHash hashAlgo = new Sha512Hash();

            using FileStream fileStream = new(Data.ExpectedHashFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            HashResult hashResult = hashAlgo.GetHash(fileStream);

            hashResult.Algorithm.Should().Be(Hashing.ExpectedSha512Algorithm);
            hashResult.Value.Should().Be(Hashing.ExpectedSha512Hash);
        }
Ejemplo n.º 13
0
            public void Constructor_Should_SetProperties()
            {
                // Arrange
                var hash = Sha512Hash.Compute(new byte[64]);

                // Act
                var obj = new Sha512Hash(hash.Hash);

                // Assert
                obj.Hash.SequenceEqual(hash.Hash).Should().BeTrue();
                obj.Name.Should().Be(HashAlgorithmName.SHA512);
            }
Ejemplo n.º 14
0
            public void FromArrayWithInputBlockSizeLength_Should_Succeed()
            {
                // Arrange
                int inputBlockSize;

                using (var sha512 = SHA512Managed.Create()) inputBlockSize = sha512.InputBlockSize;

                // Act
                // Assert
                Sha512Hash.Compute(new byte[inputBlockSize]).Hash
                .SequenceEqual(Sha512Hash.Compute(new byte[inputBlockSize]).Hash).Should().BeTrue();
            }
Ejemplo n.º 15
0
                public void VerifySignatureForDifferentHash_ShouldThrow_TrustException()
                {
                    // Arrange
                    var key         = RsaKey.Generate();
                    var certificate = key.DeriveCertificate();
                    var hashToSign  = Sha512Hash.Compute(new byte[] { 0x1f, 0x2e, 0x3d, 0x4c });
                    var otherHash   = Sha512Hash.Compute(new byte[] { 0x01, 0x00, 0x03, 0x02 });

                    // Act
                    // Assert
                    var signature = key.Sign(hashToSign);

                    Assert.Throws <TrustException>(() => certificate.Verify(otherHash, signature));
                }
Ejemplo n.º 16
0
                public void SignHashAndVerify_Should_Succeed()
                {
                    // Arrange
                    var key  = RsaKey.Generate();
                    var hash = Sha512Hash.Compute(new byte[] { 0x10, 0x20, 0x30, 0x40 });

                    // Act
                    var signature = key.Sign(hash: hash);

                    // Assert
                    signature.Should().BeOfType <RsaSignature>();
                    signature.SignerCertificateHash.Equals(key.Hash).Should().BeTrue();
                    key.DeriveCertificate().Verify(hash, signature);
                }
Ejemplo n.º 17
0
            public void FromArrayAndStream_Should_BeEqual()
            {
                // Arrange
                var data = Encoding.UTF8.GetBytes("test");

                using (var stream = new MemoryStream(data))
                {
                    // Act
                    var arrayHash  = Sha512Hash.Compute(data);
                    var streamHash = Sha512Hash.Compute(stream);

                    // Assert
                    arrayHash.Hash.SequenceEqual(streamHash.Hash).Should().BeTrue();
                }
            }
Ejemplo n.º 18
0
                public void SameParametersAndSignature_ShouldReturn_True()
                {
                    // Arrange
                    var signature    = new RsaSignature(Sha512Hash.Compute(new byte[] { 0x00 }), new byte[] { 0x01 });
                    var certificate1 = new RsaCertificate(
                        parameters: ScenarioRsa1.RsaParameters,
                        signature: signature);
                    var certificate2 = new RsaCertificate(
                        parameters: ScenarioRsa1.RsaParameters,
                        signature: signature);

                    // Act
                    // Assert
                    certificate1.Equals(certificate2).Should().BeTrue();
                }
Ejemplo n.º 19
0
 static ScenarioRsa()
 {
     DefaultData                 = new byte[] { 0x00, 0x01, 0x02, 0x03 };
     DefaultDataHash             = Sha512Hash.Compute(DefaultData);
     DefaultEmbeddedData         = new byte[] { 0xff, 0xee, 0xdd, 0xcc };
     DefaultKey                  = RsaKey.Generate();
     DefaultRsa                  = DefaultKey.CreateRsa();
     DefaultRsaParameters        = DefaultRsa.ExportParameters(true);
     DefaultCertificateSignature = new RsaSignature(Sha512Hash.Compute(new byte[] { 0x12, 0x34, 0xaa, 0xbb }), new byte[] { 0xa1, 0xb2, 0xc3, 0xd4 });
     DefaultCertificate          = new RsaCertificate(DefaultRsaParameters, DefaultCertificateSignature);
     DefaultSignerKey            = RsaKey.Generate();
     DefaultSignerCertificate    = (RsaCertificate)DefaultSignerKey.DeriveCertificate();
     DefaultSignatureData        = new byte[] { 0x1f, 0x2f, 0x3f, 0x4f };
     DefaultSignature            = new RsaSignature(DefaultSignerCertificate.Hash, DefaultSignatureData);
     DefaultChain                = new ChainOfTrust(DefaultSignerCertificate);
 }
Ejemplo n.º 20
0
                public void SameParametersAndDifferentSignature_ShouldReturn_False()
                {
                    // Arrange
                    var signature1   = createRsaSignature();
                    var certificate1 = new RsaCertificate(
                        parameters: ScenarioRsa1.RsaParameters,
                        signature: signature1);
                    var signature2 = createRsaSignature(
                        signerCertificateHash: Sha512Hash.Compute(new byte[] { 0x00 }),
                        signature: new byte[] { 0x01 });
                    var certificate2 = new RsaCertificate(
                        parameters: ScenarioRsa1.RsaParameters,
                        signature: signature2);

                    // Act
                    // Assert
                    certificate1.Equals(certificate2).Should().BeFalse();
                }
Ejemplo n.º 21
0
            public void DifferentSignatures_ShouldReturn_DifferentHashes()
            {
                // Arrange
                var hash1 = Helpers.ComputeRsaHashWithSignature(
                    rsaParameters: ScenarioRsa.DefaultRsaParameters,
                    includePrivateParameters: true,
                    embeddedData: ScenarioRsa.DefaultEmbeddedData,
                    signature: ScenarioRsa.DefaultSignature);
                var hash2 = Helpers.ComputeRsaHashWithSignature(
                    rsaParameters: ScenarioRsa.DefaultRsaParameters,
                    includePrivateParameters: true,
                    embeddedData: ScenarioRsa.DefaultEmbeddedData,
                    signature: new RsaSignature(Sha512Hash.Compute(new byte[] { 0xaa, 0xbb, 0xcc, 0xdd }), new byte[] { 0x1a, 0x2b, 0x3c, 0x4d }));

                // Act
                // Assert
                hash1.Hash.SequenceEqual(hash2.Hash).Should().BeFalse();
            }
Ejemplo n.º 22
0
                public void CertificatesWithDifferentSignatures_Should_HaveSameHashesButDifferentHashWithSignatures()
                {
                    // Arrange
                    var signature1   = createRsaSignature();
                    var certificate1 = new RsaCertificate(
                        parameters: ScenarioRsa1.RsaParameters,
                        signature: signature1);
                    var signature2 = createRsaSignature(
                        signerCertificateHash: Sha512Hash.Compute(new byte[] { 0x00 }),
                        signature: new byte[] { 0x01 });
                    var certificate2 = new RsaCertificate(
                        parameters: ScenarioRsa1.RsaParameters,
                        signature: signature2);

                    // Act
                    // Assert
                    certificate1.Hash.Equals(certificate2.Hash).Should().BeTrue();
                    certificate1.HashWithSignature.Equals(certificate2.HashWithSignature).Should().BeFalse();
                }
Ejemplo n.º 23
0
            public void FromEmptyStream_Should_Succeed()
            {
                // Arrange
                IHash hash1 = null;
                IHash hash2 = null;

                // Act
                using (var stream = new MemoryStream(new byte[0]))
                {
                    hash1 = Sha512Hash.Compute(stream);
                }

                using (var stream = new MemoryStream(new byte[0]))
                {
                    hash2 = Sha512Hash.Compute(stream);
                }

                // Assert
                hash1.Hash.SequenceEqual(hash2.Hash).Should().BeTrue();
            }
Ejemplo n.º 24
0
            public void Stream_Should_Succeed()
            {
                // Arrange
                var   data  = Encoding.UTF8.GetBytes("test");
                IHash hash1 = null;
                IHash hash2 = null;

                // Act
                using (var stream = new MemoryStream(data))
                {
                    hash1 = Sha512Hash.Compute(stream);
                }

                using (var stream = new MemoryStream(data))
                {
                    hash2 = Sha512Hash.Compute(stream);
                }

                // Assert
                hash1.Hash.SequenceEqual(hash2.Hash).Should().BeTrue();
                hash1.Name.Should().Be(HashAlgorithmName.SHA512);
            }
Ejemplo n.º 25
0
        /// <summary>
        /// 散列服务创造器
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public IHash CreateHash(Type type)
        {
            IHash hash;

            switch (type)
            {
            case Type.Md5:
                hash = new MD5Hash();
                break;

            case Type.Sha1:
                hash = new Sha1Hash();
                break;

            case Type.Sha256:
                hash = new Sha256Hash();
                break;

            case Type.Sha384:
                hash = new Sha384Hash();
                break;

            case Type.Sha512:
                hash = new Sha512Hash();
                break;

            case Type.RipEmd160:
                hash = new RipEmd160Hash();
                break;

            default:
                hash = new MD5Hash();
                break;
            }
            return(hash);
        }
Ejemplo n.º 26
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello!");
            Console.WriteLine("Let me show you the basics of cryptography with the TrustMe library for Dotnet Core.");
            Console.WriteLine();

            var key = RsaKey.Generate();

            Console.WriteLine($"Generated sample private key (abbr.): {toHex(key.Hash.Hash).Substring(0, 8)}");
            Console.WriteLine("This is used to sign data and thus prove its integrity. Usually this is pre-generated and stored in a file kept secret\nand never to be included in publicly available applications.");
            Console.WriteLine();

            var certificate = key.DeriveCertificate();

            Console.WriteLine($"This public key (or certificate) is derived from it (abbr.): {toHex(certificate.Hash.Hash).Substring(0, 8)}");
            Console.WriteLine("It may be included as a \"hidden\" constant (by means of hard to find and replace in decompiled or disassembled code) in\nany application willing to test the integrity of data expected to come from a known and trusted party.");
            Console.WriteLine();

            Console.Write("Enter some text: ");
            var input     = Console.ReadLine();
            var inputHash = Sha512Hash.Compute(Encoding.UTF8.GetBytes(input));

            Console.WriteLine($"The hash value of the input is (abbr.): {toHex(inputHash.Hash).Substring(0, 8)}");
            Console.WriteLine("The hash value is always exactly the same for the same input.");
            Console.WriteLine();

            var signature = key.Sign(inputHash);

            Console.WriteLine($"Signed with the private key, the signature of the input is (abbr.): {toHex(signature.Signature).Substring(0, 8)}");
            Console.WriteLine();

            Console.Write("Checking the signature against the public key (or certificate), should be valid: ");
            try
            {
                certificate.Verify(inputHash, signature);
                Console.WriteLine("valid");
            }
            catch (TrustException ex)
            {
                Console.WriteLine($"invalid,\n{ex.Message}");
            }
            Console.WriteLine();

            Console.Write("Checking the signature against some different arbitrary public key (or certificate), should be invalid: ");
            try
            {
                RsaKey.Generate().DeriveCertificate().Verify(inputHash, signature);
                Console.WriteLine("valid");
            }
            catch (TrustException ex)
            {
                Console.WriteLine($"invalid,\n{ex.Message}");
            }
            Console.WriteLine();

            var maximumAllowedPlainTextLength = ((RsaCertificate)certificate).GetMaximumPlainTextLengthForEncryption();

            Console.Write($"Enter some text to encrypt using the public key (max. {maximumAllowedPlainTextLength} chars): ");
            var plainText = Console.ReadLine();

            Console.WriteLine("Encrypted the plain text with the public key:");
            var cipher = certificate.Encrypt(plainText: Encoding.UTF8.GetBytes(plainText));

            Console.WriteLine(toHex(cipher));
            Console.Write("Decrypted cipher with the private key is: ");
            Console.WriteLine(Encoding.UTF8.GetString(key.Decrypt(cipher: cipher).ToArray()));
        }
Ejemplo n.º 27
0
 public void FromArrayNull_ShouldThrow_ArgumentNullException()
 {
     // Arrange
     // Act & Assert
     Assert.Throws <ArgumentNullException>(() => Sha512Hash.Compute((byte[])null));
 }