Example #1
0
        public void InitializesIv(EncryptionAlgorithm algorithm)
        {
            // Use a 256-bit key which will be truncated based on the selected algorithm.
            byte[] k = new byte[] { 0xe2, 0x7e, 0xd0, 0xc8, 0x45, 0x12, 0xbb, 0xd5, 0x5b, 0x6a, 0xf4, 0x34, 0xd2, 0x37, 0xc1, 0x1f, 0xeb, 0xa3, 0x11, 0x87, 0x0f, 0x80, 0xf2, 0xc2, 0xe3, 0x36, 0x42, 0x60, 0xf3, 0x1c, 0x82, 0xc8 };

            JsonWebKey key = new JsonWebKey(new[] { KeyOperation.Encrypt, KeyOperation.Decrypt })
            {
                K = k,
            };

            AesCryptographyProvider provider = new AesCryptographyProvider(key, null);

            byte[] plaintext = Encoding.UTF8.GetBytes("plaintext");

            EncryptOptions encryptOptions = new EncryptOptions(algorithm, plaintext, null, null);
            EncryptResult  encrypted      = provider.Encrypt(encryptOptions, default);

            Assert.IsNotNull(encryptOptions.Iv);
            CollectionAssert.AreEqual(encryptOptions.Iv, encrypted.Iv);

            DecryptOptions decryptOptions = new DecryptOptions(algorithm, encrypted.Ciphertext, encrypted.Iv);
            DecryptResult  decrypted      = provider.Decrypt(decryptOptions, default);

            Assert.IsNotNull(decrypted);

            // AES-CBC will be zero-padded.
            StringAssert.StartsWith("plaintext", Encoding.UTF8.GetString(decrypted.Plaintext));
        }
Example #2
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"));
        }
Example #3
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();
        }
Example #4
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);
        }
		/// <summary>
		/// Sets the values used in <see cref="GetPasswords"/>
		/// </summary>
		public MockContentEncryptionUi(string openPassword, string modifyPassword, DecryptResult result, DecryptionErrorAction incorrectPasswordAction)
		{
			m_OpenPassword = openPassword;
			m_ModifyPassword = modifyPassword;
			m_Result = result;
			m_IncorrectPasswordAction = incorrectPasswordAction;
		}
        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 async Task <string> DecryptStringAsync(CryptographyClient cryptoClient, string input)
        {
            byte[] inputAsByteArray = Convert.FromBase64String(input);

            DecryptResult decryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, inputAsByteArray).ConfigureAwait(false);

            return(Encoding.Default.GetString(decryptResult.Plaintext));
        }
Example #8
0
        public override async Task RunAsync(CancellationToken cancellationToken)
        {
            DecryptResult result = await CryptographyClient.DecryptAsync(s_algorithm, _ciphertext);

            byte[] plaintext = result.Plaintext;

#if DEBUG
            Assert.AreEqual(_plaintext, plaintext);
#endif
        }
Example #9
0
        public override void Run(CancellationToken cancellationToken)
        {
            DecryptResult result = CryptographyClient.Decrypt(s_algorithm, _ciphertext);

            byte[] plaintext = result.Plaintext;

#if DEBUG
            Assert.AreEqual(_plaintext, plaintext);
#endif
        }
Example #10
0
        public void EncryptDecryptSync()
        {
            // 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());

            // Let's create a RSA key which will be used to encrypt and decrypt
            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 encrypt some arbitrary plain text with the key using the CryptographyClient. Note that RSA encryption
            // algorithms have no chaining so they can only encrypt a single block of plaintext securely. For RSAOAEP this can be
            // calculated as (keysize / 8) - 42, or in our case (2048 / 8) - 42 = 214 bytes.
            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // First encrypt the data using RSAOAEP with the created key.
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);

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

            // Now decrypt the encrypted data. Note that the same algorithm must always be used for both encrypt and decrypt
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

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

            // 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);
        }
        public async Task <IActionResult> Decrypt(EncryptDto toDecrypt)
        {
            byte[]      toDecryptInBytes = Convert.FromBase64String(toDecrypt.Payload);
            KeyVaultKey key = await _keyClient.GetKeyAsync("test");

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

            DecryptResult result = await crypto.DecryptAsync(EncryptionAlgorithm.RsaOaep256, toDecryptInBytes);

            return(new OkObjectResult(Encoding.UTF8.GetString(result.Plaintext)));
        }
        public void EncryptDecrypt()
        {
            #region Snippet:EncryptDecrypt
            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // encrypt the data using the algorithm RSAOAEP
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);

            // decrypt the encrypted data.
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);
            #endregion
        }
        public void OctEncryptDecryptSync()
        {
            TestEnvironment.AssertManagedHsm();

            string managedHsmUrl = TestEnvironment.ManagedHsmUrl;

            #region Snippet:OctKeysSample4CreateKey
            var managedHsmClient = new KeyClient(new Uri(managedHsmUrl), new DefaultAzureCredential());

            var octKeyOptions = new CreateOctKeyOptions($"CloudOctKey-{Guid.NewGuid()}")
            {
                KeySize = 256,
            };

            KeyVaultKey cloudOctKey = managedHsmClient.CreateOctKey(octKeyOptions);
            #endregion

            #region Snippet:OctKeySample4Encrypt
            var cryptoClient = new CryptographyClient(cloudOctKey.Id, new DefaultAzureCredential());

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");
            byte[] aad       = Encoding.UTF8.GetBytes("additional authenticated data");

            EncryptParameters encryptParams = EncryptParameters.A256GcmParameters(plaintext, aad);
            EncryptResult     encryptResult = cryptoClient.Encrypt(encryptParams);
            #endregion

            #region Snippet:OctKeySample4Decrypt
            DecryptParameters decryptParams = DecryptParameters.A256GcmParameters(
                encryptResult.Ciphertext,
                encryptResult.Iv,
                encryptResult.AuthenticationTag,
                encryptResult.AdditionalAuthenticatedData);

            DecryptResult decryptResult = cryptoClient.Decrypt(decryptParams);
            #endregion

            Assert.AreEqual(plaintext, decryptResult.Plaintext);

            // Delete and purge the key.
            DeleteKeyOperation operation = managedHsmClient.StartDeleteKey(octKeyOptions.Name);

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

                operation.UpdateStatus();
            }

            managedHsmClient.PurgeDeletedKey(operation.Value.Name);
        }
        static void Main(string[] args)
        {
            var credential = new InteractiveBrowserCredential();

            var kvUri = "[key vault uri]";

            var           client              = new KeyClient(new Uri(kvUri), credential);
            var           key                 = client.GetKey("[kek key name]");
            var           cryptoClient        = new CryptographyClient(key.Value.Id, credential);
            var           secretClient        = new SecretClient(new Uri(kvUri), credential);
            var           encryptedDEK        = secretClient.GetSecret("[dek key name]");
            DecryptResult decryptDek          = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, Convert.FromBase64String(encryptedDEK.Value.Value));
            var           keynew              = decryptDek.Plaintext[0..16];
        public async Task EncryptDecryptRoundtrip([EnumValues(nameof(EncryptionAlgorithm.Rsa15), nameof(EncryptionAlgorithm.RsaOaep))] EncryptionAlgorithm algorithm)
        {
            JsonWebKey jwk = CreateKey(KeyType.Rsa, includePrivateParameters: true);
            LocalCryptographyClient client = CreateClient <LocalCryptographyClient>(jwk);

            EncryptResult encrypted = await client.EncryptAsync(algorithm, TestData);

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

            string actual = Encoding.UTF8.GetString(decrypted.Plaintext);

            Assert.AreEqual("test", actual);
        }
