Example #1
0
        public async Task <WrapResult <object> > Get(int id)
        {
            var data = new GoodsModel
            {
                _id    = 1,
                Name   = "鲜享黑米",
                Price  = 10,
                Remark = "鲜享黑米,不好吃不要钱!",
                Images = new List <ImageBase> {
                    new ImageBase {
                        Path = "http://a0.att.hudong.com/78/52/01200000123847134434529793168.jpg"
                    }
                },
                Types = new List <ClassifyModel> {
                    new ClassifyModel {
                        Remark = "谷物类", Name = "谷物类", _id = 1
                    }
                }
            };
            var result = new WrapResult <object>
            {
                Data = data
            };

            return(await Task.FromResult(result));
        }
Example #2
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var result = await next();

            if (result.Canceled)
            {
                return;
            }
            if (result.Exception != default)
            {
                return;
            }
            if (result.Result == default)
            {
                return;
            }
            if (!(result.Result is ObjectResult objectResult))
            {
                return;
            }
            if (objectResult.Value is null)
            {
                return;
            }
            if (objectResult.Value is WrapResultBase wrapResultBase)
            {
                return;
            }
            var @object = new WrapResult <object>(objectResult.Value);

            objectResult.Value = @object;
        }
Example #3
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 <WrapResult <object> > Get(int page, int limit)
        {
            var data = new WrapResult <object>
            {
                Data = new
                {
                    Items = new List <ClassifyModel> {
                        new ClassifyModel {
                            Remark = "谷物类", Name = "谷物类", _id = 1
                        },
                        new ClassifyModel {
                            Remark = "糯米类", Name = "糯米类", _id = 2
                        },
                        new ClassifyModel {
                            Remark = "五谷杂粮类", Name = "五谷杂粮类", _id = 3
                        },
                        new ClassifyModel {
                            Remark = "东北大米", Name = "东北大米", _id = 4
                        }
                    },
                    Paginate = 0,
                    Number   = 10
                }
            };

            return(data);
        }
        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);
        }
Example #6
0
        public async Task <WrapResult <object> > Get()
        {
            var data   = cartService.GetCart(1);
            var result = new WrapResult <object> {
                Data = new { Items = data }
            };

            return(await Task.FromResult(result));
        }
        public async Task UnwrapKeyRequiresPrivateKey()
        {
            JsonWebKey jwk = CreateKey(KeyType.Rsa, keyOps: new[] { KeyOperation.WrapKey, KeyOperation.UnwrapKey });
            LocalCryptographyClient client = CreateClient <LocalCryptographyClient>(jwk);

            WrapResult wrapped = await client.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep, TestData);

            Assert.ThrowsAsync(new InstanceOfTypeConstraint(typeof(CryptographicException)), async() => await client.UnwrapKeyAsync(KeyWrapAlgorithm.RsaOaep, wrapped.EncryptedKey));
        }
Example #8
0
        public void WrapUnwrapSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            #region Snippet:KeysSample6KeyClient
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample6CreateKey
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey);
            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");
            #endregion

            #region Snippet:KeysSample6CryptographyClient
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample6GenerateKey
            byte[] keyData = AesManaged.Create().Key;
            Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}");
            #endregion

            #region Snippet:KeysSample6WrapKey
            WrapResult wrapResult = cryptoClient.WrapKey(KeyWrapAlgorithm.RsaOaep, keyData);
            Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}");
            #endregion

            #region Snippet:KeysSample6UnwrapKey
            UnwrapResult unwrapResult = cryptoClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey);
            Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}");
            #endregion

            #region Snippet:KeysSample6DeleteKey
            DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }
            #endregion

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
        public async Task WrapKeyUnwrapKeyRoundtrip([EnumValues(Exclude = new[] { nameof(KeyWrapAlgorithm.RsaOaep256) })] KeyWrapAlgorithm algorithm)
        {
            JsonWebKey jwk = KeyUtilities.CreateKey(algorithm, includePrivateParameters: true);
            LocalCryptographyClient client = CreateClient <LocalCryptographyClient>(jwk);

            WrapResult wrapped = await client.WrapKeyAsync(algorithm, TestKey);

            UnwrapResult unwrapped = await client.UnwrapKeyAsync(algorithm, wrapped.EncryptedKey);

            CollectionAssert.AreEqual(TestKey, unwrapped.Key);
        }
