public void VerifyDataStreamAlgorithmNotSupported([EnumValues(Exclude = new[] { nameof(KeyType.Rsa), nameof(KeyType.RsaHsm), nameof(KeyType.Ec), nameof(KeyType.EcHsm) })] KeyType keyType)
        {
            JsonWebKey         jwk    = CreateKey(keyType);
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.VerifyDataAsync(new SignatureAlgorithm("ignored"), TestStream, TestData));
        }
        public void CreateClient()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:CreateKeyClient
            // Create a new key client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            // Create a new key using the key client.
            KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

            // Retrieve a key using the key client.
            key = client.GetKey("key-name");
            #endregion

            #region Snippet:CreateCryptographyClient
            // Create a new certificate client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential());
            #endregion

            this.client       = client;
            this.cryptoClient = cryptoClient;
        }
        public async Task EncryptDecryptRoundTrip([Fields] EncryptionAlgorithm algorithm)
        {
            Key key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient cryptoClient = GetCryptoClient(key.Id, forceRemote: true);

            byte[] data = new byte[32];
            Recording.Random.NextBytes(data);

            EncryptResult encResult = await cryptoClient.EncryptAsync(algorithm, data);

            Assert.AreEqual(algorithm, encResult.Algorithm);
            Assert.AreEqual(key.Id, encResult.KeyId);
            Assert.IsNotNull(encResult.Ciphertext);

            DecryptResult decResult = await cryptoClient.DecryptAsync(algorithm, encResult.Ciphertext);

            Assert.AreEqual(algorithm, decResult.Algorithm);
            Assert.AreEqual(key.Id, decResult.KeyId);
            Assert.IsNotNull(decResult.Plaintext);

            CollectionAssert.AreEqual(data, decResult.Plaintext);
        }
        public void CreateClient()
        {
            // Environment variable with the Key Vault endpoint.
            string vaultUrl = TestEnvironment.KeyVaultUrl;

            #region Snippet:CreateKeyClient
            // Create a new key client using the default credential from Azure.Identity using environment variables previously set,
            // including AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, and AZURE_TENANT_ID.
            var client = new KeyClient(vaultUri: new Uri(vaultUrl), credential: new DefaultAzureCredential());

            // Create a new key using the key client.
            KeyVaultKey key = client.CreateKey("key-name", KeyType.Rsa);

            // Retrieve a key using the key client.
            key = client.GetKey("key-name");
            #endregion

            #region Snippet:CreateCryptographyClient
            // Create a new cryptography client using the same Key Vault or Managed HSM endpoint, service version,
            // and options as the KeyClient created earlier.
            var cryptoClient = client.GetCryptographyClient(key.Name, key.Properties.Version);
            #endregion

            this.client       = client;
            this.cryptoClient = cryptoClient;
        }
Exemple #5
0
        private async Task <CryptographyClient> GetCryptographyClient(CancellationToken cancellationToken)
        {
            // Using DefaultAzureCredential to support local development. If developing
            // locally you'll need to register an AAD application and set the following
            // variables:
            //
            //      AZURE_TENANT_ID (the ID of the AAD tenant)
            //      AZURE_CLIENT_ID (the iD of the AAD application you registered)
            //      AZURE_CLIENT_SECRET (the secret for the AAD application you registered)
            //
            // You can get these values when you configure the application. Set them in
            // the Debug section of the project properties. Once this is done you will need
            // to create a KeyVault instance and then register a GitHub application and upload
            // the private key into the vault. The AAD application that you just created needs
            // to have Get and Sign rights - so set an access policy up which grants the app
            // those rights.
            //
            var credential = new DefaultAzureCredential();

            var keyClient = GetKeyClient(credential);
            var key       = await GetKey(keyClient, cancellationToken);

            var cryptographyClient = new CryptographyClient(key.Id, credential);

            return(cryptographyClient);
        }
