public void CertificateSignedWithUnlocatableCertificate_ShouldThrow_TrustException()
            {
                // Arrange
                var intermediateKey               = RsaKey.Generate();
                var intermediateCertificate       = intermediateKey.DeriveCertificate();
                var signedIntermediateCertificate = ScenarioRsa.DefaultSignerKey.Sign((RsaCertificate)intermediateCertificate);
                var key               = RsaKey.Generate();
                var certificate       = key.DeriveCertificate();
                var signedCertificate = intermediateKey.Sign((RsaCertificate)certificate);

                var scenario = new Scenario3();
                var lookedUpIntermediateCertificate = false;

                Mock.Get(scenario.CertificateLocator)
                .Setup(m => m.Get(It.IsAny <IHash>()))
                .Returns <IHash>((_hash) =>
                {
                    lookedUpIntermediateCertificate = true;
                    return(null);
                });

                // Act
                // Assert
                Assert.Throws <TrustException>(() => scenario.ChainWithLocator.Verify(signedCertificate));
                lookedUpIntermediateCertificate.Should().BeTrue();
            }
Example #2
0
 public void GenerateWithEmbeddedDataNull_Should_Succeed()
 {
     // Arrange
     // Act
     // Assert
     RsaKey.Generate(embeddedData: null);
 }
Example #3
0
 public void GenerateWithoutSignature_Should_Succeed()
 {
     // Arrange
     // Act
     // Assert
     RsaKey.Generate().Should().NotBeNull();
 }
            public void CertificateSignedIndirectly_Should_FindIntermediateCertificateViaLocator()
            {
                // Arrange
                var intermediateKey               = RsaKey.Generate();
                var intermediateCertificate       = intermediateKey.DeriveCertificate();
                var signedIntermediateCertificate = ScenarioRsa.DefaultSignerKey.Sign((RsaCertificate)intermediateCertificate);
                var key               = RsaKey.Generate();
                var certificate       = key.DeriveCertificate();
                var signedCertificate = intermediateKey.Sign((RsaCertificate)certificate);

                var scenario = new Scenario3();
                var lookedUpIntermediateCertificate = false;

                Mock.Get(scenario.CertificateLocator)
                .Setup(m => m.Get(It.IsAny <IHash>()))
                .Returns <IHash>((_hash) =>
                {
                    if (_hash.Hash.SequenceEqual(intermediateCertificate.Hash.Hash))
                    {
                        lookedUpIntermediateCertificate = true;
                        return(signedIntermediateCertificate);
                    }
                    else
                    {
                        return(null);
                    }
                });

                // Act
                // Assert
                scenario.ChainWithLocator.Verify(signedCertificate);
                lookedUpIntermediateCertificate.Should().BeTrue();
            }
Example #5
0
            public void CertificateRoundtrip_Should_Succeed()
            {
                // Arrange
                var signerKey = RsaKey.Generate();
                var key       = RsaKey.Generate(
                    embeddedData: new byte[] { 0xa1, 0xb2, 0xc3, 0xd4 },
                    signKeyCallback: hash => (RsaSignature)signerKey.Sign(hash));
                var certificate = (RsaCertificate)key.DeriveCertificate();

                // Act
                RsaCertificate deserialized;

                using (var memoryStream = new MemoryStream())
                {
                    Xml.Serialize(
                        certificate: certificate,
                        stream: memoryStream);
                    memoryStream.Position = 0;
                    deserialized          = Xml.DeserializeCertificate(stream: memoryStream);
                }

                // Assert
                deserialized.Hash.Equals(certificate.Hash).Should().BeTrue();
                deserialized.EmbeddedData.SequenceEqual(certificate.EmbeddedData).Should().BeTrue();
                deserialized.Signature.SignerCertificateHash.Equals(certificate.Signature.SignerCertificateHash).Should().BeTrue();
                deserialized.Signature.Signature.SequenceEqual(certificate.Signature.Signature).Should().BeTrue();
            }
            public void UnsignedCertificate_ShouldThrow_TrustException()
            {
                // Arrange
                var certificate = RsaKey.Generate().DeriveCertificate();

                // Act & Assert
                Assert.Throws <TrustException>(() => ScenarioRsa.DefaultChain.Verify(certificate));
            }