Example #10
0
        public override async Task SetupAsync()
        {
            await base.SetupAsync();

            // Generate new key with each iteration to avoid potential caching of results.
            _aes.GenerateKey();

            // CryptographyClient caches the public key so encrypting now removes the initial request from metrics.
            WrapResult result = await CryptographyClient.WrapKeyAsync(s_algorithm, _aes.Key);

            _encryptedKey = result.EncryptedKey;
        }
        public void WrapUnwrapSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a key client that will be used to create a key. Notice that the client is using default Azure
            // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // First create a RSA key which will be used to wrap and unwrap another key
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false)
            {
                KeySize = 2048,
            };

            KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey);

            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}");

            // Let's create the CryptographyClient which can perform cryptographic operations with the key we just created.
            // Again we are using the default Azure credential as above.
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());

            // Next we'll generate a symmetric key which we will wrap
            byte[] keyData = AesManaged.Create().Key;
            Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}");

            // Wrap the key using RSAOAEP with the created key.
            WrapResult wrapResult = cryptoClient.WrapKey(KeyWrapAlgorithm.RsaOaep, keyData);

            Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}");

            // Now unwrap the encrypted key. Note that the same algorithm must always be used for both wrap and unwrap
            UnwrapResult unwrapResult = cryptoClient.UnwrapKey(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey);

            Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}");

            // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
            DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName);

            // To ensure the key is deleted on server before we try to purge it.
            while (!operation.HasCompleted)
            {
                Thread.Sleep(2000);

                operation.UpdateStatus();
            }

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
Example #12
0
        public async Task <IActionResult> Wrap(EncryptDto toEncrypt)
        {
            byte[]      keyToWrap = Encoding.UTF8.GetBytes(toEncrypt.Payload);
            KeyVaultKey key       = await _keyClient.GetKeyAsync("test");

            CryptographyClient crypto = new CryptographyClient(key.Id, new DefaultAzureCredential());

            WrapResult result = await crypto.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, keyToWrap);

            KeyVaultSecret secret = await _secretClient.SetSecretAsync(new KeyVaultSecret(toEncrypt.Name, Convert.ToBase64String(result.EncryptedKey)));

            return(Ok(secret));
        }
Example #13
0
        public async Task <WrapResult <object> > GetList(QueryGoodPaged query)
        {
            var data = new List <GoodsModel>
            {
                new GoodsModel {
                    _id    = 1, Name = "鲜享黑米", Price = 10, Remark = "鲜享黑米,不好吃不要钱!",
                    Images = new List <ImageBase> {
                        new ImageBase {
                            Path = "http://a0.att.hudong.com/78/52/01200000123847134434529793168.jpg"
                        }
                    },
                    Types = new List <ClassifyModel> {
                        new ClassifyModel {
                            Remark = "谷物类", Name = "谷物类", _id = 1
                        }
                    }
                },
                new GoodsModel {
                    _id    = 2, Name = "新玉米五谷杂粮", Price = 50, Remark = "新玉米五谷杂粮,不好吃不要钱!",
                    Images = new List <ImageBase> {
                        new ImageBase {
                            Path = "http://localhost:5000/images/1.png"
                        }
                    }
                },
                new GoodsModel {
                    _id    = 3, Name = "自产红小豆", Price = (decimal)6.66, Remark = "自产红小豆,不好吃不要钱!",
                    Images = new List <ImageBase> {
                        new ImageBase {
                            Path = "http://localhost:5000/images/1.png"
                        }
                    }
                }
            };
            var result = new WrapResult <object>
            {
                Data = new
                {
                    Items    = data,
                    Paginate = new
                    {
                        Total   = 3,
                        Next    = 1,
                        PerPage = 1
                    }
                }
            };

            return(await Task.FromResult(result));
        }