Exemple #6
0
        /// <summary>
        /// Creates a new Key Vault context.
        /// </summary>
        public KeyVaultContext(TokenCredential credential, Uri keyId, X509Certificate2 publicCertificate, CryptographyClientOptions options = null)
        {
            if (credential is null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            Certificate   = publicCertificate ?? throw new ArgumentNullException(nameof(publicCertificate));
            KeyIdentifier = keyId ?? throw new ArgumentNullException(nameof(keyId));

            cryptographyClient = new CryptographyClient(keyId, credential, options);

            string algorithm = publicCertificate.GetKeyAlgorithm();

            switch (algorithm)
            {
            case "1.2.840.113549.1.1.1":     //rsa
                using (var rsa = publicCertificate.GetRSAPublicKey())
                {
                    Key = new JsonWebKey(rsa, includePrivateParameters: false);
                }
                break;

            case "1.2.840.10045.2.1":     //ec
                using (var ecdsa = publicCertificate.GetECDsaPublicKey())
                {
                    Key = new JsonWebKey(ecdsa, includePrivateParameters: false);
                }
                break;

            default:
                throw new NotSupportedException($"Certificate algorithm '{algorithm}' is not supported.");
            }
        }
        public async Task <(string, string)> DecryptAsync()
        {
            //string keyVaultName = "myfavouritekeyvault";
            string keyVaultUri     = "https://joeycrackvault.vault.azure.net";
            string keyVaultKeyName = "TestVaultKey";
            string textToEncrypt   = "cnbTestString";

            var defaultAzurecredentialsOption = new DefaultAzureCredentialOptions()
            {
                ExcludeManagedIdentityCredential = true,
                ExcludeVisualStudioCredential    = true,
                ExcludeAzurePowerShellCredential = true,
            };

            var client = new KeyClient(new Uri(keyVaultUri), new DefaultAzureCredential(defaultAzurecredentialsOption));

            await client.CreateRsaKeyAsync(new CreateRsaKeyOptions(keyVaultKeyName)).ConfigureAwait(false);

            KeyVaultKey key = await client.GetKeyAsync(keyVaultKeyName).ConfigureAwait(false);

            var cryptoClient = new CryptographyClient(key.Id, new DefaultAzureCredential());

            string encryptedString = await EncryptStringAsync(cryptoClient, textToEncrypt).ConfigureAwait(false);

            Console.WriteLine($"Encrypted string: {encryptedString}");
            //return $"Encrypted string: {encryptedString}";

            string decryptedString = await DecryptStringAsync(cryptoClient, encryptedString).ConfigureAwait(false);

            Console.WriteLine($"Decrypted string: {decryptedString}");
            return($"Encrypted string: {encryptedString}", $"Decrypted string: {decryptedString}");
        }
        public async Task AlgorithmNotSupportedRsa(string operation, string value, Func <CryptographyClient, string, Task <object> > thunk)
        {
            using RSA rsa = RSA.Create();
            KeyVaultKey key = new KeyVaultKey
            {
                Key = new JsonWebKey(rsa, includePrivateParameters: true)
                {
                    Id = KeyId,
                },
            };

            MockResponse response = new MockResponse(200);

            response.SetContent(@$ "{{" "kid" ":" "{KeyId}" "," "value" ":{value ?? @" "" test "" "}}}");

            CryptographyClient client = CreateClient(key, new MockTransport(_ => response));

            object result = await thunk(client, "invalid");

            Assert.IsNotNull(result);

            EventWrittenEventArgs e = _listener.SingleEventById(KeysEventSource.AlgorithmNotSupportedEvent);

            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("AlgorithmNotSupported", e.EventName);
            Assert.AreEqual(operation, e.GetProperty <string>("operation"));
            Assert.AreEqual("invalid", e.GetProperty <string>("algorithm"));
        }
        /*Creates example container and client side encrypted blob for sample
         *
         * NOTE: This program requires the following to be stored in the App.Config file:
         * Azure Active Directory Tenant ID - tenantId
         * Service Principal Application ID - clientId
         * Service Principal Password - clientSecret
         * Storage Account Connection String- connectionString
         * Client Side Key Vault Key Uri - clientSideKeyVaultKeyUri
         * Key Wrap Algorithm - keyWrapAlgorithm
         *
         * Creates example objects using names from Constants.cs, which may be edited as needed
         */
        static void Main()
        {
            //Credentials of Service Principal
            TokenCredential credential =
                new ClientSecretCredential(
                    Constants.TenantId,
                    Constants.ClientId,
                    Constants.ClientSecret
                    );

            //Get Uri for Key Vault key
            Uri keyVaultKeyUri = new Uri(Constants.ClientSideKeyVaultKeyUri);
            //Create CryptographyClient using Key Vault Key
            CryptographyClient cryptographyClient = new CryptographyClient(keyVaultKeyUri, credential);
            //Set up Client Side Encryption Options used for Client Side Encryption
            ClientSideEncryptionOptions clientSideOptions = new ClientSideEncryptionOptions(ClientSideEncryptionVersion.V1_0)
            {
                KeyEncryptionKey = cryptographyClient,
                KeyWrapAlgorithm = Constants.KeyWrapAlgorithm
            };

            //Create Blob Service Client
            BlobServiceClient blobServiceClient = new BlobServiceClient(Constants.ConnectionString);

            //Run Setup Function that creates and example container and blob
            SetupForExample(
                blobServiceClient,
                Constants.ContainerName,
                Constants.BlobName,
                clientSideOptions);

            Console.WriteLine("Completed creation of example container and blob");
        }
        public void AesEncryptAlgorithmNotSupported([EnumValues(nameof(EncryptionAlgorithm.A128Gcm), nameof(EncryptionAlgorithm.A192Gcm), nameof(EncryptionAlgorithm.A256Gcm))] EncryptionAlgorithm algorithm)
        {
            JsonWebKey         jwk    = CreateKey(KeyType.Oct);
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.EncryptAsync(algorithm, TestData));
        }
        public void DecryptOperationNotSupported()
        {
            JsonWebKey         jwk    = new JsonWebKey(RSA.Create(), keyOps: Array.Empty <KeyOperation>());
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.DecryptAsync(new EncryptionAlgorithm("ignored"), TestData));
        }
        public void EncryptAlgorithmNotSupported([EnumValues(Exclude = new[] { nameof(KeyType.Rsa), nameof(KeyType.RsaHsm), nameof(KeyType.Oct), nameof(KeyType.OctHsm) })] KeyType keyType)
        {
            JsonWebKey         jwk    = CreateKey(keyType);
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.EncryptAsync(new EncryptionAlgorithm("ignored"), TestData));
        }
        public void UnwrapKeyAlgorithmNotSupported([EnumValues(Exclude = new[] { nameof(KeyType.Ec), nameof(KeyType.EcHsm) })] KeyType keyType)
        {
            JsonWebKey         jwk    = CreateKey(keyType);
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.UnwrapKeyAsync(new KeyWrapAlgorithm("ignored"), TestData));
        }
        public void SignDataStreamRequiresPrivateKey([EnumValues] SignatureAlgorithm algorithm)
        {
            JsonWebKey         jwk    = KeyUtilities.CreateKey(algorithm, keyOps: new[] { KeyOperation.Sign, KeyOperation.Verify });
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync(new InstanceOfTypeConstraint(typeof(CryptographicException)), async() => await client.SignDataAsync(algorithm, TestStream));
        }