Example #7
0
                public void SignCertificateNull_ShouldThrow_ArgumentNullException()
                {
                    // Arrange
                    var key = RsaKey.Generate();

                    // Act & Assert
                    Assert.Throws <ArgumentNullException>(() => key.Sign(certificate: null));
                }
Example #8
0
                public void GenerateWithEmbeddedDataHashAndSignCallbackNull_ShouldThrow_ArgumentNullException()
                {
                    // Arrange
                    var embeddedData = ScenarioRsa.DefaultEmbeddedData;

                    // Act & Assert
                    Assert.Throws <ArgumentNullException>(() => RsaKey.Generate(embeddedData: embeddedData, signKeyCallback: null));
                }
Example #9
0
 public void CertificateStreamNull_ShouldThrow_ArgumentNullException()
 {
     // Arrange
     // Act & Assert
     Assert.Throws <ArgumentNullException>(
         () => Xml.Serialize(
             certificate: (RsaCertificate)RsaKey.Generate().DeriveCertificate(),
             stream: null));
 }
            public void CertificateSignedByTrustedSigner_Should_Succeed()
            {
                // Arrange
                var certificate       = RsaKey.Generate().DeriveCertificate();
                var signedCertificate = ScenarioRsa.DefaultSignerKey.Sign((RsaCertificate)certificate);

                // Act
                // Assert
                ScenarioRsa.DefaultChain.Verify(signedCertificate);
            }
Example #11
0
                public void GenerateWithGenericEmbeddedDataWithoutSignature_Should_Succeed()
                {
                    // Arrange
                    var embeddedData = ScenarioRsa.DefaultEmbeddedData;

                    // Act
                    var key = RsaKey.Generate(embeddedData: embeddedData);

                    // Assert
                    key.EmbeddedData.SequenceEqual(embeddedData).Should().BeTrue();
                }
Example #12
0
            public void DeriveCertificateFromKey_Should_HaveSameHash()
            {
                // Arrange
                var key = RsaKey.Generate();

                // Act
                var certificate = key.DeriveCertificate();

                // Assert
                certificate.Hash.Equals(key.Hash);
            }
Example #13
0
                public void GenerateAndSignCallback_Should_StoreSignature()
                {
                    // Arrange
                    var signature = new RsaSignature(ScenarioRsa.DefaultSignerCertificate.Hash, new byte[] { 0x11, 0x11, 0x11, 0x11 });

                    // Act
                    var key = RsaKey.Generate((_hash) => signature);

                    // Assert
                    key.Signature.Should().BeSameAs(signature);
                    key.Signature.Should().BeSameAs(((IKey)key).Signature);
                }
Example #14
0
                public void DeriveWithEmbeddedData_Should_ReflectEmbeddedDataInCertificate()
                {
                    // Arrange
                    var embeddedData = ScenarioRsa.DefaultEmbeddedData;
                    var key          = RsaKey.Generate(embeddedData);

                    // Act
                    var certificate = key.DeriveCertificate();

                    // Assert
                    certificate.Should().BeOfType <RsaCertificate>();
                    certificate.EmbeddedData.SequenceEqual(embeddedData).Should().BeTrue();
                }
Example #15
0
                public void GenerateWithEmbeddedDataHashAndSignCallback_Should_StoreSignature()
                {
                    // Arrange
                    var embeddedData = ScenarioRsa.DefaultEmbeddedData;
                    var signature    = new RsaSignature(ScenarioRsa.DefaultSignerCertificate.Hash, new byte[] { 0x11, 0x11, 0x11, 0x11 });

                    // Act
                    var key = RsaKey.Generate(embeddedData: embeddedData, signKeyCallback: (_hash) => signature);

                    // Assert
                    key.EmbeddedData.SequenceEqual(embeddedData).Should().BeTrue();
                    key.Signature.Should().BeSameAs(signature);
                }