Example #14
0
        public async Task WrapUnwrapAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

            // Instantiate a key client that will be used to create a key. Notice that the client is using default Azure
            // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID',
            // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials.
            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

            // First create a RSA key which will be used to wrap and unwrap another key
            string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}";
            var    rsaKey     = new RsaKeyCreateOptions(rsaKeyName, hsm: false, keySize: 2048);

            Key cloudRsaKey = await keyClient.CreateRsaKeyAsync(rsaKey);

            Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyMaterial.KeyType}");

            // Let's create the CryptographyClient which can perform cryptographic operations with the key we just created.
            // Again we are using the default Azure credential as above.
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());

            // Next we'll generate a symmetric key which we will wrap
            byte[] keyData = AesManaged.Create().Key;
            Debug.WriteLine($"Generated Key: {Convert.ToBase64String(keyData)}");

            // Wrap the key using RSAOAEP with the created key.
            WrapResult wrapResult = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.RSAOAEP, keyData);

            Debug.WriteLine($"Encrypted data using the algorithm {wrapResult.Algorithm}, with key {wrapResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(wrapResult.EncryptedKey)}");

            // Now unwrap the encrypted key. Note that the same algorithm must always be used for both wrap and unwrap
            UnwrapResult unwrapResult = await cryptoClient.UnwrapKeyAsync(KeyWrapAlgorithm.RSAOAEP, wrapResult.EncryptedKey);

            Debug.WriteLine($"Decrypted data using the algorithm {unwrapResult.Algorithm}, with key {unwrapResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(unwrapResult.Key)}");

            // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault.
            await keyClient.DeleteKeyAsync(rsaKeyName);

            // To ensure key is deleted on server side.
            Assert.IsTrue(await WaitForDeletedKeyAsync(keyClient, rsaKeyName));

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            await keyClient.PurgeDeletedKeyAsync(rsaKeyName);
        }
        public async Task <WrapResult <object> > Get(bool is_show = true)
        {
            var data = new List <BannerModel> {
                new BannerModel {
                    Title   = "图片1",
                    Remark  = "图片1-remark",
                    Sort    = 1,
                    Is_Show = true,
                    Images  = new List <ImageBase> {
                        new ImageBase {
                            Path = "http://localhost:5000/images/1.png"
                        }
                    }
                },
                new BannerModel {
                    Title   = "图片2",
                    Remark  = "图片2-remark",
                    Sort    = 2,
                    Is_Show = true,
                    Images  = new List <ImageBase> {
                        new ImageBase {
                            Path = "http://localhost:5000/images/1.png"
                        }
                    }
                },
                new BannerModel {
                    Title   = "图片3",
                    Remark  = "图片3-remark",
                    Sort    = 3,
                    Is_Show = true,
                    Images  = new List <ImageBase> {
                        new ImageBase {
                            Path = "http://localhost:5000/images/1.png"
                        }
                    }
                }
            };
            var result = new WrapResult <object> {
                Data = new { Items = data }
            };

            return(await Task.FromResult(result));
        }
            /// <summary>
            /// Simulates WrapKeyAsync method of KeyVault SDK.
            /// </summary>
            /// <param name="algorithm"> Encryption Algorithm </param>
            /// <param name="key"> Key to be wrapped </param>
            /// <param name="cancellationToken"> cancellation token </param>
            /// <returns></returns>
            public override Task <WrapResult> WrapKeyAsync(KeyWrapAlgorithm algorithm, byte[] key, CancellationToken cancellationToken = default)
            {
                if (key.IsNullOrEmpty())
                {
                    throw new ArgumentNullException("Key is Null.");
                }

                byte[] wrappedKey = this.Encrypt(key, this.secretkey, this.iv);

                // simulate a null wrapped key
                if (this.keyId.ToString().Contains(KeyVaultTestConstants.ValidateNullWrappedKey))
                {
                    wrappedKey = null;
                }

                string     keyid          = "12345678910";
                WrapResult mockWrapResult = CryptographyModelFactory.WrapResult(keyId: keyid, key: wrappedKey, algorithm: KeyVaultConstants.RsaOaep256);

                return(Task.FromResult(mockWrapResult));
            }