Exemple #15
0
        public async Task AlgorithmNotSupportedAes(string operation, Func <CryptographyClient, string, Task <object> > thunk)
        {
            using Aes aes = Aes.Create();
            KeyVaultKey key = new KeyVaultKey
            {
                Key = new JsonWebKey(aes)
                {
                    Id = KeyId,
                },
            };

            MockResponse response = new MockResponse(200);

            response.SetContent(@$ "{{" "kid" ":" "{KeyId}" "," "value" ":" "test" "}}");

            MockTransport      transport = new MockTransport(response);
            CryptographyClient client    = CreateClient(key, transport);

            object result = await thunk(client, "invalid");

            Assert.IsNotNull(result);

            EventWrittenEventArgs e = _listener.SingleEventById(KeysEventSource.AlgorithmNotSupportedEvent);

            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("AlgorithmNotSupported", e.EventName);
            Assert.AreEqual("invalid", e.GetProperty <string>("algorithm"));
        }
Exemple #16
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            //var credential = new ClientSecretCredential("231dd9cd-ddc7-4fba-ae78-9f4ac3c912e7", "5f43fe5c-1c2b-4afa-97e6-fda41302e28b", "5ZlLakKHA:DE.6Jq-GbJWF=icJaCwW32");
            var credential = new ManagedIdentityCredential();
            var kvUri      = "https://kvswapana.vault.azure.net/";

            var           secretClient = new SecretClient(new Uri(kvUri), credential);
            var           encryptedDEK = secretClient.GetSecret("DEK");
            var           keyClient    = new KeyClient(new Uri(kvUri), credential);
            var           encryptedKEY = keyClient.GetKey("KEK");
            var           cryptoClient = new CryptographyClient(encryptedKEY.Value.Id, credential);
            DecryptResult decryptDek   = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, Convert.FromBase64String(encryptedDEK.Value.Value));

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            name = name ?? data?.name;

            return(name != null
                   // Create MemoryStream
                ? (ActionResult) new OkObjectResult($"Hello, {name}, {encryptedKEY.Value.Id}, {Encoding.UTF8.GetString(decryptDek.Plaintext)}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body"));
        }
