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, false);

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

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

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

            DecryptParameters decryptOptions = new DecryptParameters(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));
        }
        public IActionResult Decrypt([FromBody] DecryptParameters decryptParameters)
        {
            if (decryptParameters == null)
            {
                return(BadRequest());
            }

            return(Ok(Cryptography.Decrypt(_dirName, decryptParameters.Data)));
        }
        public void DecryptOptionsAll()
        {
            byte[]            buffer  = new byte[] { 0, 1, 2, 3 };
            DecryptParameters options = CryptographyModelFactory.DecryptParameters(EncryptionAlgorithm.A128Cbc, buffer, buffer, buffer, buffer);

            Assert.AreEqual(EncryptionAlgorithm.A128Cbc, options.Algorithm);
            CollectionAssert.AreEqual(buffer, options.Ciphertext);
            CollectionAssert.AreEqual(buffer, options.Iv);
            CollectionAssert.AreEqual(buffer, options.AuthenticationTag);
            CollectionAssert.AreEqual(buffer, options.AdditionalAuthenticatedData);
        }
        public void RequiresCiphertext()
        {
            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.Rsa15Parameters(null));

            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.RsaOaepParameters(null));
            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.RsaOaep256Parameters(null));
            Assert.AreEqual("ciphertext", ex.ParamName);
        }
        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);
        }
        public async Task <IActionResult> Decrypt([FromBody] DecryptParameters decryptParameters)
        {
            using (var client = new HttpClient())
            {
                client.SetAcceptEncodingHeader(this.HttpContext.Request.Headers);

                var content = new StringContent(JsonConvert.SerializeObject(decryptParameters), Encoding.UTF8, "application/json");

                using (var response = await client.PostAsync(CreateInternalUri("crypto/decrypt"), content))
                {
                    return(await response.GetActionResult());
                }
            }
        }
Esempio n. 7
0
        static int Decrypt(DecryptParameters p)
        {
            _arguments = p;

            EnsureCanOverwriteDestination(p);

            var retryWithBase64 = false;

            do
            {
                try
                {
                    using (var encryptedStream = new FileStream(p.SourceFileName, FileMode.Open, FileAccess.Read, FileShare.None))
                        using (var decryptedStream = new FileStream(p.DestinationFileName, FileMode.Create, FileAccess.Write, FileShare.None))
                            using (var cipher = new EncryptedNewKeyCipher(p.Certificate))
                            {
                                cipher.Base64Encoded = retryWithBase64;
                                cipher.Decrypt(encryptedStream, decryptedStream);
                                retryWithBase64 = false;
                            }
                }
                catch (ArgumentException x) when(x.ParamName == "encryptedStream")
                {
                    if (retryWithBase64)
                    {
                        throw;
                    }

                    using (var reader = new StreamReader(p.SourceFileName, Encoding.ASCII))
                    {
                        for (var i = 0; i < 5 && !reader.EndOfStream; i++)
                        {
                            var line = reader.ReadLine();
                            if (!Regex.IsMatch(line, _base64Regex))
                            {
                                throw;
                            }
                        }
                        retryWithBase64 = true;
                    }
                }
            }while (retryWithBase64);

            return(0);
        }
Esempio n. 8
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 void RequiresCiphertextIv()
        {
            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A128CbcParameters(null, null));

            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A128CbcParameters(Array.Empty <byte>(), null));
            Assert.AreEqual("iv", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A192CbcParameters(null, null));
            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A192CbcParameters(Array.Empty <byte>(), null));
            Assert.AreEqual("iv", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A256CbcParameters(null, null));
            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A256CbcParameters(Array.Empty <byte>(), null));
            Assert.AreEqual("iv", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A128CbcPadParameters(null, null));
            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A128CbcPadParameters(Array.Empty <byte>(), null));
            Assert.AreEqual("iv", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A192CbcPadParameters(null, null));
            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A192CbcPadParameters(Array.Empty <byte>(), null));
            Assert.AreEqual("iv", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A256CbcPadParameters(null, null));
            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A256CbcPadParameters(Array.Empty <byte>(), null));
            Assert.AreEqual("iv", ex.ParamName);
        }
        public void RequiresOnlyCiphertextIvAuthenticationTag()
        {
            ArgumentNullException ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A128GcmParameters(null, null, null, null));

            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A128GcmParameters(Array.Empty <byte>(), null, null, null));
            Assert.AreEqual("iv", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A128GcmParameters(Array.Empty <byte>(), Array.Empty <byte>(), null, null));
            Assert.AreEqual("authenticationTag", ex.ParamName);

            Assert.DoesNotThrow(() => DecryptParameters.A128GcmParameters(Array.Empty <byte>(), Array.Empty <byte>(), Array.Empty <byte>(), null));

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A192GcmParameters(null, null, null, null));
            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A192GcmParameters(Array.Empty <byte>(), null, null, null));
            Assert.AreEqual("iv", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A192GcmParameters(Array.Empty <byte>(), Array.Empty <byte>(), null, null));
            Assert.AreEqual("authenticationTag", ex.ParamName);

            Assert.DoesNotThrow(() => DecryptParameters.A192GcmParameters(Array.Empty <byte>(), Array.Empty <byte>(), Array.Empty <byte>(), null));

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A256GcmParameters(null, null, null, null));
            Assert.AreEqual("ciphertext", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A256GcmParameters(Array.Empty <byte>(), null, null, null));
            Assert.AreEqual("iv", ex.ParamName);

            ex = Assert.Throws <ArgumentNullException>(() => DecryptParameters.A256GcmParameters(Array.Empty <byte>(), Array.Empty <byte>(), null, null));
            Assert.AreEqual("authenticationTag", ex.ParamName);

            Assert.DoesNotThrow(() => DecryptParameters.A256GcmParameters(Array.Empty <byte>(), Array.Empty <byte>(), Array.Empty <byte>(), null));
        }
        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);
        }
Esempio n. 12
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);
        }
Esempio n. 13
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);
        }
Esempio n. 14
0
 public Task <DecryptResult> DecryptAsync(DecryptParameters options, CancellationToken cancellationToken = default) => throw new CryptographicException(CRYPT_E_NO_PROVIDER);
        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, false);

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

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

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

            DecryptParameters decryptOptions = new DecryptParameters(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));
        }
Esempio n. 16
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);
        }