Example #17
0
        public async Task <WrapResult <object> > SignIn(RequestUserSginIn input)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(30)).ToUnixTimeSeconds()}"),
                new Claim(ClaimTypes.Name, input.UserName)
            };
            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecurityKey"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var token = new JwtSecurityToken(
                issuer: configuration["Jwt:Domain"],
                audience: configuration["Jwt:Domain"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(30),
                signingCredentials: creds);
            var data = new WrapResult <object> {
                Data = new { Token = new JwtSecurityTokenHandler().WriteToken(token) }
            };

            return(await Task.FromResult(data));
        }
Example #18
0
        public void OnException(ExceptionContext context)
        {
            if (context.ExceptionHandled)
            {
                return;
            }
            var statusCode = GetStatusCode(context);

            var @object = new WrapResult(new ErrorInfo
            {
                Message = context.Exception.Message,
            });
            var objectResult = new ObjectResult(@object)
            {
                StatusCode = statusCode
            };

            objectResult.ContentTypes?.Add(MediaTypeHeaderValue.Parse("application/json"));
            context.Result           = objectResult;
            context.ExceptionHandled = true;
            context.Exception        = null;
        }
        public async Task ShouldNotAttemptSubsequentDownload()
        {
            // Test for https://github.com/Azure/azure-sdk-for-net/issues/25254
            MockTransport transport = new((MockRequest request) =>
            {
                if (request.Method == RequestMethod.Get)
                {
                    // Any attempt to get the key must return 403 Forbidden.
                    return(new MockResponse((int)HttpStatusCode.Forbidden, nameof(HttpStatusCode.Forbidden)));
                }

                return(new MockResponse((int)HttpStatusCode.OK).WithContent(@"{""kid"":""https://mock.vault.azure.net/keys/mock-key/mock-version"",""value"":""dGVzdA""}"));
            });

            KeyResolver resolver = GetResolver(transport);

            // This would otherwise throw if "keys/get" permission was denied and #11574 was not resolved.
            CryptographyClient client = await resolver.ResolveAsync(new Uri("https://mock.vault.azure.net/keys/mock-key"));

            WrapResult result = await client.WrapKeyAsync(KeyWrapAlgorithm.A256KW, new byte[] { 0, 1, 2, 3 });

            Assert.AreEqual("https://mock.vault.azure.net/keys/mock-key/mock-version", result.KeyId);
        }
        public async Task ResolveSecretId()
        {
            SecretClient secretClient = GetSecretClient();

            // using Random to create a key so it is consistent for the recording. IRL this would be
            // a major security no no.  We would need to use AES.Create or RNGCryptoServiceProvider
            byte[] key = new byte[32];

            Recording.Random.NextBytes(key);

            Secret secret = new Secret(Recording.GenerateId(), Base64Url.Encode(key))
            {
                Properties =
                {
                    ContentType = "application/octet-stream"
                }
            };

            secret = await secretClient.SetSecretAsync(secret);

            CryptographyClient cryptoClient = await Resolver.ResolveAsync(secret.Id);

            cryptoClient = InstrumentClient(cryptoClient);

            Assert.IsNotNull(cryptoClient);

            byte[] toWrap = new byte[32];

            Recording.Random.NextBytes(toWrap);

            WrapResult wrapResult = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.A256KW, toWrap);

            UnwrapResult unwrapResult = await cryptoClient.UnwrapKeyAsync(KeyWrapAlgorithm.A256KW, wrapResult.EncryptedKey);

            CollectionAssert.AreEqual(toWrap, unwrapResult.Key);
        }
        public async Task ResolveKeyId()
        {
            string keyName = Recording.GenerateId();

            Key key = await Client.CreateKeyAsync(keyName, KeyType.Rsa);

            RegisterForCleanup(keyName);

            CryptographyClient cryptoClient = await Resolver.ResolveAsync(key.Id);

            cryptoClient = InstrumentClient(cryptoClient);

            Assert.IsNotNull(cryptoClient);

            byte[] toWrap = new byte[32];

            Recording.Random.NextBytes(toWrap);

            WrapResult wrapResult = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep, toWrap);

            UnwrapResult unwrapResult = await cryptoClient.UnwrapKeyAsync(KeyWrapAlgorithm.RsaOaep, wrapResult.EncryptedKey);

            CollectionAssert.AreEqual(toWrap, unwrapResult.Key);
        }