Exemple #17
0
        public async Task AlgorithmNotSupportedEc(string operation, string value, Func <CryptographyClient, string, Task <object> > thunk)
        {
            KeyVaultKey key = new KeyVaultKey
            {
                Key = new JsonWebKey(new[] { KeyOperation.Sign, KeyOperation.Verify })
                {
                    Id        = KeyId,
                    KeyType   = KeyType.Ec,
                    CurveName = "invalid",
                },
            };

            MockResponse response = new MockResponse(200);

            response.SetContent(@$ "{{" "kid" ":" "{KeyId}" "," "value" ":{value ?? @" "" test "" "}}}");

            CryptographyClient client = CreateClient(key, new MockTransport(response));

            object result = await thunk(client, "invalid");

            Assert.IsNotNull(result);

            EventWrittenEventArgs e = _listener.SingleEventById(KeysEventSource.AlgorithmNotSupportedEvent);

            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("AlgorithmNotSupported", e.EventName);
            Assert.AreEqual(operation, e.GetProperty <string>("operation"));
            Assert.AreEqual("invalid", e.GetProperty <string>("algorithm"));
        }
Exemple #18
0
        private async Task <string> SignAndCreateJwtAsync(JwtSecurityToken jwt)
        {
            var algorithm = "RS256";//jwt.SignatureAlgorithm;

            var plaintext = $"{jwt.EncodedHeader}.{jwt.EncodedPayload}";

            byte[] hash;
            using (var hasher = CryptoHelper.GetHashAlgorithmForSigningAlgorithm(algorithm))
            {
                hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(plaintext));
            }

            var cryptoClient = new CryptographyClient(
                new Uri("https://cleankey.vault.azure.net/keys/cleankey/82f7ce0323574ab4869565d3bc525793"),
                new DefaultAzureCredential());

            try
            {
                //jwt.SignatureAlgorithm
                var signResult = await cryptoClient.SignAsync(new SignatureAlgorithm(algorithm), hash);

                return($"{plaintext}.{Base64UrlTextEncoder.Encode(signResult.Signature)}");
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Exemple #19
0
        public async Task AesKwWrapUnwrapRoundTrip([EnumValues(
                                                        nameof(KeyWrapAlgorithm.A128KW),
                                                        nameof(KeyWrapAlgorithm.A192KW),
                                                        nameof(KeyWrapAlgorithm.A256KW))] KeyWrapAlgorithm algorithm)
        {
            KeyVaultKey key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient remoteClient = GetCryptoClient(key.Id, forceRemote: true);

            byte[] plaintext = new byte[32];
            Recording.Random.NextBytes(plaintext);

            WrapResult encrypted = await remoteClient.WrapKeyAsync(algorithm, plaintext);

            Assert.AreEqual(algorithm, encrypted.Algorithm);
            Assert.AreEqual(key.Id, encrypted.KeyId);
            Assert.IsNotNull(encrypted.EncryptedKey);

            UnwrapResult decrypted = await remoteClient.UnwrapKeyAsync(algorithm, encrypted.EncryptedKey);

            Assert.AreEqual(algorithm, decrypted.Algorithm);
            Assert.AreEqual(key.Id, decrypted.KeyId);
            Assert.IsNotNull(decrypted.Key);

            CollectionAssert.AreEqual(plaintext, decrypted.Key);
        }
        public async Task SignLocalVerifyRoundTrip([Fields(nameof(SignatureAlgorithm.ES256), nameof(SignatureAlgorithm.ES384), nameof(SignatureAlgorithm.ES512))] SignatureAlgorithm algorithm)
        {
            Key key = await CreateTestKey(algorithm);

            RegisterForCleanup(key);

            CryptographyClient client = GetCryptoClient(key.Id);

            byte[] data = new byte[32];
            Recording.Random.NextBytes(data);

            using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm();
            byte[] digest = hashAlgo.ComputeHash(data);

            // Should sign remotely...
            SignResult signResult = await client.SignAsync(algorithm, digest);

            Assert.AreEqual(algorithm, signResult.Algorithm);
            Assert.AreEqual(key.KeyMaterial.KeyId, signResult.KeyId);
            Assert.NotNull(signResult.Signature);

            // ...and verify locally.
            VerifyResult verifyResult = await client.VerifyAsync(algorithm, digest, signResult.Signature);

            Assert.AreEqual(algorithm, verifyResult.Algorithm);
            Assert.AreEqual(key.KeyMaterial.KeyId, verifyResult.KeyId);
            Assert.IsTrue(verifyResult.IsValid);
        }
Exemple #21
0
        static void Main(string[] args)
        {
            string keyVaultUrl = "https://demovault2090.vault.azure.net/";
            var    client      = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential());

            // Getting the Encryption key from the key vault
            KeyVaultKey key = client.GetKey("newkey");

            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential());

            byte[] plaintext = Encoding.UTF8.GetBytes("This is sensitive data");

            // Encrypting data
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep256, plaintext);

            //Decrypting data
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, encryptResult.Ciphertext);

            Console.WriteLine("Plain text");

            string txt = Encoding.UTF8.GetString(decryptResult.Plaintext);

            Console.WriteLine(txt);
            Console.ReadLine();
        }