Example #16
0
                public void SignCertificateAndVerify_Should_Succeed()
                {
                    // Arrange
                    var key = RsaKey.Generate();

                    // Act
                    var signedCertificate = key.Sign(certificate: ScenarioRsa.DefaultCertificate);

                    // Assert
                    signedCertificate.Should().BeOfType <RsaCertificate>();
                    signedCertificate.Signature.SignerCertificateHash.Equals(key.Hash).Should().BeTrue();
                    key.DeriveCertificate().Verify(signedCertificate.Hash, signedCertificate.Signature);
                }
Example #17
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));
                }
Example #18
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);
                }
            public void CertificateSignedByTrustedSignerWhileSignerCertificateHashExistsTwice_ShouldThrow_TrustException()
            {
                // Arrange
                var certificate                 = RsaKey.Generate().DeriveCertificate();
                var signedCertificate           = ScenarioRsa.DefaultSignerKey.Sign((RsaCertificate)certificate);
                var signerCertificateParameters = ScenarioRsa.DefaultSignerCertificate.CreateRsa().ExportParameters(false);
                var signerCertificateDuplicate  = new RsaCertificate(
                    parameters: signerCertificateParameters,
                    embeddedData: ScenarioRsa.DefaultSignerCertificate.EmbeddedData);
                var chainOfTrust = new ChainOfTrust(
                    ScenarioRsa.DefaultSignerCertificate,
                    signerCertificateDuplicate);

                // Act & Assert
                Assert.Throws <TrustException>(() => chainOfTrust.Verify(signedCertificate));
            }
Example #20
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);
 }