Example #22
0
 static WrapResult()
 {
     instance = new WrapResult();
 }
        private async Task MigrationGuide()
        {
            #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Create
            KeyClient client = new KeyClient(
                new Uri("https://myvault.vault.azure.net"),
                new DefaultAzureCredential());

            CryptographyClient cryptoClient = new CryptographyClient(
                new Uri("https://myvault.vault.azure.net"),
                new DefaultAzureCredential());
            #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Create

            #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions
            using (HttpClient httpClient = new HttpClient())
            {
                KeyClientOptions options = new KeyClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                };

#if SNIPPET
                KeyClient client = new KeyClient(
#else
                client = new KeyClient(
#endif
                    new Uri("https://myvault.vault.azure.net"),
                    new DefaultAzureCredential(),
                    options);

                CryptographyClientOptions cryptoOptions = new CryptographyClientOptions
                {
                    Transport = new HttpClientTransport(httpClient)
                };

#if SNIPPET
                CryptographyClient cryptoClient = new CryptographyClient(
#else
                cryptoClient = new CryptographyClient(
#endif
                    new Uri("https://myvault.vault.azure.net"),
                    new DefaultAzureCredential(),
                    cryptoOptions);
            }
            #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateWithOptions

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateKeys
                // Create RSA key.
                CreateRsaKeyOptions createRsaOptions = new CreateRsaKeyOptions("rsa-key-name")
                {
                    KeySize = 4096
                };

                KeyVaultKey rsaKey = await client.CreateRsaKeyAsync(createRsaOptions);

                // Create Elliptic-Curve key.
                CreateEcKeyOptions createEcOptions = new CreateEcKeyOptions("ec-key-name")
                {
                    CurveName = KeyCurveName.P256
                };

                KeyVaultKey ecKey = await client.CreateEcKeyAsync(createEcOptions);

                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_CreateKeys
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
                // List all keys asynchronously.
                await foreach (KeyProperties item in client.GetPropertiesOfKeysAsync())
                {
                    KeyVaultKey key = await client.GetKeyAsync(item.Name);
                }

                // List all keys synchronously.
                foreach (KeyProperties item in client.GetPropertiesOfKeys())
                {
                    KeyVaultKey key = client.GetKey(item.Name);
                }
                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_ListKeys
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
                // Delete the key.
                DeleteKeyOperation deleteOperation = await client.StartDeleteKeyAsync("key-name");

                // Purge or recover the deleted key if soft delete is enabled.
                if (deleteOperation.Value.RecoveryId != null)
                {
                    // Deleting a key does not happen immediately. Wait for the key to be deleted.
                    DeletedKey deletedKey = await deleteOperation.WaitForCompletionAsync();

                    // Purge the deleted key.
                    await client.PurgeDeletedKeyAsync(deletedKey.Name);

                    // You can also recover the deleted key using StartRecoverDeletedKeyAsync,
                    // which returns RecoverDeletedKeyOperation you can await like DeleteKeyOperation above.
                }
                #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_DeleteKey
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
                // Encrypt a message. The plaintext must be small enough for the chosen algorithm.
                byte[] plaintext        = Encoding.UTF8.GetBytes("Small message to encrypt");
                EncryptResult encrypted = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep256, plaintext);

                // Decrypt the message.
                DecryptResult decrypted = await cryptoClient.DecryptAsync(encrypted.Algorithm, encrypted.Ciphertext);

                string message = Encoding.UTF8.GetString(decrypted.Plaintext);
                                                         #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Encrypt
            }

            {
                #region Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Wrap
                using (Aes aes = Aes.Create())
                {
                    // Use a symmetric key to encrypt large amounts of data, possibly streamed...

                    // Now wrap the key and store the encrypted key and plaintext IV to later decrypt the key to decrypt the data.
                    WrapResult wrapped = await cryptoClient.WrapKeyAsync(KeyWrapAlgorithm.RsaOaep256, aes.Key);

                    // Read the IV and the encrypted key from the payload, then unwrap the key.
                    UnwrapResult unwrapped = await cryptoClient.UnwrapKeyAsync(wrapped.Algorithm, wrapped.EncryptedKey);

                    aes.Key = unwrapped.Key;

                    // Decrypt the payload with the symmetric key.
                }
                       #endregion Snippet:Azure_Security_KeyVault_Keys_Snippets_MigrationGuide_Wrap
            }
        }
