Пример #1
0
        public void ShouldSignXml()
        {
            // Given
            var signingCertificate = TestCertificates.GetCertificate();
            var xmlDocument        = CreateXmlDocument();

            // When
            var signedXmlDocument = SignXmlDocument(xmlDocument, signingCertificate);

            // Then
            Assert.IsTrue(VerifyXmlDocumentSignature(signedXmlDocument));
        }
Пример #2
0
        public void ShouldSignXml()
        {
            // Given
            var signingCertificate = TestCertificates.GetCertificate();
            var smevRequest        = CreateSmevRequest();

            // When
            var signedXmlDocument = SignSmevRequest(smevRequest, signingCertificate);

            // Then
            Assert.IsTrue(VerifySmevRequestSignature(signedXmlDocument));
        }
Пример #3
0
        protected virtual async Task SasProvisionEdgeAsync(bool withCerts = false)
        {
            using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
            {
                CancellationToken token     = cts.Token;
                DateTime          startTime = DateTime.Now;

                this.device = await EdgeDevice.GetOrCreateIdentityAsync(
                    Context.Current.DeviceId.GetOrElse(DeviceId.Current.Generate()),
                    this.GetNestedEdgeConfig(this.IotHub),
                    this.IotHub,
                    AuthenticationType.Sas,
                    null,
                    token);

                Log.Information($"Device ID {this.device.Id}");

                Context.Current.DeleteList.TryAdd(this.device.Id, this.device);

                this.runtime = new EdgeRuntime(
                    this.device.Id,
                    Context.Current.EdgeAgentImage,
                    Context.Current.EdgeHubImage,
                    Context.Current.EdgeProxy,
                    Context.Current.Registries,
                    Context.Current.OptimizeForPerformance,
                    this.IotHub);

                // This is a temporary solution see ticket: 9288683
                if (!Context.Current.ISA95Tag)
                {
                    TestCertificates testCerts;
                    (testCerts, this.ca) = await TestCertificates.GenerateCertsAsync(this.device.Id, token);

                    await this.ConfigureDaemonAsync(
                        config =>
                    {
                        testCerts.AddCertsToConfig(config);

                        config.SetManualSasProvisioning(Context.Current.ParentHostname.GetOrElse(this.device.HubHostname), this.device.Id, this.device.SharedAccessKey);

                        config.Update();
                        return(Task.FromResult((
                                                   "with connection string for device '{Identity}'",
                                                   new object[] { this.device.Id })));
                    },
                        this.device,
                        startTime,
                        token);
                }
            }
        }
Пример #4
0
        public void ShouldSign()
        {
            // Given
            var certificate = TestCertificates.GetCertificate();
            var message     = CreateMessage();

            // When
            var detachedSignature        = SignMessage(certificate, message);
            var isValudDetachedSignature = VerifyMessage(message, detachedSignature);

            // Then
            Assert.IsTrue(isValudDetachedSignature);
        }
Пример #5
0
        public void ShouldSignXml()
        {
            // Given
            var keyContainer = TestCertificates.GetKeyContainer();
            var signingKey   = new Gost3410AsymmetricAlgorithm(keyContainer);
            var xmlDocument  = CreateXmlDocument();

            // When
            var signedXmlDocument = SignXmlDocument(xmlDocument, signingKey);

            // Then
            Assert.IsTrue(VerifyXmlDocumentSignature(signedXmlDocument));
        }
Пример #6
0
        public void ShouldEncryptAndDecrypt()
        {
            // Given
            var certificate = TestCertificates.GetCertificate();
            var message     = CreateMessage();

            // When
            var encryptedMessage = EncryptMessage(certificate, message);
            var decryptedMessage = DecryptMessage(encryptedMessage);

            // Then
            Assert.IsTrue(message.SequenceEqual(decryptedMessage));
        }
Пример #7
0
        public void ShouldSign()
        {
            // Given
            var certificate = TestCertificates.GetCertificate();
            var message     = CreateMessage();

            // When
            var signedMessage        = SignMessage(certificate, message);
            var isValudSignedMessage = VerifyMessage(signedMessage);

            // Then
            Assert.IsTrue(isValudSignedMessage);
        }
Пример #8
0
        internal virtual IConnectionProperties?CreateListenerProperties()
        {
            if (!UseSsl)
            {
                return(null);
            }

            var properties = new ConnectionProperties();

            properties.Add(SslConnectionFactory.SslServerAuthenticationOptionsPropertyKey, new SslServerAuthenticationOptions
            {
                ServerCertificate = TestCertificates.GetSelfSigned13ServerCertificate()
            });
            return(properties);
        }
Пример #9
0
        public void ShouldEncryptXml()
        {
            // Given
            var certificate = TestCertificates.GetCertificate();
            var xmlDocument = CreateXmlDocument();
            var expectedXml = xmlDocument.OuterXml;

            // When
            var encryptedXmlDocument = EncryptXmlDocument(xmlDocument, certificate);
            var decryptedXmlDocument = DecryptXmlDocument(encryptedXmlDocument);
            var actualXml            = decryptedXmlDocument.OuterXml;

            // Then
            Assert.AreEqual(expectedXml, actualXml);
        }