Example #21
0
                public void Derive_Should_CreateCertificateWithSameRsaExponentAndModulusAndEmbeddedData()
                {
                    // Arrange
                    var key = RsaKey.Generate(embeddedData: new byte[] { 0xf1, 0xf2, 0xf3, 0xf4 });
                    var keyRsaParameters = key.CreateRsa().ExportParameters(true);

                    // Act
                    var certificate = key.DeriveCertificate();

                    // Assert
                    var certificateRsaParameters = certificate.CreateRsa().ExportParameters(false);

                    certificateRsaParameters.Exponent.SequenceEqual(keyRsaParameters.Exponent).Should().BeTrue();
                    certificateRsaParameters.Modulus.SequenceEqual(keyRsaParameters.Modulus).Should().BeTrue();
                    // Certificates may not export private RSA cryptographic parameters.
                    Assert.Throws(Is.InstanceOf <Exception>(), () => certificate.CreateRsa().ExportParameters(true));
                    certificate.EmbeddedData.SequenceEqual(key.EmbeddedData).Should().BeTrue();
                }
            public void WithEmbeddedDataButWithoutSignature_Should_Succeed()
            {
                // Arrange
                var originalKey = RsaKey.Generate(embeddedData: new byte[] { 0x01, 0x02, 0x03, 0x03 });

                // Act
                var model = SerializationModelConverter.Convert(key: originalKey);
                var key   = SerializationModelConverter.ConvertKeyModel(model: model);

                // Assert
                System.Convert.FromBase64String(model.Hash).SequenceEqual(originalKey.Hash.Hash).Should().BeTrue();
                key.Hash.Hash.SequenceEqual(originalKey.Hash.Hash).Should().BeTrue();
                System.Convert.FromBase64String(model.EmbeddedData).SequenceEqual(originalKey.EmbeddedData).Should().BeTrue();
                key.EmbeddedData.SequenceEqual(originalKey.EmbeddedData).Should().BeTrue();
                model.SignerCertificateHash.Should().BeNull();
                model.Signature.Should().BeNull();
                key.Signature.Should().BeNull();
            }
            public void WithoutEmbeddedDataAndWithoutSignature_Should_Succeed()
            {
                // Arrange
                var originalKey         = RsaKey.Generate();
                var originalCertificate = (RsaCertificate)originalKey.DeriveCertificate();

                // Act
                var model       = SerializationModelConverter.Convert(certificate: originalCertificate);
                var certificate = SerializationModelConverter.ConvertCertificateModel(model: model);

                // Assert
                System.Convert.FromBase64String(model.Hash).SequenceEqual(originalCertificate.Hash.Hash).Should().BeTrue();
                certificate.Hash.Hash.SequenceEqual(originalCertificate.Hash.Hash).Should().BeTrue();
                model.EmbeddedData.Should().BeNull();
                certificate.EmbeddedData.Should().BeNull();
                model.SignerCertificateHash.Should().BeNull();
                model.Signature.Should().BeNull();
                certificate.Signature.Should().BeNull();
            }
            public void WithoutEmbeddedDataButWithSignature_Should_Succeed()
            {
                // Arrange
                var signerKey   = RsaKey.Generate();
                var originalKey = RsaKey.Generate(signKeyCallback: hash => (RsaSignature)signerKey.Sign(hash));

                // Act
                var model = SerializationModelConverter.Convert(key: originalKey);
                var key   = SerializationModelConverter.ConvertKeyModel(model: model);

                // Assert
                System.Convert.FromBase64String(model.Hash).SequenceEqual(originalKey.Hash.Hash).Should().BeTrue();
                key.Hash.Hash.SequenceEqual(originalKey.Hash.Hash).Should().BeTrue();
                model.EmbeddedData.Should().BeNull();
                key.EmbeddedData.Should().BeNull();
                System.Convert.FromBase64String(model.SignerCertificateHash).SequenceEqual(originalKey.Signature.SignerCertificateHash.Hash).Should().BeTrue();
                System.Convert.FromBase64String(model.Signature).SequenceEqual(originalKey.Signature.Signature).Should().BeTrue();
                key.Signature.SignerCertificateHash.Hash.SequenceEqual(originalKey.Signature.SignerCertificateHash.Hash).Should().BeTrue();
                key.Signature.Signature.SequenceEqual(originalKey.Signature.Signature).Should().BeTrue();
            }
            public void WithEmbeddedDataAndWithSignature_Should_Succeed()
            {
                // Arrange
                var signerKey   = RsaKey.Generate();
                var originalKey = RsaKey.Generate(
                    embeddedData: new byte[] { 0x01, 0x02, 0x03, 0x03 },
                    signKeyCallback: hash => (RsaSignature)signerKey.Sign(hash));
                var originalCertificate = (RsaCertificate)originalKey.DeriveCertificate();

                // Act
                var model       = SerializationModelConverter.Convert(certificate: originalCertificate);
                var certificate = SerializationModelConverter.ConvertCertificateModel(model: model);

                // Assert
                System.Convert.FromBase64String(model.Hash).SequenceEqual(originalCertificate.Hash.Hash).Should().BeTrue();
                certificate.Hash.Hash.SequenceEqual(originalCertificate.Hash.Hash).Should().BeTrue();
                System.Convert.FromBase64String(model.EmbeddedData).SequenceEqual(originalCertificate.EmbeddedData).Should().BeTrue();
                certificate.EmbeddedData.SequenceEqual(originalCertificate.EmbeddedData).Should().BeTrue();
                System.Convert.FromBase64String(model.SignerCertificateHash).SequenceEqual(originalCertificate.Signature.SignerCertificateHash.Hash).Should().BeTrue();
                System.Convert.FromBase64String(model.Signature).SequenceEqual(originalCertificate.Signature.Signature).Should().BeTrue();
                certificate.Signature.SignerCertificateHash.Hash.SequenceEqual(originalCertificate.Signature.SignerCertificateHash.Hash).Should().BeTrue();
                certificate.Signature.Signature.SequenceEqual(originalCertificate.Signature.Signature).Should().BeTrue();
            }
Example #26
0
 public void GenerateAndSignCallbackNull_ShouldThrow_ArgumentNullException()
 {
     // Arrange
     // Act & Assert
     Assert.Throws <ArgumentNullException>(() => RsaKey.Generate(signKeyCallback: null));
 }
Example #27
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()));
        }