Example #24
0
        /// <summary>Attempt to wrap text into the given available width, while trying to keep all lines more-or-less even</summary>
        public static void WrapOptimise(string input, StringBuilder output, int availableWidth, SpriteFont font, StringBuilder workingSpace)
        {
            float maxBlockWidth = (float)availableWidth;

            WrapResult initialResult = WrapInternal(input, output, maxBlockWidth, font, workingSpace);

            if (initialResult.lineCount <= 1)
            {
                return; // We can never waste space with a single line
            }
            // At this point, we have some excess space available at the end of the line,
            // which we can use up by pushing some words down by iterativly reducing the width.
            //
            // There is maybe some concerns about opening up a larger gap on a prior line,
            // but I'm (-AR) not sure that this is a problem in practice. Won't worry about it for now.
            // (Practical results indicate the main problem is not enough iterations.)


            // Determine a threshold to stop doing trials:
            workingSpace.Clear();
            workingSpace.EnsureCapacity(3);
            workingSpace.Append(' ');
            workingSpace.Append(' ');
            float zeroSpace = font.MeasureString(workingSpace).X;

            workingSpace.Append(' '); // <- NOTE: Width of a space used as exit threshold
            float exitThreshold = (font.MeasureString(workingSpace).X - zeroSpace) * 0.5f;

            exitThreshold = 1;

            float      minBlockWidth  = 0;
            bool       lastResultGood = true;
            WrapResult latestResult   = initialResult;

            // NOTE: Keep iteration count capped to keep wrap algorithm O(n)
            int i = 6; // <- Hand-tuned value

            while (true)
            {
                if (i == 0)
                {
                    break;
                }
                if (maxBlockWidth - minBlockWidth < exitThreshold) // <- TODO: Should probably switch to linear search at this point? (use Floor(max) or Ceiling(min) and go from there with 1px resolution?)
                {
                    break;
                }

                // Determine a new width to trial:
                float trialWidth;
                if (lastResultGood)
                {
                    float lastTrailingSpace = (maxBlockWidth - latestResult.finalLineWidth);
                    if (lastTrailingSpace <= exitThreshold)
                    {
                        break;
                    }

                    trialWidth = maxBlockWidth - (lastTrailingSpace / (float)(initialResult.lineCount)); // <- TODO: More carefully check this improves results or iteration count.

                    if (trialWidth <= minBlockWidth + exitThreshold)
                    {
                        trialWidth = (minBlockWidth + maxBlockWidth) * 0.5f;
                    }
                }
                else
                {
                    trialWidth = (minBlockWidth + maxBlockWidth) * 0.5f; // <- binary search
                }
                latestResult = WrapInternal(input, output, trialWidth, font, workingSpace);


                lastResultGood = (latestResult.lineCount == initialResult.lineCount);
                if (lastResultGood)
                {
                    maxBlockWidth = trialWidth; // <- We fit in this much, maybe we can get smaller
                }
                else
                {
                    minBlockWidth = trialWidth; // <- We didn't fit, so we must be wider
                }
                i--;
            }

            // Ensure we exit with output in a known-good state:
            if (!lastResultGood)
            {
                WrapInternal(input, output, maxBlockWidth, font, workingSpace);
            }
        }
 public PSKeyOperationResult(WrapResult wrapResult)
 {
     this.KeyId     = wrapResult.KeyId;
     this.Result    = System.Convert.ToBase64String(wrapResult.EncryptedKey);
     this.Algorithm = wrapResult.Algorithm.ToString();
 }
Example #26
0
 static WrapResult()
 {
     instance = new WrapResult();
 }