Exemple #22
0
        /// <summary>
        /// Wrap the Key with latest Key version.
        /// Only supports bytes in base64 format.
        /// </summary>
        /// <param name="key">plain text key.</param>
        /// <param name="keyVaultUriProperties">Parsed key Vault Uri Properties.Properties as in sample Format: https://{keyvault-name}.vault.azure.net/keys/{key-name}/{key-version}.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>Result including KeyIdentifier and encrypted bytes in base64 string format.</returns>
        public async Task <byte[]> WrapKeyAsync(
            byte[] key,
            KeyVaultKeyUriProperties keyVaultUriProperties,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            WrapResult keyOpResult;

            // Get a Crypto Client for Wrap and UnWrap,this gets init per Key ID
            CryptographyClient cryptoClient = await this.GetCryptoClientAsync(keyVaultUriProperties, cancellationToken);

            try
            {
                keyOpResult = await cryptoClient.WrapKeyAsync(KeyVaultConstants.RsaOaep256, key, cancellationToken);
            }
            catch (RequestFailedException ex)
            {
                throw new KeyVaultAccessException(
                          ex.Status,
                          ex.ErrorCode,
                          "WrapKeyAsync: Failed to Wrap the data encryption key.",
                          ex);
            }

            return(keyOpResult.EncryptedKey);
        }