Example #16
0
        public string Decode(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentException("Value cannot be null or empty.", nameof(value));
            }

            byte[]        encryptedByteArray = Convert.FromBase64String(value);
            DecryptResult decryptResult      =
                _cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptedByteArray);

            return(Encoding.Default.GetString(decryptResult.Plaintext));
        }
Example #17
0
        public void EncryptDecryptSync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL");

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

            #region Snippet:KeysSample4CreateKey
            // Let's create a RSA key which will be used to encrypt and decrypt
            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:KeysSample4CryptographyClient
            var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential());
            #endregion

            #region Snippet:KeysSample4EncryptKey
            byte[]        plaintext     = Encoding.UTF8.GetBytes("A single block of plaintext");
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);
            Debug.WriteLine($"Encrypted data using the algorithm {encryptResult.Algorithm}, with key {encryptResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(encryptResult.Ciphertext)}");
            #endregion

            #region Snippet:KeysSample4DecryptKey
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);
            Debug.WriteLine($"Decrypted data using the algorithm {decryptResult.Algorithm}, with key {decryptResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(decryptResult.Plaintext)}");
            #endregion

            #region Snippet:KeysSample4DeleteKey
            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);
        }
Example #18
0
        public async Task EncryptDecryptFromKeyClient()
        {
            KeyVaultKey key = await CreateTestKey(EncryptionAlgorithm.RsaOaep);

            RegisterForCleanup(key.Name);

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // Make sure the same (instrumented) pipeline is used from the KeyClient.
            CryptographyClient cryptoClient  = Client.GetCryptographyClient(key.Name, key.Properties.Version);
            EncryptResult      encryptResult = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, plaintext);

            DecryptResult decryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

            Assert.AreEqual(plaintext, decryptResult.Plaintext);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var    keyclient = new KeyClient(new Uri("https://markappincc.vault.azure.net/"), new DefaultAzureCredential());
            string payload   = req.Query["payload"];

            byte[]      toDecryptInBytes = Convert.FromBase64String(payload);
            KeyVaultKey key = await keyclient.GetKeyAsync("marekmaencrypt");

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

            DecryptResult result = await crypto.DecryptAsync(EncryptionAlgorithm.RsaOaep256, toDecryptInBytes);

            return(new OkObjectResult(Encoding.UTF8.GetString(result.Plaintext)));
        }
Example #20
0
    public async Task <string> DecryptAsync(
        string cipherValue,
        VariableEncryptionInfo encryptionInfo,
        CancellationToken cancellationToken)
    {
        EncryptionAlgorithm algorithm = new EncryptionAlgorithm(encryptionInfo.Algorithm);

        CryptographyClient cryptoClient = _clientFactory
                                          .CreateDecryptionClient(encryptionInfo.Key);

        DecryptResult result = await cryptoClient.DecryptAsync(
            algorithm,
            Convert.FromBase64String(cipherValue),
            cancellationToken);

        return(Encoding.UTF8.GetString(result.Plaintext));
    }
        public void EncryptDecrypt()
        {
            #region Snippet:EncryptDecrypt
#if SNIPPET
            // 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);
#endif

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

            // encrypt the data using the algorithm RSAOAEP
            EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext);

            // decrypt the encrypted data.
            DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);
            #endregion
        }