Пример #10
0
        static IOAuthSession CreateConsumer(string signatureMethod)
        {
            var consumerContext = new OAuthConsumerContext
            {
                SignatureMethod = signatureMethod,
                ConsumerKey     = "key",
                ConsumerSecret  = "secret",
                Key             = TestCertificates.OAuthTestCertificate().PrivateKey
            };

            var session = new OAuthSession(consumerContext, "http://localhost/oauth/requesttoken.rails",
                                           "http://localhost/oauth/userauhtorize.rails",
                                           "http://localhost/oauth/accesstoken.rails");

            return(session);
        }
Пример #11
0
    protected IOAuthSession CreateSession()
    {
      string callBackUrl = "http://localhost:" + HttpContext.Current.Request.Url.Port + "/Callback.aspx";

      var consumerContext = new OAuthConsumerContext
        {
          ConsumerKey = "key",
          ConsumerSecret = "secret",
          Key = TestCertificates.OAuthTestCertificate().PrivateKey
        };

      return new OAuthSession(consumerContext,
                                     Settings.Default.RequestTokenUrl,
                                     Settings.Default.UserAuthorizationUrl,
                                     Settings.Default.AccessTokenUrl,
                                     callBackUrl).RequiresCallbackConfirmation();      
    }
Пример #12
0
        public async Task DpsSymmetricKey()
        {
            string idScope        = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope"));
            string groupKey       = Context.Current.DpsGroupKey.Expect(() => new InvalidOperationException("Missing DPS enrollment group key"));
            string registrationId = DeviceId.Current.Generate();

            string deviceKey = this.DeriveDeviceKey(Convert.FromBase64String(groupKey), registrationId);

            CancellationToken token = this.TestToken;

            (TestCertificates testCerts, _) = await TestCertificates.GenerateCertsAsync(registrationId, token);

            await this.daemon.ConfigureAsync(
                config =>
            {
                testCerts.AddCertsToConfig(config);
                config.SetDpsSymmetricKey(idScope, registrationId, deviceKey);
                config.Update();
                return(Task.FromResult((
                                           "with DPS symmetric key attestation for '{Identity}'",
                                           new object[] { registrationId })));
            },
                token);

            await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

            var agent = new EdgeAgent(registrationId, this.iotHub);
            await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);

            await agent.PingAsync(token);

            Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync(
                registrationId,
                Context.Current.ParentDeviceId,
                this.iotHub,
                token,
                takeOwnership : true);

            Context.Current.DeleteList.TryAdd(
                registrationId,
                device.Expect(() => new InvalidOperationException(
                                  $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'")));
        }
Пример #13
0
        public void ShouldSignDataStream()
        {
            // Given
            var certificate = TestCertificates.GetCertificate();
            var privateKey  = (Gost3410AsymmetricAlgorithmBase)certificate.GetPrivateKeyAlgorithm();
            var publicKey   = (Gost3410AsymmetricAlgorithmBase)certificate.GetPrivateKeyAlgorithm();
            var dataStream  = CreateDataStream();

            // When

            dataStream.Seek(0, SeekOrigin.Begin);
            var signature = CreateSignature(privateKey, dataStream);

            dataStream.Seek(0, SeekOrigin.Begin);
            var isValidSignature = VerifySignature(publicKey, dataStream, signature);

            // Then
            Assert.IsTrue(isValidSignature);
        }
        public void ShouldSign()
        {
            // Given
            var certificate = TestCertificates.GetCertificate();

            Assert.IsNotNull(certificate);
            Assert.AreEqual(certificate.SignatureAlgorithm.Value, "1.2.643.2.2.3");
            var message = CreateMessage();

            // When
            var signedMessage = SignMessage(certificate, message);
            var bFile         = Convert.ToBase64String(signedMessage);

            File.WriteAllBytes("test.txt", signedMessage);
            var isValudSignedMessage = VerifyMessage(signedMessage);

            // Then
            Assert.IsTrue(isValudSignedMessage);
        }
        public async Task Connect_SelfSigned_Success()
        {
            var protocols = new List <SslApplicationProtocol> {
                new SslApplicationProtocol("test")
            };

            var connectProperties = new ConnectionProperties();

            connectProperties.Add(SslConnectionFactory.SslClientAuthenticationOptionsPropertyKey, new SslClientAuthenticationOptions
            {
                TargetHost           = "localhost",
                ApplicationProtocols = protocols,
                RemoteCertificateValidationCallback = delegate { return(true); }
            });

            var listenProperties = new ConnectionProperties();

            listenProperties.Add(SslConnectionFactory.SslServerAuthenticationOptionsPropertyKey, new SslServerAuthenticationOptions
            {
                ApplicationProtocols = protocols,
                ServerCertificate    = TestCertificates.GetSelfSigned13ServerCertificate()
            });

            byte[] sendBuffer = Encoding.ASCII.GetBytes("Testing 123");

            await using ConnectionFactory factory   = new SslConnectionFactory(new MemoryConnectionFactory());
            await using ConnectionListener listener = await factory.ListenAsync(options : listenProperties);

            await RunClientServer(
                async() =>
            {
                await using Connection connection = await factory.ConnectAsync(listener.EndPoint !, connectProperties);
                await connection.Stream.WriteAsync(sendBuffer);
            },
                async() =>
            {
                await using Connection? connection = await listener.AcceptConnectionAsync();
                Assert.NotNull(connection);
                Debug.Assert(connection != null);

                byte[] buffer = new byte[sendBuffer.Length + 1];
                int readLen   = await connection.Stream.ReadAsync(buffer);
                Assert.Equal(sendBuffer, buffer[..readLen]);
Пример #16
0
        public void SetUp()
        {
            // Получатель извлекает информацию о закрытом ключе из контейнера ключей
            var keyContainer = TestCertificates.GetKeyContainer();

            // Получатель формирует закрытый ключ для дешифрации XML
            var privateKey = new Gost3410AsymmetricAlgorithm(keyContainer);

            // Получатель экспортирует отправителю информацию о своем открытом ключе
            var publicKeyInfo = privateKey.ExportParameters(false);

            // Отправитель импортирует от получателя информацию о его открытом ключе
            var publicKey = new Gost3410AsymmetricAlgorithm();

            // Отправитель формирует открытый ключ для шифрации XML
            publicKey.ImportParameters(publicKeyInfo);

            _privateKey = privateKey;
            _publicKey  = publicKey;
        }
        public void RsaSha1SignatureMethodFetchesCertificate()
        {
            var repository = new MockRepository();

            var consumerStore = repository.DynamicMock <IConsumerStore>();
            var signer        = repository.StrictMock <IOAuthContextSigner>();

            var context = new OAuthContext {
                ConsumerKey = "key", SignatureMethod = SignatureMethod.RsaSha1
            };

            using (repository.Record())
            {
                Expect.Call(consumerStore.GetConsumerPublicKey(context)).Return(
                    TestCertificates.OAuthTestCertificate().PublicKey.Key);
                Expect.Call(signer.ValidateSignature(null, null)).IgnoreArguments().Return(true);
            }
            using (repository.Playback())
            {
                var inspector = new SignatureValidationInspector(consumerStore, signer);
                inspector.InspectContext(ProviderPhase.GrantRequestToken, context);
            }
        }
Пример #18
0
        public async Task DpsX509()
        {
            (string, string, string)rootCa =
                Context.Current.RootCaKeys.Expect(() => new InvalidOperationException("Missing DPS ID scope (check rootCaPrivateKeyPath in context.json)"));
            string caCertScriptPath =
                Context.Current.CaCertScriptPath.Expect(() => new InvalidOperationException("Missing CA cert script path (check caCertScriptPath in context.json)"));
            string idScope        = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope (check dpsIdScope in context.json)"));
            string registrationId = DeviceId.Current.Generate();

            CancellationToken token = this.TestToken;

            CertificateAuthority ca = await CertificateAuthority.CreateAsync(
                registrationId,
                rootCa,
                caCertScriptPath,
                token);

            IdCertificates idCert = await ca.GenerateIdentityCertificatesAsync(registrationId, token);

            (TestCertificates testCerts, _) = await TestCertificates.GenerateCertsAsync(registrationId, token);

            // Generated credentials need to be copied out of the script path because future runs
            // of the script will overwrite them.
            string path     = Path.Combine(FixedPaths.E2E_TEST_DIR, registrationId);
            string certPath = Path.Combine(path, "device_id_cert.pem");
            string keyPath  = Path.Combine(path, "device_id_cert_key.pem");

            Directory.CreateDirectory(path);
            File.Copy(idCert.CertificatePath, certPath);
            OsPlatform.Current.SetOwner(certPath, "aziotcs", "644");
            File.Copy(idCert.KeyPath, keyPath);
            OsPlatform.Current.SetOwner(keyPath, "aziotks", "600");

            await this.daemon.ConfigureAsync(
                config =>
            {
                testCerts.AddCertsToConfig(config);
                config.SetDpsX509(idScope, registrationId, certPath, keyPath);
                config.Update();
                return(Task.FromResult((
                                           "with DPS X509 attestation for '{Identity}'",
                                           new object[] { registrationId })));
            },
                token);

            await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

            var agent = new EdgeAgent(registrationId, this.iotHub);
            await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);

            await agent.PingAsync(token);

            Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync(
                registrationId,
                this.iotHub,
                token,
                takeOwnership : true);

            Context.Current.DeleteList.TryAdd(
                registrationId,
                device.Expect(() => new InvalidOperationException(
                                  $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'")));
        }
Пример #19
0
 public AsymmetricAlgorithm GetConsumerPublicKey(IConsumer consumer)
 {
     return(TestCertificates.OAuthTestCertificate().PublicKey.Key);
 }
Пример #20
0
 public X509Certificate2 GetConsumerCertificate(IConsumer consumer)
 {
   return TestCertificates.OAuthTestCertificate();
 }
Пример #21
0
 public System.Security.Cryptography.AsymmetricAlgorithm GetConsumerPublicKey(IConsumer consumer)
 {
     return(TestCertificates.OAuthTestCertificate().PublicKey.Key);
 }