Exemple #23
0
        public async Task EncryptLocalDecryptOnKeyVault([EnumValues(nameof(EncryptionAlgorithm.Rsa15), nameof(EncryptionAlgorithm.RsaOaep), nameof(EncryptionAlgorithm.RsaOaep256))] EncryptionAlgorithm algorithm)
        {
            KeyVaultKey key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient remoteClient = GetCryptoClient(key.Id, forceRemote: true);
            CryptographyClient localClient  = GetLocalCryptoClient(key.Key);

            byte[] plaintext = new byte[32];
            Recording.Random.NextBytes(plaintext);

            EncryptResult encrypted = await localClient.EncryptAsync(algorithm, plaintext);

            Assert.AreEqual(algorithm, encrypted.Algorithm);
            Assert.AreEqual(key.Id, encrypted.KeyId);
            Assert.IsNotNull(encrypted.Ciphertext);

            DecryptResult decrypted = await remoteClient.DecryptAsync(algorithm, encrypted.Ciphertext);

            Assert.AreEqual(algorithm, decrypted.Algorithm);
            Assert.AreEqual(key.Id, decrypted.KeyId);
            Assert.IsNotNull(decrypted.Plaintext);

            CollectionAssert.AreEqual(plaintext, decrypted.Plaintext);
        }
Exemple #24
0
        public async Task KeyTypeNotSupported(string operation, string value, Func <CryptographyClient, string, Task <object> > thunk)
        {
            MockResponse keyResponse = new MockResponse(200);

            keyResponse.SetContent($@"{{""key"":{{""kid"":""{KeyId}"",""kty"":""invalid""}}}}");

            // Get the same key as above and reset the stream.
            KeyVaultKey key = new KeyVaultKey();

            key.Deserialize(keyResponse.ContentStream);
            keyResponse.ContentStream.Position = 0;

            MockResponse resultResponse = new MockResponse(200);

            resultResponse.SetContent(@$ "{{" "kid" ":" "{KeyId}" "," "value" ":{value ?? @" "" test "" "}}}");

            CryptographyClient client = CreateClient(key, new MockTransport(keyResponse, resultResponse));

            object result = await thunk(client, "invalid");

            Assert.IsNotNull(result);

            EventWrittenEventArgs e = _listener.SingleEventById(KeysEventSource.KeyTypeNotSupportedEvent);

            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("KeyTypeNotSupported", e.EventName);
            Assert.AreEqual(operation, e.GetProperty <string>("operation"));
            Assert.AreEqual("invalid", e.GetProperty <string>("keyType"));
        }
Exemple #25
0
        private CryptographyClient GetCryptoClient(Uri keyId, bool forceRemote = false)
        {
            CryptographyClientOptions options = InstrumentClientOptions(new CryptographyClientOptions((CryptographyClientOptions.ServiceVersion)_serviceVersion));
            CryptographyClient        client  = new CryptographyClient(keyId, TestEnvironment.Credential, options, forceRemote);

            return(InstrumentClient(client));
        }