Example #22
0
        public async Task OctEncryptDecryptAsync()
        {
            TestEnvironment.AssertManagedHsm();

            string managedHsmUrl = TestEnvironment.ManagedHsmUrl;

            var managedHsmClient = new KeyClient(new Uri(managedHsmUrl), new DefaultAzureCredential());

            var octKeyOptions = new CreateOctKeyOptions($"CloudOctKey-{Guid.NewGuid()}")
            {
                KeySize = 256,
            };

            KeyVaultKey cloudOctKey = await managedHsmClient.CreateOctKeyAsync(octKeyOptions);

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

            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");
            byte[] aad       = Encoding.UTF8.GetBytes("additional authenticated data");

            EncryptParameters encryptParams = EncryptParameters.A256GcmParameters(plaintext, aad);
            EncryptResult     encryptResult = await cryptoClient.EncryptAsync(encryptParams);

            DecryptParameters decryptParams = DecryptParameters.A256GcmParameters(
                encryptResult.Ciphertext,
                encryptResult.Iv,
                encryptResult.AuthenticationTag,
                encryptResult.AdditionalAuthenticatedData);

            DecryptResult decryptResult = await cryptoClient.DecryptAsync(decryptParams);

            Assert.AreEqual(plaintext, decryptResult.Plaintext);

            // Delete and purge the key.
            DeleteKeyOperation operation = await managedHsmClient.StartDeleteKeyAsync(octKeyOptions.Name);

            // You only need to wait for completion if you want to purge or recover the key.
            await operation.WaitForCompletionAsync();

            managedHsmClient.PurgeDeletedKey(operation.Value.Name);
        }
 public PSKeyOperationResult(DecryptResult decryptResult)
 {
     this.KeyId     = decryptResult.KeyId;
     this.Result    = System.Text.Encoding.Default.GetString(decryptResult.Plaintext);
     this.Algorithm = decryptResult.Algorithm.ToString();
 }
		protected void okButton_Click(object sender, System.EventArgs e)
		{
			m_Result = DecryptResult.Ok;
			Close();
		}
        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
            }
        }
        public async Task SerializeJsonWebKeyAsync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

            var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential());

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

            KeyVaultKey cloudRsaKey = await keyClient.CreateRsaKeyAsync(rsaKey);

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

            string dir = Path.Combine(TestContext.CurrentContext.WorkDirectory, "samples", nameof(Sample7_SerializeJsonWebKey));

            Directory.CreateDirectory(dir);

            string path = Path.Combine(dir, $"{nameof(SerializeJsonWebKeyAsync)}.json");

            // Use `using` expression for clean sample, but scope it to close and dispose immediately.
            {
                using FileStream file = File.Create(path);
                await JsonSerializer.SerializeAsync(file, cloudRsaKey.Key);

                Debug.WriteLine($"Saved JWK to {path}");
            }

            // Use `using` expression for clean sample, but scope it to close and dispose immediately.
            JsonWebKey jwk = null;
            {
                using FileStream file = File.Open(path, FileMode.Open);
                jwk = await JsonSerializer.DeserializeAsync <JsonWebKey>(file);

                Debug.WriteLine($"Read JWK from {path} with ID {jwk.Id}");
            }

            string content = "plaintext";

            var encryptClient = new CryptographyClient(jwk);

            byte[]        plaintext = Encoding.UTF8.GetBytes(content);
            EncryptResult encrypted = await encryptClient.EncryptAsync(EncryptParameters.RsaOaepParameters(plaintext));

            Debug.WriteLine($"Encrypted: {Encoding.UTF8.GetString(plaintext)}");

            byte[] ciphertext = encrypted.Ciphertext;

            CryptographyClient decryptClient = keyClient.GetCryptographyClient(cloudRsaKey.Name, cloudRsaKey.Properties.Version);
            DecryptResult      decrypted     = await decryptClient.DecryptAsync(DecryptParameters.RsaOaepParameters(ciphertext));

            Debug.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decrypted.Plaintext)}");

            DeleteKeyOperation operation = await keyClient.StartDeleteKeyAsync(rsaKeyName);

            // You only need to wait for completion if you want to purge or recover the key.
            await operation.WaitForCompletionAsync();

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
		public MockContentEncryptionUi(Dictionary<string, PasswordInfo> passwordInfo, DecryptResult result, DecryptionErrorAction incorrectPasswordAction)
		{
			m_passwordInfo = passwordInfo;
			m_Result = result;
			m_IncorrectPasswordAction = incorrectPasswordAction;
		}
		protected void cancelButton_Click(object sender, System.EventArgs e)
		{
			m_Result = DecryptResult.Cancel;
			Close();
		}
