コード例 #1
0
        public void DecryptAlgorithmNotSupported([EnumValues(Exclude = new[] { nameof(KeyType.Rsa), nameof(KeyType.RsaHsm), nameof(KeyType.Oct), nameof(KeyType.OctHsm) })] KeyType keyType)
        {
            JsonWebKey         jwk    = CreateKey(keyType);
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.DecryptAsync(new EncryptionAlgorithm("ignored"), TestData));
        }
コード例 #2
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);
        }
コード例 #3
0
        public async Task EncryptDecryptRoundTrip([EnumValues] EncryptionAlgorithm algorithm)
        {
            KeyVaultKey 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);
        }
コード例 #4
0
        public void DecryptOperationNotSupported()
        {
            JsonWebKey         jwk    = new JsonWebKey(RSA.Create(), keyOps: Array.Empty <KeyOperation>());
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.DecryptAsync(new EncryptionAlgorithm("ignored"), TestData));
        }
コード例 #5
0
        public void AesDecryptAlgorithmNotSupported([EnumValues(nameof(EncryptionAlgorithm.A128Gcm), nameof(EncryptionAlgorithm.A192Gcm), nameof(EncryptionAlgorithm.A256Gcm))] EncryptionAlgorithm algorithm)
        {
            JsonWebKey         jwk    = CreateKey(KeyType.Oct);
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

            Assert.ThrowsAsync <NotSupportedException>(async() => await client.DecryptAsync(algorithm, TestData));
        }
コード例 #6
0
        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));
        }
コード例 #7
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
        }
コード例 #8
0
        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)));
        }
コード例 #9
0
        public async Task EncryptDecryptRoundtrip([EnumValues(nameof(EncryptionAlgorithm.Rsa15), nameof(EncryptionAlgorithm.RsaOaep))] EncryptionAlgorithm algorithm)
        {
            JsonWebKey         jwk    = CreateKey(KeyType.Rsa, includePrivateParameters: true);
            CryptographyClient client = CreateClient <CryptographyClient>(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);
        }
コード例 #10
0
        public async Task EncryptDecrypt()
        {
            #region Snippet:EncryptDecrypt
            byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext");

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

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

            #endregion
        }
コード例 #11
0
        public async Task EncryptDecryptAsync()
        {
            // 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 we 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 = await keyClient.CreateRsaKeyAsync(rsaKey);

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

            // Then we 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 = await cryptoClient.EncryptAsync(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 = await cryptoClient.DecryptAsync(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.
            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);
        }
コード例 #12
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);
        }
コード例 #13
0
        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)));
        }
コード例 #14
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));
    }
コード例 #15
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);
        }
コード例 #16
0
        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
            }
        }
コード例 #17
0
        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);
        }
コード例 #18
0
        public async Task DecryptRequiresPrivateKey()
        {
            JsonWebKey         jwk    = CreateKey(KeyType.Rsa, keyOps: new[] { KeyOperation.Encrypt, KeyOperation.Decrypt });
            CryptographyClient client = CreateClient <CryptographyClient>(jwk);

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

            Assert.ThrowsAsync(new InstanceOfTypeConstraint(typeof(CryptographicException)), async() => await client.DecryptAsync(EncryptionAlgorithm.RsaOaep, encrypted.Ciphertext));
        }
コード例 #19
0
        public async Task <UserAccountData> requestDecryption(string email_Address, string accountName)
        {
            DBAccountData   dBAccountData = null;
            UserAccountData data          = null;
            //connect to the firestoredatabase
            bool connection_Result = connectToFirebase();

            try
            {
                if (connection_Result)
                {
                    DocumentReference documentReference = db.Collection("UserAccounts").Document(email_Address).Collection("MyAccounts").Document(accountName);
                    DocumentSnapshot  documentSnapshot  = await documentReference.GetSnapshotAsync();

                    if (documentSnapshot.Exists)
                    {
                        //first of all encrypt the user Data
                        //Get the User Encryption Key from the firestore database
                        DocumentReference getUserKey = db.Collection("UserEncryptionKeys").Document(email_Address);

                        //get the snapshot for the same
                        DocumentSnapshot snapshot = await getUserKey.GetSnapshotAsync();

                        if (snapshot.Exists)
                        {
                            string keyName = "";
                            Dictionary <string, object> userKeyDict = snapshot.ToDictionary();
                            foreach (KeyValuePair <string, object> pair in userKeyDict)
                            {
                                if (pair.Key == "userKeyName")
                                {
                                    keyName = pair.Value.ToString();
                                    break;
                                }
                            }

                            //Convert to the DBUserEncryption
                            //DBUserEncryptionKeys dBUserEncryptionKeys = snapshot.ConvertTo<DBUserEncryptionKeys>();
                            //string key_Name_For_Encryption = dBUserEncryptionKeys.userKeyName;

                            //Create the client for the azure KeyVault Access
                            var client = new KeyClient(vaultUri: new Uri(KeyVaultUrl), credential: new ClientSecretCredential(tenantId, clientid, client_secret));

                            //Retrive the key from the azure Key Vault
                            KeyVaultKey key = await client.GetKeyAsync(keyName);

                            //Now Creating the Crypto Client for the Encryption of the user Data
                            var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new ClientSecretCredential(tenantId, clientid, client_secret));

                            //get the Account Details
                            DocumentReference documentReference_for_getting_data = db.Collection("UserAccounts").Document(email_Address).Collection("MyAccounts").Document(accountName);

                            //get the snapshots for the document
                            DocumentSnapshot documentSnapshot_for_getting_data = await documentReference_for_getting_data.GetSnapshotAsync();

                            if (documentSnapshot_for_getting_data.Exists)
                            {
                                //intiliaze the AccountData object and conver the snapshot to the Account Data object
                                dBAccountData = new DBAccountData();
                                dBAccountData = documentSnapshot_for_getting_data.ConvertTo <DBAccountData>();

                                //perform the decryption
                                DecryptResult decryptResult_for_userName = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, Convert.FromBase64String(dBAccountData.accountUserName));

                                DecryptResult decryptResult_for_password = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, Convert.FromBase64String(dBAccountData.accountPassword));

                                //convert decrypted result to the string
                                string decrypted_username_plaintext = Encoding.UTF8.GetString(decryptResult_for_userName.Plaintext);
                                string decrypted_password_plaintext = Encoding.UTF8.GetString(decryptResult_for_password.Plaintext);

                                //chnage the decrypted string to the plaintext
                                dBAccountData.accountUserName = decrypted_username_plaintext;
                                dBAccountData.accountPassword = decrypted_password_plaintext;

                                data           = new UserAccountData();
                                data.userEmail = email_Address;
                                data.Name      = dBAccountData.accountName;
                                data.UserName  = dBAccountData.accountUserName;
                                data.Password  = dBAccountData.accountPassword;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CustomException customException = new CustomException();
                customException.errorTitleName     = "Error Occured while performing the decryption of the Username ans Password";
                customException.errorMessageToUser = ex.Message;
                throw new FaultException <CustomException>(customException);
            }
            return(data);
        }
コード例 #20
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);
        }
コード例 #21
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);
        }
コード例 #22
0
        public async Task <byte[]> Decrypt(byte[] aEncrypted, int offset = 0)
        {
            var result = await _client.DecryptAsync(_algorithm, aEncrypted);

            return(result.Plaintext);
        }
コード例 #23
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();
        }