Exemple #26
0
        public async Task PrivateKeyRequiredEc(string operation, string value, Func <CryptographyClient, string, Task <object> > thunk)
        {
#if NET461
            Assert.Ignore("Creating JsonWebKey with ECDsa is not supported on net461.");
#endif

            KeyOperation[] keyOps = new[]
            {
                KeyOperation.Sign,
                KeyOperation.Verify,
            };

            using ECDsa ecdsa = ECDsa.Create();
            KeyVaultKey key = new KeyVaultKey
            {
                Key = new JsonWebKey(ecdsa, includePrivateParameters: false, keyOps)
                {
                    Id = KeyId,
                },
            };

            MockResponse response = new MockResponse(200);
            response.SetContent(@$ "{{" "kid" ":" "{KeyId}" "," "value" ":{value ?? @" "" test "" "}}}");

            CryptographyClient client = CreateClient(key, new MockTransport(response));

            object result = await thunk(client, "invalid");

            Assert.IsNotNull(result);

            EventWrittenEventArgs e = _listener.SingleEventById(KeysEventSource.PrivateKeyRequiredEvent);
            Assert.AreEqual(EventLevel.Verbose, e.Level);
            Assert.AreEqual("PrivateKeyRequired", e.EventName);
            Assert.AreEqual(operation, e.GetProperty <string>("operation"));
        }
        public async Task SignLocalVerifyRoundTripFramework([Fields(nameof(SignatureAlgorithm.PS256), nameof(SignatureAlgorithm.PS384), nameof(SignatureAlgorithm.PS512))] SignatureAlgorithm algorithm)
        {
#if !NETFRAMEWORK
            // RSA-PSS is not supported on .NET Framework so recorded tests will fall back to the remote client.
            Assert.Ignore("RSA-PSS is supported on .NET Core so local tests will pass. This test method is to test that on .NET Framework RSA-PSS sign/verify attempts fall back to the remote client.");
#endif

            Key key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient client = GetCryptoClient(key.Properties.Id);

            byte[] data = new byte[32];
            Recording.Random.NextBytes(data);

            using HashAlgorithm hashAlgo = algorithm.GetHashAlgorithm();
            byte[] digest = hashAlgo.ComputeHash(data);

            // Should sign remotely...
            SignResult signResult = await client.SignAsync(algorithm, digest);

            Assert.AreEqual(algorithm, signResult.Algorithm);
            Assert.AreEqual(key.KeyMaterial.KeyId, signResult.KeyId);
            Assert.NotNull(signResult.Signature);

            // ...and verify locally.
            VerifyResult verifyResult = await client.VerifyAsync(algorithm, digest, signResult.Signature);

            Assert.AreEqual(algorithm, verifyResult.Algorithm);
            Assert.AreEqual(key.KeyMaterial.KeyId, verifyResult.KeyId);
            Assert.IsTrue(verifyResult.IsValid);
        }
Exemple #28
0
        public async Task CryptographicException(string operation, string value, Func <CryptographyClient, string, Task <object> > thunk)
        {
            using RSA rsa = RSA.Create();
            KeyVaultKey key = new KeyVaultKey
            {
                Key = new JsonWebKey(rsa, includePrivateParameters: true)
                {
                    Id = KeyId,
                },
            };

            Random rand = new Random();

            rand.NextBytes(key.Key.N);

            MockResponse response = new MockResponse(200);

            response.SetContent(@$ "{{" "kid" ":" "{KeyId}" "," "value" ":{value ?? @" "" test "" "}}}");

            CryptographyClient client = CreateClient(key, new MockTransport(response), new ThrowingCryptographyProvider());

            object result = await thunk(client, null);

            Assert.IsNotNull(result);

            EventWrittenEventArgs e = _listener.SingleEventById(KeysEventSource.CryptographicExceptionEvent);

            Assert.AreEqual(EventLevel.Informational, e.Level);
            Assert.AreEqual("CryptographicException", e.EventName);
            Assert.AreEqual(operation, e.GetProperty <string>("operation"));
            StringAssert.StartsWith("System.Security.Cryptography.CryptographicException (0x80092006):", e.GetProperty <string>("message"));
        }
        public async Task WrapUnwrapRoundTrip([Fields] KeyWrapAlgorithm algorithm)
        {
            Key key = await CreateTestKey(algorithm);

            RegisterForCleanup(key.Name);

            CryptographyClient cryptoClient = GetCryptoClient(key.Id, forceRemote: true);

            byte[] data = new byte[32];
            Recording.Random.NextBytes(data);

            WrapResult encResult = await cryptoClient.WrapKeyAsync(algorithm, data);

            Assert.AreEqual(algorithm, encResult.Algorithm);
            Assert.AreEqual(key.Id, encResult.KeyId);
            Assert.IsNotNull(encResult.EncryptedKey);

            UnwrapResult decResult = await cryptoClient.UnwrapKeyAsync(algorithm, encResult.EncryptedKey);

            Assert.AreEqual(algorithm, decResult.Algorithm);
            Assert.AreEqual(key.Id, decResult.KeyId);
            Assert.IsNotNull(decResult.Key);

            CollectionAssert.AreEqual(data, decResult.Key);
        }
        public void VerifyDataStreamOperationNotSupported()
        {
            JsonWebKey         jwk    = new JsonWebKey(RSA.Create(), keyOps: Array.Empty <KeyOperation>());
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.VerifyDataAsync(new SignatureAlgorithm("ignored"), TestStream, TestData));
        }