Example #29
0
        /// <summary>
        ///     Выполнить операцию
        /// </summary>
        /// <param name="settingsJSON"></param>
        /// <param name="signedFileInfosJSON"></param>
        /// <param name="type"></param>
        /// <param name="savePIN"></param>
        /// <returns></returns>
        public ActionResult MakeOperation(string settingsJSON, string signedFileInfosJSON, OperationType type,
                                          bool?savePIN, bool?needToPIN)
        {
            //_logger.Info("MakeOperation PID:" + System.Diagnostics.Process.GetCurrentProcess().Id);
            //_logger.Info("MakeOperation TID:" + System.Threading.Thread.CurrentThread.ManagedThreadId);

            Guid token = CheckSessionAuthState(CurrentUser, _authService);

            if (token == Guid.Empty)
            {
                return
                    (Json(
                         new { OperationResult = new Result {
                                   Exception = new MasterException(401, "Токен истек", null)
                               } },
                         JsonRequestBehavior.AllowGet));
            }
            Settings              settings;
            Exception             globalException = null;
            List <SignedFileInfo> signedFileInfos;

            try
            {
                var serializer = new DataContractJsonSerializer(typeof(List <SignedFileInfo>));
                var stream     = new MemoryStream(Encoding.UTF8.GetBytes(signedFileInfosJSON));
                signedFileInfos = (List <SignedFileInfo>)serializer.ReadObject(stream);
                stream.Close();
            }
            catch (Exception exception)
            {
                return
                    (Json(
                         new
                {
                    OperationResult =
                        new Result
                    {
                        Exception =
                            new MasterException(500, "Не удалось сериализовать список файлов от клиента",
                                                null)
                    }
                }, JsonRequestBehavior.AllowGet));
            }

            try
            {
                var serializer = new DataContractJsonSerializer(typeof(Settings));
                var stream     = new MemoryStream(Encoding.UTF8.GetBytes(settingsJSON));
                settings = (Settings)serializer.ReadObject(stream);
                stream.Close();
            }
            catch (Exception exception)
            {
                return
                    (Json(
                         new
                {
                    OperationResult =
                        new Result
                    {
                        Exception =
                            new MasterException(500, "Не удалось сериализовать настройки от клиента", null)
                    }
                }, JsonRequestBehavior.AllowGet));
            }
            var davListCryptoOperationResponse = new DAVListCryptoOperationResponse();

            var pinsettings = new PINSettings
            {
                NeedToPIN = (needToPIN != null && (bool)needToPIN),
                PIN       = settings._SignatureSettings.KeysetPassword,
                SavePIN   = (savePIN != null && (bool)savePIN)
            };

            if (!string.IsNullOrEmpty(settings._SignatureSettings.KeysetPassword))
            {
                pinsettings.PIN = settings._SignatureSettings.KeysetPassword;
            }
            if (!string.IsNullOrEmpty(settings._DecryptionSettings.KeysetPassword))
            {
                pinsettings.PIN = settings._DecryptionSettings.KeysetPassword;
            }

            var doubleOperationResult = new DoubleOperationResult();

            //список файлов с ошибками
            var errorDataOperationResults = new List <DataOperationResult>();

            #region Единичные операции

            if (type != OperationType.DecryptSignverify && type != OperationType.SignEncrypt)
            {
                var result = new Result();

                #region Подпись

                if (type == OperationType.Sign)
                {
                    settings._SignatureSettings.KeysetPassword = string.Empty;
                    List <string> files = signedFileInfos.Select(signedFileInfo => signedFileInfo.FileUri).ToList();
                    try
                    {
                        davListCryptoOperationResponse = _cryptxService.DAVListSignOperation(files, settings,
                                                                                             pinsettings, token);
                        if (davListCryptoOperationResponse.Exception != null)
                        {
                            if (davListCryptoOperationResponse.Exception.Message.Contains("0x8010006b"))
                            {
                                result.Exception = new MasterException(Int32.Parse("8010006b", NumberStyles.HexNumber),
                                                                       davListCryptoOperationResponse.Exception.Message,
                                                                       davListCryptoOperationResponse.Exception);
                            }
                            else
                            {
                                result.Exception = new MasterException(
                                    davListCryptoOperationResponse.Exception.HResult,
                                    davListCryptoOperationResponse.Exception.Message,
                                    davListCryptoOperationResponse.Exception);
                            }
                        }
                        else
                        {
                            foreach (
                                DataOperationResult dataOperationResult in
                                davListCryptoOperationResponse.OperationResults)
                            {
                                var signResult = new SignResult();

                                signResult.UnsignedFile = dataOperationResult.SourceFile;
                                if (dataOperationResult.Exception != null)
                                {
                                    Exception curException = dataOperationResult.Exception;
                                    signResult.Exception = new MasterException(curException.HResult,
                                                                               curException.Message, curException);
                                }
                                else
                                {
                                    signResult.SignedFile = dataOperationResult.OperatedFile;
                                }

                                result.OperationResults.Add(signResult);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Exception = new MasterException(ex.HResult, "", ex);
                        globalException  = ex;
                    }
                }

                #endregion

                #region Шифровка

                if (type == OperationType.Encrypt)
                {
                    try
                    {
                        List <string> files = signedFileInfos.Select(signedFileInfo => signedFileInfo.FileUri).ToList();
                        davListCryptoOperationResponse = _cryptxService.DAVListEncryptOperation(files, settings, token);
                        if (davListCryptoOperationResponse.Exception != null)
                        {
                            result.Exception = new MasterException(davListCryptoOperationResponse.Exception.HResult,
                                                                   davListCryptoOperationResponse.Exception.Message,
                                                                   davListCryptoOperationResponse.Exception);
                            globalException = davListCryptoOperationResponse.Exception;
                        }
                        else
                        {
                            foreach (
                                DataOperationResult dataOperationResult in
                                davListCryptoOperationResponse.OperationResults)
                            {
                                var encryptResult = new EncryptResult();

                                encryptResult.UnencryptedFile = dataOperationResult.SourceFile;
                                if (dataOperationResult.Exception != null)
                                {
                                    Exception curException = dataOperationResult.Exception;

                                    encryptResult.Exception = new MasterException(curException.HResult,
                                                                                  curException.Message, curException);
                                }
                                else
                                {
                                    encryptResult.EncryptedFile = dataOperationResult.OperatedFile;
                                }

                                result.OperationResults.Add(encryptResult);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Exception = new MasterException(ex.HResult, ex.Message, ex);
                        globalException  = ex;
                    }
                }

                #endregion

                #region Проверка подписи

                if (type == OperationType.SignVerify)
                {
                    var response = new List <SignVerifyResponse>();
                    try
                    {
                        response = _cryptxService.DAVListSignVerify(signedFileInfos, settings, true, token);


                        foreach (SignVerifyResponse signVerifyResponse in response)
                        {
                            var signVerifyResult = new SignVerifyResult();
                            signVerifyResult.CertificateStatuses = signVerifyResponse.CertificateStatuses;
                            signVerifyResult.MainStatus          = signVerifyResponse.MainStatus;
                            signVerifyResult.Detached            = signVerifyResponse.Detached;
                            signVerifyResult.SignedFile          = signVerifyResponse.SourceFile;
                            signVerifyResult.DataFile            = signVerifyResponse.DataSourceFile;
                            result.OperationResults.Add(signVerifyResult);
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Exception = new MasterException(ex.HResult, ex.Message, ex);
                        globalException  = ex;
                    }
                    //return Json(new { response, errorDataOperationResults, operationError = globalException }, JsonRequestBehavior.AllowGet);
                }

                #endregion

                #region  асшифровать

                if (type == OperationType.Decrypt)
                {
                    try
                    {
                        settings._DecryptionSettings.KeysetPassword = string.Empty;
                        List <string> files = signedFileInfos.Select(signedFileInfo => signedFileInfo.FileUri).ToList();
                        davListCryptoOperationResponse = _cryptxService.DAVListDecryptOperation(files, settings,
                                                                                                pinsettings, token);
                        if (davListCryptoOperationResponse.Exception != null)
                        {
                            Exception curException = davListCryptoOperationResponse.Exception;


                            result.Exception = new MasterException(curException.HResult, curException.Message,
                                                                   curException);
                            globalException = davListCryptoOperationResponse.Exception;
                        }

                        else
                        {
                            foreach (
                                DataOperationResult dataOperationResult in
                                davListCryptoOperationResponse.OperationResults)
                            {
                                var decryptResult = new DecryptResult();

                                if (dataOperationResult.Exception != null)
                                {
                                    Exception curException = dataOperationResult.Exception;
                                    decryptResult.Exception = new MasterException(curException.HResult,
                                                                                  curException.Message, curException);
                                }
                                decryptResult.DecryptedFile = dataOperationResult.SourceFile;
                                decryptResult.EncryptedFile = dataOperationResult.OperatedFile;
                                result.OperationResults.Add(decryptResult);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        result.Exception = new MasterException(ex.HResult, ex.Message, ex);
                        globalException  = ex;
                    }
                }

                #endregion


                return(Json(new { OperationResult = result }, JsonRequestBehavior.AllowGet));
            }
            #endregion

            #region Двойные операции

            #region Подпись-шифрование

            if (type == OperationType.SignEncrypt)
            {
                try
                {
                    List <string> files = signedFileInfos.Select(signedFileInfo => signedFileInfo.FileUri).ToList();
                    //подпись
                    davListCryptoOperationResponse = _cryptxService.DAVListSignOperation(files, settings, pinsettings,
                                                                                         token);
                    if (davListCryptoOperationResponse.Exception != null)
                    {
                        doubleOperationResult.Exception =
                            new MasterException(davListCryptoOperationResponse.Exception.HResult,
                                                davListCryptoOperationResponse.Exception.Message,
                                                davListCryptoOperationResponse.Exception);
                        return(Json(new { OperationResult = doubleOperationResult }, JsonRequestBehavior.AllowGet));
                    }
                    var toEncrypt = new List <string>();
                    foreach (DataOperationResult dataOperationResult in davListCryptoOperationResponse.OperationResults)
                    {
                        var signResult = new SignResult();

                        signResult.UnsignedFile = dataOperationResult.SourceFile;
                        //firsOperationResult.Add(signResult);

                        if (dataOperationResult.Exception != null)
                        {
                            Exception curException = dataOperationResult.Exception;
                            signResult.Exception = new MasterException(curException.HResult, curException.Message,
                                                                       curException);
                            errorDataOperationResults.Add(dataOperationResult);
                        }
                        else
                        {
                            signResult.SignedFile = dataOperationResult.OperatedFile;

                            toEncrypt.Add(dataOperationResult.OperatedFile);
                        }

                        doubleOperationResult.OperationResults.Add(new DoubleResult
                        {
                            FirsOperationResult = signResult
                        });
                    }

                    List <string> filesToEncryption =
                        doubleOperationResult.OperationResults.Where(x => x.FirsOperationResult.Exception == null)
                        .Select(x => ((SignResult)x.FirsOperationResult).SignedFile)
                        .ToList();
                    //шифрование
                    davListCryptoOperationResponse = _cryptxService.DAVListEncryptOperation(toEncrypt, settings, token);


                    //цикл в цикле для сопастовления данных первой операции со второй
                    foreach (DataOperationResult dataOperationResult in davListCryptoOperationResponse.OperationResults)
                    {
                        foreach (DoubleResult doubleResult in doubleOperationResult.OperationResults)
                        {
                            if (((SignResult)doubleResult.FirsOperationResult).SignedFile ==
                                dataOperationResult.SourceFile)
                            {
                                var encryptResult = new EncryptResult();
                                encryptResult.UnencryptedFile = dataOperationResult.SourceFile;
                                if (dataOperationResult.Exception != null)
                                {
                                    encryptResult.Exception = new MasterException(
                                        dataOperationResult.Exception.HResult, dataOperationResult.Exception.Message,
                                        dataOperationResult.Exception);
                                }
                                else
                                {
                                    encryptResult.EncryptedFile = dataOperationResult.OperatedFile;
                                }
                                doubleResult.SecondOperationResult = encryptResult;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    doubleOperationResult.Exception = new MasterException(ex.HResult, ex.Message, ex);
                }
            }

            #endregion

            #region  асшифровать - проверить подпись

            if (type == OperationType.DecryptSignverify)
            {
                var response = new List <SignVerifyResponse>();
                try
                {
                    settings._DecryptionSettings.KeysetPassword = string.Empty;
                    List <string> files = signedFileInfos.Select(signedFileInfo => signedFileInfo.FileUri).ToList();
                    davListCryptoOperationResponse = _cryptxService.DAVListDecryptOperation(files, settings, pinsettings,
                                                                                            token);
                    if (davListCryptoOperationResponse.Exception != null)
                    {
                        doubleOperationResult.Exception =
                            new MasterException(davListCryptoOperationResponse.Exception.HResult,
                                                davListCryptoOperationResponse.Exception.Message,
                                                davListCryptoOperationResponse.Exception);
                        return(Json(new { OperationResult = doubleOperationResult }, JsonRequestBehavior.AllowGet));
                    }
                    var toSignVerify = new List <SignedFileInfo>();
                    foreach (DataOperationResult dataOperationResult in davListCryptoOperationResponse.OperationResults)
                    {
                        var decryptResult = new DecryptResult();
                        decryptResult.DecryptedFile = dataOperationResult.SourceFile;
                        if (dataOperationResult.Exception != null)
                        {
                            Exception curException = dataOperationResult.Exception;

                            decryptResult.Exception = new MasterException(curException.HResult, curException.Message,
                                                                          curException);
                            errorDataOperationResults.Add(dataOperationResult);
                        }
                        else
                        {
                            decryptResult.EncryptedFile = dataOperationResult.OperatedFile;

                            var info = new SignedFileInfo();
                            info.FileUri = dataOperationResult.OperatedFile;
                            toSignVerify.Add(info);
                        }

                        doubleOperationResult.OperationResults.Add(new DoubleResult
                        {
                            FirsOperationResult = decryptResult
                        });
                    }

                    response = _cryptxService.DAVListSignVerify(toSignVerify, settings, true, token);

                    foreach (SignVerifyResponse signVerifyResponse in response)
                    {
                        foreach (DoubleResult doubleResult in doubleOperationResult.OperationResults)
                        {
                            //сопоставляем выход первой операции со входом второй
                            if (((DecryptResult)doubleResult.FirsOperationResult).EncryptedFile ==
                                signVerifyResponse.SourceFile)
                            {
                                var signVerifyResult = new SignVerifyResult();
                                if (signVerifyResponse.Exception != null)
                                {
                                    Exception curException = signVerifyResponse.Exception;
                                    signVerifyResult.Exception = new MasterException(curException.HResult,
                                                                                     curException.Message, curException);
                                }
                                else
                                {
                                    signVerifyResult.CertificateStatuses = signVerifyResponse.CertificateStatuses;
                                    signVerifyResult.MainStatus          = signVerifyResponse.MainStatus;
                                    signVerifyResult.Detached            = signVerifyResponse.Detached;
                                    signVerifyResult.SignedFile          = signVerifyResponse.SourceFile;
                                    signVerifyResult.DataFile            = signVerifyResponse.DataSourceFile;
                                }
                                doubleResult.SecondOperationResult = signVerifyResult;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    doubleOperationResult.Exception = new MasterException(ex.HResult, ex.Message, ex);
                }
            }

            #endregion


            return(Json(new { OperationResult = doubleOperationResult }, JsonRequestBehavior.AllowGet));

            #endregion
        }
Example #30
0
        public void SerializeJsonWebKeySync()
        {
            // Environment variable with the Key Vault endpoint.
            string keyVaultUrl = TestEnvironment.KeyVaultUrl;

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

            #region Snippet:KeysSample7CreateKey
            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

            string dir = Path.Combine(TestContext.CurrentContext.WorkDirectory, "samples", nameof(Sample7_SerializeJsonWebKey));
            Directory.CreateDirectory(dir);

            string path = Path.Combine(dir, $"{nameof(SerializeJsonWebKeySync)}.json");

            // Use `using` expression for clean sample, but scope it to close and dispose immediately.
            {
                #region Snippet:KeysSample7Serialize
                using FileStream file = File.Create(path);
                using (Utf8JsonWriter writer = new Utf8JsonWriter(file))
                {
                    JsonSerializer.Serialize(writer, cloudRsaKey.Key);
                }

                Debug.WriteLine($"Saved JWK to {path}");
                #endregion
            }

            #region Snippet:KeysSamples7Deserialize
            byte[]     buffer = File.ReadAllBytes(path);
            JsonWebKey jwk    = JsonSerializer.Deserialize <JsonWebKey>(buffer);

            Debug.WriteLine($"Read JWK from {path} with ID {jwk.Id}");
            #endregion

            string content = "plaintext";

            #region Snippet:KeysSample7Encrypt
            var encryptClient = new CryptographyClient(jwk);

            byte[]        plaintext = Encoding.UTF8.GetBytes(content);
            EncryptResult encrypted = encryptClient.Encrypt(EncryptParameters.RsaOaepParameters(plaintext));

            Debug.WriteLine($"Encrypted: {Encoding.UTF8.GetString(plaintext)}");
            #endregion

            byte[] ciphertext = encrypted.Ciphertext;

            #region Snippet:KeysSample7Decrypt
            CryptographyClient decryptClient = keyClient.GetCryptographyClient(cloudRsaKey.Name, cloudRsaKey.Properties.Version);
            DecryptResult      decrypted     = decryptClient.Decrypt(DecryptParameters.RsaOaepParameters(ciphertext));

            Debug.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decrypted.Plaintext)}");
            #endregion

            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();
            }

            // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged.
            keyClient.PurgeDeletedKey(rsaKeyName);
        }
Example #31
0
        public void EncryptDecryptRoundtrips(EncryptionAlgorithm algorithm)
        {
            // Use a 256-bit key which will be truncated based on the selected algorithm.
            byte[] k   = new byte[] { 0xe2, 0x7e, 0xd0, 0xc8, 0x45, 0x12, 0xbb, 0xd5, 0x5b, 0x6a, 0xf4, 0x34, 0xd2, 0x37, 0xc1, 0x1f, 0xeb, 0xa3, 0x11, 0x87, 0x0f, 0x80, 0xf2, 0xc2, 0xe3, 0x36, 0x42, 0x60, 0xf3, 0x1c, 0x82, 0xc8 };
            byte[] iv  = new byte[] { 0x89, 0xb8, 0xad, 0xbf, 0xb0, 0x73, 0x45, 0xe3, 0x59, 0x89, 0x32, 0xa0, 0x9c, 0x51, 0x74, 0x41 };
            byte[] aad = Encoding.UTF8.GetBytes("test");

            JsonWebKey key = new JsonWebKey(new[] { KeyOperation.Encrypt, KeyOperation.Decrypt })
            {
                K = k,
            };

            AesCryptographyProvider provider = new AesCryptographyProvider(key, null);

            byte[] plaintext = Encoding.UTF8.GetBytes("plaintext");

            if (algorithm.IsAesGcm())
            {
                iv = iv.Take(AesGcmProxy.NonceByteSize);
            }

            EncryptOptions encryptOptions = new EncryptOptions(algorithm, plaintext, iv, aad);
            EncryptResult  encrypted      = provider.Encrypt(encryptOptions, default);

#if !NETCOREAPP3_1
            if (algorithm.IsAesGcm())
            {
                Assert.IsNull(encrypted);
                Assert.Ignore($"AES-GCM is not supported on {RuntimeInformation.FrameworkDescription} on {RuntimeInformation.OSDescription}");
            }
#endif
            Assert.IsNotNull(encrypted);

            switch (algorithm.ToString())
            {
            // TODO: Move to new test to make sure CryptoClient and LocalCryptoClient initialize a null ICM for AES-CBC(PAD).
            case EncryptionAlgorithm.A128CbcValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0x63, 0x23, 0x21, 0xaf, 0x94, 0xf9, 0xe1, 0x21, 0xc2, 0xbd, 0xb1, 0x1b, 0x04, 0x89, 0x8c, 0x3a },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A192CbcValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0x95, 0x9d, 0x75, 0x91, 0x09, 0x8b, 0x70, 0x0b, 0x9c, 0xfe, 0xaf, 0xcd, 0x60, 0x1f, 0xaa, 0x79 },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A256CbcValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0xf4, 0xe8, 0x5a, 0xa4, 0xa8, 0xb3, 0xff, 0xc3, 0x85, 0x89, 0x17, 0x9a, 0x70, 0x09, 0x96, 0x7f },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A128CbcPadValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0xec, 0xb2, 0x63, 0x4c, 0xe0, 0x04, 0xe0, 0x31, 0x2d, 0x9a, 0x77, 0xb2, 0x11, 0xe5, 0x28, 0x7f },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A192CbcPadValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0xc3, 0x4e, 0x1b, 0xe7, 0x6e, 0xa1, 0xf1, 0xc3, 0x24, 0xae, 0x05, 0x1b, 0x0e, 0x32, 0xac, 0xb4 },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A256CbcPadValue:
                CollectionAssert.AreEqual(
                    new byte[] { 0x4e, 0xbd, 0x78, 0xda, 0x90, 0x73, 0xc8, 0x97, 0x67, 0x2b, 0xa1, 0x0a, 0x41, 0x67, 0xf8, 0x99 },
                    encrypted.Ciphertext);
                CollectionAssert.AreEqual(iv, encrypted.Iv);
                Assert.IsNull(encrypted.AuthenticationTag);
                Assert.IsNull(encrypted.AdditionalAuthenticatedData);
                break;

            case EncryptionAlgorithm.A128GcmValue:
            case EncryptionAlgorithm.A192GcmValue:
            case EncryptionAlgorithm.A256GcmValue:
                Assert.IsNotNull(encrypted.Ciphertext);
                Assert.IsNotNull(encrypted.Iv);
                Assert.IsNotNull(encrypted.AuthenticationTag);
                CollectionAssert.AreEqual(aad, encrypted.AdditionalAuthenticatedData);
                break;
            }

            DecryptOptions decryptOptions = algorithm.IsAesGcm() ?
                                            new DecryptOptions(algorithm, encrypted.Ciphertext, encrypted.Iv, encrypted.AuthenticationTag, encrypted.AdditionalAuthenticatedData) :
                                            new DecryptOptions(algorithm, encrypted.Ciphertext, encrypted.Iv);

            DecryptResult decrypted = provider.Decrypt(decryptOptions, default);
            Assert.IsNotNull(decrypted);

            // AES-CBC will be zero-padded.
            StringAssert.StartsWith("plaintext", Encoding.UTF8.GetString(decrypted.Plaintext));
        }
Example #32
0
        public async Task EncryptLocalDecryptOnManagedHsm([EnumValues(
                                                               nameof(EncryptionAlgorithm.A128Cbc),
                                                               nameof(EncryptionAlgorithm.A192Cbc),
                                                               nameof(EncryptionAlgorithm.A256Cbc),
                                                               nameof(EncryptionAlgorithm.A128CbcPad),
                                                               nameof(EncryptionAlgorithm.A192CbcPad),
                                                               nameof(EncryptionAlgorithm.A256CbcPad))] EncryptionAlgorithm algorithm)
        {
            int        keySizeInBytes = algorithm.GetAesCbcEncryptionAlgorithm().KeySizeInBytes;
            JsonWebKey jwk            = KeyUtilities.CreateAesKey(keySizeInBytes, s_aesKeyOps);

            string      keyName = Recording.GenerateId();
            KeyVaultKey key     = await Client.ImportKeyAsync(
                new ImportKeyOptions(keyName, jwk));

            RegisterForCleanup(key.Name);

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

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

            byte[] iv = new byte[16];
            if (algorithm.GetAesCbcEncryptionAlgorithm() is AesCbc)
            {
                Recording.Random.NextBytes(iv);
            }

            EncryptParameters encryptParams = algorithm.ToString() switch
            {
                EncryptionAlgorithm.A128CbcValue => EncryptParameters.A128CbcParameters(plaintext, iv),
                EncryptionAlgorithm.A192CbcValue => EncryptParameters.A192CbcParameters(plaintext, iv),
                EncryptionAlgorithm.A256CbcValue => EncryptParameters.A256CbcParameters(plaintext, iv),

                EncryptionAlgorithm.A128CbcPadValue => EncryptParameters.A128CbcPadParameters(plaintext, iv),
                EncryptionAlgorithm.A192CbcPadValue => EncryptParameters.A192CbcPadParameters(plaintext, iv),
                EncryptionAlgorithm.A256CbcPadValue => EncryptParameters.A256CbcPadParameters(plaintext, iv),

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            EncryptResult encrypted = await localClient.EncryptAsync(encryptParams);

            Assert.IsNotNull(encrypted.Ciphertext);

            DecryptParameters decryptParameters = algorithm.ToString() switch
            {
                EncryptionAlgorithm.A128CbcValue => DecryptParameters.A128CbcParameters(encrypted.Ciphertext, encrypted.Iv),
                EncryptionAlgorithm.A192CbcValue => DecryptParameters.A192CbcParameters(encrypted.Ciphertext, encrypted.Iv),
                EncryptionAlgorithm.A256CbcValue => DecryptParameters.A256CbcParameters(encrypted.Ciphertext, encrypted.Iv),

                EncryptionAlgorithm.A128CbcPadValue => DecryptParameters.A128CbcPadParameters(encrypted.Ciphertext, encrypted.Iv),
                EncryptionAlgorithm.A192CbcPadValue => DecryptParameters.A192CbcPadParameters(encrypted.Ciphertext, encrypted.Iv),
                EncryptionAlgorithm.A256CbcPadValue => DecryptParameters.A256CbcPadParameters(encrypted.Ciphertext, encrypted.Iv),

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            DecryptResult decrypted = await remoteClient.DecryptAsync(decryptParameters);

            Assert.IsNotNull(decrypted.Plaintext);

            CollectionAssert.AreEqual(plaintext, decrypted.Plaintext);
        }
Example #33
0
        public async Task AesGcmEncryptDecrypt([EnumValues(
                                                    nameof(EncryptionAlgorithm.A128Gcm),
                                                    nameof(EncryptionAlgorithm.A192Gcm),
                                                    nameof(EncryptionAlgorithm.A256Gcm)
                                                    )] EncryptionAlgorithm algorithm)
        {
            int keySizeInBytes = algorithm.ToString() switch
            {
                EncryptionAlgorithm.A128GcmValue => 128 >> 3,
                EncryptionAlgorithm.A192GcmValue => 192 >> 3,
                EncryptionAlgorithm.A256GcmValue => 256 >> 3,

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            JsonWebKey jwk = KeyUtilities.CreateAesKey(keySizeInBytes, s_aesKeyOps);

            string      keyName = Recording.GenerateId();
            KeyVaultKey key     = await Client.ImportKeyAsync(
                new ImportKeyOptions(keyName, jwk));

            RegisterForCleanup(key.Name);

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

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

            byte[] iv = new byte[16];
            if (algorithm.GetAesCbcEncryptionAlgorithm() is AesCbc)
            {
                Recording.Random.NextBytes(iv);
            }

            EncryptParameters encryptParams = algorithm.ToString() switch
            {
                // TODO: Re-record with random additionalAuthenticatedData once the "aad" issue is fixed with Managed HSM.
                EncryptionAlgorithm.A128GcmValue => EncryptParameters.A128GcmParameters(plaintext),
                EncryptionAlgorithm.A192GcmValue => EncryptParameters.A192GcmParameters(plaintext),
                EncryptionAlgorithm.A256GcmValue => EncryptParameters.A256GcmParameters(plaintext),

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            EncryptResult encrypted = await remoteClient.EncryptAsync(encryptParams);

            Assert.IsNotNull(encrypted.Ciphertext);

            DecryptParameters decryptParameters = algorithm.ToString() switch
            {
                // TODO: Re-record with random additionalAuthenticatedData once the "aad" issue is fixed with Managed HSM.
                EncryptionAlgorithm.A128GcmValue => DecryptParameters.A128GcmParameters(encrypted.Ciphertext, encrypted.Iv, encrypted.AuthenticationTag),
                EncryptionAlgorithm.A192GcmValue => DecryptParameters.A192GcmParameters(encrypted.Ciphertext, encrypted.Iv, encrypted.AuthenticationTag),
                EncryptionAlgorithm.A256GcmValue => DecryptParameters.A256GcmParameters(encrypted.Ciphertext, encrypted.Iv, encrypted.AuthenticationTag),

                _ => throw new NotSupportedException($"{algorithm} is not supported"),
            };

            DecryptResult decrypted = await remoteClient.DecryptAsync(decryptParameters);

            Assert.IsNotNull(decrypted.Plaintext);

            CollectionAssert.AreEqual(plaintext, decrypted.Plaintext);
        }
Example #34
0
        static async Task Main(string[] args)
        {
            // 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 ClientSecretCredential(tenantId, clientId, clientSecret));

            // next two lines are just to recover key in case we stop program after deleting and before recovering / purging
            //var recoverOperation1 = await client.StartRecoverDeletedKeyAsync("rsa-key-name");
            //await recoverOperation1.WaitForCompletionAsync();

            // Create a software RSA key
            var         rsaCreateKey = new CreateRsaKeyOptions("rsa-key-name", hardwareProtected: false);
            KeyVaultKey rsaKey       = await client.CreateRsaKeyAsync(rsaCreateKey);

            Console.WriteLine("Created the key....");
            Console.WriteLine($"rsaKey.Name: {rsaKey.Name}");
            Console.WriteLine($"rsaKey.KeyType: {rsaKey.KeyType}");
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // Retrieve
            KeyVaultKey key = await client.GetKeyAsync("rsa-key-name");

            Console.WriteLine("Retrieve the key");
            Console.WriteLine($"key.Name: {key.Name}");
            Console.WriteLine($"key.KeyType: {key.KeyType}");
            Console.WriteLine("==================================================");
            Console.WriteLine();


            // Update
            KeyVaultKey updateKey = await client.CreateKeyAsync("rsa-key-name", KeyType.Rsa);

            // You can specify additional application-specific metadata in the form of tags.
            updateKey.Properties.Tags["foo"] = "updated tag";

            KeyVaultKey updatedKey = await client.UpdateKeyPropertiesAsync(updateKey.Properties);

            Console.WriteLine("Update Initiated.");
            Console.WriteLine($"updatedKey.Name: {updatedKey.Name}");
            Console.WriteLine($"updatedKey.Properties.Version: {updatedKey.Properties.Version}");
            Console.WriteLine($"updatedKey.Properties.UpdatedOn: {updatedKey.Properties.UpdatedOn}");
            Console.WriteLine("==================================================");
            Console.WriteLine();

            /// Delete
            DeleteKeyOperation operation = await client.StartDeleteKeyAsync("rsa-key-name");

            DeletedKey deletedKey = operation.Value;

            Console.WriteLine("Delete operation initialted.");
            Console.WriteLine($"deletedKey.Name: {deletedKey.Name}");
            Console.WriteLine($"deletedKey.DeletedOn: {deletedKey.DeletedOn}");
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // Wait for deletion to complete
            await operation.WaitForCompletionAsync();

            // Recover deleted key
            var recoverOperation = await client.StartRecoverDeletedKeyAsync("rsa-key-name");

            await recoverOperation.WaitForCompletionAsync();

            Console.WriteLine("Recovery completed");
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // Create crypto client and demo of encryption / decryption
            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new ClientSecretCredential(tenantId, clientId, clientSecret));

            byte[] plaintext = Encoding.UTF8.GetBytes("If you can dream it, you can do it.");

            // encrypt the data using the algorithm RSAOAEP
            EncryptResult encryptResult = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, plaintext);

            Console.WriteLine("Encryption demo.");
            Console.WriteLine("Encrypted Base64: " + Convert.ToBase64String(encryptResult.Ciphertext));
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // decrypt the encrypted data.
            DecryptResult decryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext);

            Console.WriteLine("Decryption demo.");
            Console.WriteLine("Decrypted: " + Encoding.UTF8.GetString(decryptResult.Plaintext));
            Console.WriteLine("==================================================");
            Console.WriteLine();

            // Purge
            DeleteKeyOperation deleteOperation = await client.StartDeleteKeyAsync("rsa-key-name");

            await deleteOperation.WaitForCompletionAsync();

            DeletedKey purgekey = deleteOperation.Value;
            await client.PurgeDeletedKeyAsync(purgekey.Name);

            Console.WriteLine("Purge Initiated.");
            Console.WriteLine($"purgekey.Name: {purgekey.Name}");
            Console.WriteLine("==================================================");
            Console.WriteLine();
        }