public void PreformHashCodeCorrectly()
        {
            KeyEncryptionKey masterKey1 = new KeyEncryptionKey("CMK", keyEncryptionKeyPath, azureKeyProvider);
            KeyEncryptionKey masterKey2 = new KeyEncryptionKey("CMK", keyEncryptionKeyPath, azureKeyProvider);

            Assert.Equal(masterKey1.GetHashCode(), masterKey2.GetHashCode());
        }
        public void PreformEqualityCorrectly()
        {
            KeyEncryptionKey masterKey1 = new KeyEncryptionKey("CMK", keyEncryptionKeyPath, azureKeyProvider);
            KeyEncryptionKey masterKey2 = new KeyEncryptionKey("CMK", keyEncryptionKeyPath, azureKeyProvider);

            Assert.Equal(masterKey1, masterKey2);
        }
        public void CacheEncryptionKeyCorrectlyWhenCallingGetOrCreate()
        {
            KeyEncryptionKey masterKey1 = new KeyEncryptionKey("MK", keyEncryptionKeyPath, azureKeyProvider);
            KeyEncryptionKey masterKey2 = new KeyEncryptionKey("MK", keyEncryptionKeyPath, azureKeyProvider);
            KeyEncryptionKey masterKey3 = new KeyEncryptionKey("Not_MK", keyEncryptionKeyPath, azureKeyProvider);

            byte[] EncryptedKey1 = { 1, 206, 0, 0, 1, 104, 0, 116, 0, 116, 0, 112, 0, 115, 0, 58, 0, 47, 0, 47, 0, 106, 0, 101, 0, 116, 0, 114, 0, 105, 0, 109, 0, 109, 0, 101, 0, 45, 0, 107, 0, 101, 0, 121, 0, 45, 0, 118, 0, 97, 0, 117, 0, 108, 0, 116, 0, 46, 0, 118, 0, 97, 0, 117, 0, 108, 0, 116, 0, 46, 0, 97, 0, 122, 0, 117, 0, 114, 0, 101, 0, 46, 0, 110, 0, 101, 0, 116, 0, 47, 0, 107, 0, 101, 0, 121, 0, 115, 0, 47, 0, 97, 0, 108, 0, 119, 0, 97, 0, 121, 0, 115, 0, 45, 0, 101, 0, 110, 0, 99, 0, 114, 0, 121, 0, 112, 0, 116, 0, 101, 0, 100, 0, 45, 0, 97, 0, 117, 0, 116, 0, 111, 0, 49, 0, 47, 0, 97, 0, 55, 0, 100, 0, 53, 0, 99, 0, 57, 0, 56, 0, 57, 0, 100, 0, 53, 0, 97, 0, 48, 0, 52, 0, 50, 0, 51, 0, 102, 0, 56, 0, 100, 0, 51, 0, 53, 0, 54, 0, 102, 0, 49, 0, 57, 0, 53, 0, 53, 0, 51, 0, 54, 0, 101, 0, 53, 0, 57, 0, 48, 0, 146, 197, 248, 185, 212, 19, 214, 85, 165, 169, 226, 123, 111, 175, 36, 125, 232, 11, 157, 149, 159, 59, 85, 94, 205, 149, 132, 235, 77, 85, 113, 234, 252, 191, 31, 138, 176, 171, 34, 177, 99, 108, 122, 127, 250, 60, 198, 101, 237, 238, 73, 109, 146, 56, 227, 101, 159, 141, 193, 102, 165, 82, 221, 233, 169, 55, 13, 102, 135, 162, 19, 133, 126, 147, 117, 254, 79, 128, 38, 251, 104, 60, 175, 40, 37, 73, 207, 66, 93, 25, 252, 150, 234, 122, 54, 166, 133, 208, 122, 221, 80, 139, 226, 186, 112, 158, 75, 154, 11, 61, 116, 18, 241, 187, 130, 251, 38, 222, 19, 179, 227, 115, 88, 194, 56, 28, 231, 94, 34, 153, 136, 26, 241, 109, 193, 150, 165, 91, 209, 210, 157, 196, 45, 171, 180, 10, 51, 130, 115, 100, 132, 54, 167, 192, 1, 41, 26, 99, 161, 206, 83, 172, 231, 44, 249, 232, 29, 25, 193, 12, 28, 133, 193, 7, 86, 78, 41, 151, 56, 13, 159, 8, 167, 226, 242, 31, 14, 51, 196, 36, 94, 109, 12, 181, 103, 126, 84, 208, 18, 134, 183, 74, 74, 209, 55, 40, 206, 187, 162, 159, 94, 208, 114, 188, 254, 25, 31, 79, 88, 126, 163, 167, 38, 245, 45, 217, 133, 149, 21, 141, 124, 34, 176, 39, 61, 177, 2, 124, 160, 138, 170, 65, 7, 61, 203, 40, 32, 57, 228, 172, 10, 193, 162, 30, 51, 121, 1, 185, 3, 43, 189, 28, 36, 109, 14, 153, 209, 17, 165, 201, 245, 18, 86, 215, 86, 104, 206, 109, 227, 78, 207, 14, 112, 148, 130, 136, 144, 115, 212, 4, 144, 194, 150, 234, 6, 53, 123, 51, 220, 126, 21, 75, 64, 186, 145, 208, 96, 176, 46, 249, 242, 10, 177, 18, 158, 131, 92, 76, 203, 28, 123, 218, 121, 112, 75, 215, 187, 226, 247, 116, 159, 244, 229, 30, 115, 206, 227, 175, 72, 80, 229, 117, 198, 184, 28, 35, 86, 185, 226, 192, 99, 178, 40, 153, 98, 155, 219, 43, 111, 190, 58, 183, 241, 234, 139, 155, 252, 109, 207, 237, 56, 222, 212, 163, 216, 35, 55, 57, 106, 60, 145, 102, 163, 132, 65, 128, 149, 48, 187, 174, 75, 62, 157, 31, 162, 38, 239, 43, 88, 140, 203, 221, 181, 244, 200, 182, 237, 36, 224, 241, 89, 40, 232, 107, 65, 64, 15, 164, 110, 21, 121, 183, 36, 200, 20, 223, 45, 238, 209, 43, 88, 123, 108, 252, 219, 75, 80, 197, 173, 244, 130, 193, 11, 96, 143, 7, 23, 250, 60, 21, 168, 69, 108, 168, 85, 8, 96, 78, 156, 122, 45, 202, 82, 180, 135, 200, 131, 220, 248, 42, 210, 234, 132, 100, 88, 80, 93, 212, 145, 253, 45, 117, 51, 163, 214, 134, 42, 167, 0, 120, 40, 165, 171, 114, 252, 151, 74, 0, 157, 190, 250, 132, 22, 141, 14, 146, 34, 155, 39, 103, 58, 226 };
            byte[] EncryptedKey2 = { 1, 206, 0, 0, 1, 104, 0, 116, 0, 116, 0, 112, 0, 115, 0, 58, 0, 47, 0, 47, 0, 106, 0, 101, 0, 116, 0, 114, 0, 105, 0, 109, 0, 109, 0, 101, 0, 45, 0, 107, 0, 101, 0, 121, 0, 45, 0, 118, 0, 97, 0, 117, 0, 108, 0, 116, 0, 46, 0, 118, 0, 97, 0, 117, 0, 108, 0, 116, 0, 46, 0, 97, 0, 122, 0, 117, 0, 114, 0, 101, 0, 46, 0, 110, 0, 101, 0, 116, 0, 47, 0, 107, 0, 101, 0, 121, 0, 115, 0, 47, 0, 97, 0, 108, 0, 119, 0, 97, 0, 121, 0, 115, 0, 45, 0, 101, 0, 110, 0, 99, 0, 114, 0, 121, 0, 112, 0, 116, 0, 101, 0, 100, 0, 45, 0, 97, 0, 117, 0, 116, 0, 111, 0, 49, 0, 47, 0, 97, 0, 55, 0, 100, 0, 53, 0, 99, 0, 57, 0, 56, 0, 57, 0, 100, 0, 53, 0, 97, 0, 48, 0, 52, 0, 50, 0, 51, 0, 102, 0, 56, 0, 100, 0, 51, 0, 53, 0, 54, 0, 102, 0, 49, 0, 57, 0, 53, 0, 53, 0, 51, 0, 54, 0, 101, 0, 53, 0, 57, 0, 48, 0, 146, 197, 248, 185, 212, 19, 214, 85, 165, 169, 226, 123, 111, 175, 36, 125, 232, 11, 157, 149, 159, 59, 85, 94, 205, 149, 132, 235, 77, 85, 113, 234, 252, 191, 31, 138, 176, 171, 34, 177, 99, 108, 122, 127, 250, 60, 198, 101, 237, 238, 73, 109, 146, 56, 227, 101, 159, 141, 193, 102, 165, 82, 221, 233, 169, 55, 13, 102, 135, 162, 19, 133, 126, 147, 117, 254, 79, 128, 38, 251, 104, 60, 175, 40, 37, 73, 207, 66, 93, 25, 252, 150, 234, 122, 54, 166, 133, 208, 122, 221, 80, 139, 226, 186, 112, 158, 75, 154, 11, 61, 116, 18, 241, 187, 130, 251, 38, 222, 19, 179, 227, 115, 88, 194, 56, 28, 231, 94, 34, 153, 136, 26, 241, 109, 193, 150, 165, 91, 209, 210, 157, 196, 45, 171, 180, 10, 51, 130, 115, 100, 132, 54, 167, 192, 1, 41, 26, 99, 161, 206, 83, 172, 231, 44, 249, 232, 29, 25, 193, 12, 28, 133, 193, 7, 86, 78, 41, 151, 56, 13, 159, 8, 167, 226, 242, 31, 14, 51, 196, 36, 94, 109, 12, 181, 103, 126, 84, 208, 18, 134, 183, 74, 74, 209, 55, 40, 206, 187, 162, 159, 94, 208, 114, 188, 254, 25, 31, 79, 88, 126, 163, 167, 38, 245, 45, 217, 133, 149, 21, 141, 124, 34, 176, 39, 61, 177, 2, 124, 160, 138, 170, 65, 7, 61, 203, 40, 32, 57, 228, 172, 10, 193, 162, 30, 51, 121, 1, 185, 3, 43, 189, 28, 36, 109, 14, 153, 209, 17, 165, 201, 245, 18, 86, 215, 86, 104, 206, 109, 227, 78, 207, 14, 112, 148, 130, 136, 144, 115, 212, 4, 144, 194, 150, 234, 6, 53, 123, 51, 220, 126, 21, 75, 64, 186, 145, 208, 96, 176, 46, 249, 242, 10, 177, 18, 158, 131, 92, 76, 203, 28, 123, 218, 121, 112, 75, 215, 187, 226, 247, 116, 159, 244, 229, 30, 115, 206, 227, 175, 72, 80, 229, 117, 198, 184, 28, 35, 86, 185, 226, 192, 99, 178, 40, 153, 98, 155, 219, 43, 111, 190, 58, 183, 241, 234, 139, 155, 252, 109, 207, 237, 56, 222, 212, 163, 216, 35, 55, 57, 106, 60, 145, 102, 163, 132, 65, 128, 149, 48, 187, 174, 75, 62, 157, 31, 162, 38, 239, 43, 88, 140, 203, 221, 181, 244, 200, 182, 237, 36, 224, 241, 89, 40, 232, 107, 65, 64, 15, 164, 110, 21, 121, 183, 36, 200, 20, 223, 45, 238, 209, 43, 88, 123, 108, 252, 219, 75, 80, 197, 173, 244, 130, 193, 11, 96, 143, 7, 23, 250, 60, 21, 168, 69, 108, 168, 85, 8, 96, 78, 156, 122, 45, 202, 82, 180, 135, 200, 131, 220, 248, 42, 210, 234, 132, 100, 88, 80, 93, 212, 145, 253, 45, 117, 51, 163, 214, 134, 42, 167, 0, 120, 40, 165, 171, 114, 252, 151, 74, 0, 157, 190, 250, 132, 22, 141, 14, 146, 34, 155, 39, 103, 58, 226 };

            DataEncryptionKey encryptionkey1 = ProtectedDataEncryptionKey.GetOrCreate("EK", masterKey1, EncryptedKey1);
            DataEncryptionKey encryptionkey2 = ProtectedDataEncryptionKey.GetOrCreate("EK", masterKey2, EncryptedKey1);

            Assert.Same(encryptionkey1, encryptionkey2);

            DataEncryptionKey encryptionkey3 = ProtectedDataEncryptionKey.GetOrCreate("EK", masterKey1, EncryptedKey1);
            DataEncryptionKey encryptionkey4 = ProtectedDataEncryptionKey.GetOrCreate("EK", masterKey3, EncryptedKey1);

            Assert.NotSame(encryptionkey3, encryptionkey4);

            DataEncryptionKey encryptionkey5 = ProtectedDataEncryptionKey.GetOrCreate("EK", masterKey1, EncryptedKey1);
            DataEncryptionKey encryptionkey6 = ProtectedDataEncryptionKey.GetOrCreate("Not_EK", masterKey1, EncryptedKey1);

            Assert.NotSame(encryptionkey5, encryptionkey6);

            DataEncryptionKey encryptionkey7 = ProtectedDataEncryptionKey.GetOrCreate("EK", masterKey1, EncryptedKey1);
            DataEncryptionKey encryptionkey8 = ProtectedDataEncryptionKey.GetOrCreate("EK", masterKey1, EncryptedKey2);

            Assert.Same(encryptionkey7, encryptionkey8);
        }
        private async Task <ProtectedDataEncryptionKey> BuildProtectedDataEncryptionKeyAsync(
            ClientEncryptionKeyProperties clientEncryptionKeyProperties,
            string keyId,
            CancellationToken cancellationToken)
        {
            if (await EncryptionCosmosClient.EncryptionKeyCacheSemaphore.WaitAsync(-1, cancellationToken))
            {
                try
                {
                    KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                        clientEncryptionKeyProperties.EncryptionKeyWrapMetadata.Name,
                        clientEncryptionKeyProperties.EncryptionKeyWrapMetadata.Value,
                        this.encryptionContainer.EncryptionCosmosClient.EncryptionKeyStoreProviderImpl);

                    ProtectedDataEncryptionKey protectedDataEncryptionKey = ProtectedDataEncryptionKey.GetOrCreate(
                        keyId,
                        keyEncryptionKey,
                        clientEncryptionKeyProperties.WrappedDataEncryptionKey);

                    return(protectedDataEncryptionKey);
                }
                finally
                {
                    EncryptionCosmosClient.EncryptionKeyCacheSemaphore.Release(1);
                }
            }

            throw new InvalidOperationException("Failed to build ProtectedDataEncryptionKey. ");
        }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of MdeEncryptionAlgorithm.
        /// Uses <see cref="AeadAes256CbcHmac256EncryptionAlgorithm"/> which implements authenticated encryption algorithm with associated data as described
        /// <see href="http://tools.ietf.org/html/draft-mcgrew-aead-aes-cbc-hmac-sha2-05">here</see> .
        /// More specifically this implements AEAD_AES_256_CBC_HMAC_SHA256 algorithm.
        /// </summary>
        /// <param name="dekProperties"> Data Encryption Key properties</param>
        /// <param name="encryptionType"> Encryption type </param>
        /// <param name="encryptionKeyStoreProvider"> EncryptionKeyStoreProvider for wrapping and unwrapping </param>
        public MdeEncryptionAlgorithm(
            DataEncryptionKeyProperties dekProperties,
            Data.Encryption.Cryptography.EncryptionType encryptionType,
            EncryptionKeyStoreProvider encryptionKeyStoreProvider,
            TimeSpan?cacheTimeToLive)
        {
            if (dekProperties == null)
            {
                throw new ArgumentNullException(nameof(dekProperties));
            }

            if (encryptionKeyStoreProvider == null)
            {
                throw new ArgumentNullException(nameof(encryptionKeyStoreProvider));
            }

            KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                dekProperties.EncryptionKeyWrapMetadata.Name,
                dekProperties.EncryptionKeyWrapMetadata.Value,
                encryptionKeyStoreProvider);

            ProtectedDataEncryptionKey protectedDataEncryptionKey;

            if (cacheTimeToLive.HasValue)
            {
                // no caching
                if (cacheTimeToLive.Value == TimeSpan.Zero)
                {
                    protectedDataEncryptionKey = new ProtectedDataEncryptionKey(
                        dekProperties.Id,
                        keyEncryptionKey,
                        dekProperties.WrappedDataEncryptionKey);
                }
                else
                {
                    protectedDataEncryptionKey = ProtectedDataEncryptionKey.GetOrCreate(
                        dekProperties.Id,
                        keyEncryptionKey,
                        dekProperties.WrappedDataEncryptionKey);

                    protectedDataEncryptionKey.TimeToLive = cacheTimeToLive.Value;
                }
            }
            else
            {
                protectedDataEncryptionKey = ProtectedDataEncryptionKey.GetOrCreate(
                    dekProperties.Id,
                    keyEncryptionKey,
                    dekProperties.WrappedDataEncryptionKey);
            }

            this.mdeAeadAes256CbcHmac256EncryptionAlgorithm = AeadAes256CbcHmac256EncryptionAlgorithm.GetOrCreate(
                protectedDataEncryptionKey,
                encryptionType);
        }
Esempio n. 6
0
        protected IList <FileEncryptionSettings> LoadFileEncryptionSettings(DataProtectionConfig config, bool encrypted)
        {
            List <FileEncryptionSettings> encryptionSettings = new List <FileEncryptionSettings>();

            for (int i = 0; i < header.Length; i++)
            {
                ColumnEncryptionInfo encryptionInfo = config.ColumnEncryptionInfo.Where(x => x.ColumnName == header[i]).FirstOrDefault();

                if (encryptionInfo != null)
                {
                    string dekName = encryptionInfo.ColumnKeyName;

                    ColumnKeyInfo dekInfo  = config.ColumnKeyInfo.First(x => x.Name == encryptionInfo.ColumnKeyName);
                    byte[]        dekBytes = Converter.FromHexString(dekInfo.EncryptedColumnKey);

                    ColumnMasterKeyInfo kekInfo = config.ColumnMasterKeyInfo.First(x => x.Name == dekInfo.ColumnMasterKeyName);
                    KeyEncryptionKey    kek     = new KeyEncryptionKey(kekInfo.Name, kekInfo.KeyPath, azureKeyProvider);

                    EncryptionType encryptionType = EncryptionType.Plaintext;

                    if (encrypted)
                    {
                        if (encryptionInfo.EncryptionType.ToLower() == "randomized")
                        {
                            encryptionType = EncryptionType.Randomized;
                        }
                        else if (encryptionInfo.EncryptionType.ToLower() == "deterministic")
                        {
                            encryptionType = EncryptionType.Deterministic;
                        }
                        else
                        {
                            encryptionType = EncryptionType.Plaintext;
                        }
                    }

                    var encryptionSetting = new FileEncryptionSettings <string>(new ProtectedDataEncryptionKey(dekName, kek, dekBytes), encryptionType, new SqlVarCharSerializer(size: 255));
                    encryptionSettings.Add(encryptionSetting);
                }
                else
                {
                    if (defaultKEK == null)
                    {
                        ColumnMasterKeyInfo kekInfo = config.ColumnMasterKeyInfo.First();
                        KeyEncryptionKey    kek     = new KeyEncryptionKey(kekInfo.Name, kekInfo.KeyPath, azureKeyProvider);
                        defaultKEK = kek;
                    }

                    var encryptionSetting = new FileEncryptionSettings <string>(new ProtectedDataEncryptionKey("none", defaultKEK), EncryptionType.Plaintext, new SqlVarCharSerializer(size: 255));
                    encryptionSettings.Add(encryptionSetting);
                }
            }

            return(encryptionSettings);
        }
Esempio n. 7
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="Rest.ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (DiskEncryptionKey != null)
     {
         DiskEncryptionKey.Validate();
     }
     if (KeyEncryptionKey != null)
     {
         KeyEncryptionKey.Validate();
     }
 }
Esempio n. 8
0
        internal ProtectedDataEncryptionKey BuildProtectedDataEncryptionKey(
            ClientEncryptionKeyProperties clientEncryptionKeyProperties,
            EncryptionKeyStoreProvider encryptionKeyStoreProvider,
            string keyId)
        {
            KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                clientEncryptionKeyProperties.EncryptionKeyWrapMetadata.Name,
                clientEncryptionKeyProperties.EncryptionKeyWrapMetadata.Value,
                encryptionKeyStoreProvider);

            return(new ProtectedDataEncryptionKey(
                       keyId,
                       keyEncryptionKey,
                       clientEncryptionKeyProperties.WrappedDataEncryptionKey));
        }
        public void LazilyGenerateSignature()
        {
            const string masterKeyPath             = "Test_Path";
            const bool   masterKeyIsEnclaveEnabled = true;

            Mock <EncryptionKeyStoreProvider> mockKeyStoreProvider = new Mock <EncryptionKeyStoreProvider>();
            KeyEncryptionKey masterKey = new KeyEncryptionKey("Test_MK", "Test_Path", mockKeyStoreProvider.Object, masterKeyIsEnclaveEnabled);

            mockKeyStoreProvider.Verify(m => m.Sign(masterKeyPath, masterKeyIsEnclaveEnabled), Times.Never);

            byte[] signature = masterKey.Signature;
            mockKeyStoreProvider.Verify(m => m.Sign(masterKeyPath, masterKeyIsEnclaveEnabled), Times.Once);

            signature = masterKey.Signature;
            mockKeyStoreProvider.Verify(m => m.Sign(masterKeyPath, masterKeyIsEnclaveEnabled), Times.Once);
        }
Esempio n. 10
0
        public override Task <EncryptionKeyWrapResult> WrapKeyAsync(
            byte[] key,
            EncryptionKeyWrapMetadata metadata,
            CancellationToken cancellationToken)
        {
            if (metadata == null)
            {
                throw new ArgumentNullException(nameof(metadata));
            }

            KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                metadata.Name,
                metadata.Value,
                this.EncryptionKeyStoreProvider);

            byte[] result = keyEncryptionKey.EncryptEncryptionKey(key);
            return(Task.FromResult(new EncryptionKeyWrapResult(result, metadata)));
        }
Esempio n. 11
0
        private (byte[], EncryptionKeyWrapMetadata) GenerateAndWrapPdekForMdeEncAlgo(EncryptionKeyWrapMetadata encryptionKeyWrapMetadata)
        {
            if (this.DekProvider.MdeKeyWrapProvider == null)
            {
                throw new InvalidOperationException($"For use of '{CosmosEncryptionAlgorithm.MdeAeadAes256CbcHmac256Randomized}' algorithm, " +
                                                    "Encryptor or CosmosDataEncryptionKeyProvider needs to be initialized with EncryptionKeyStoreProvider.");
            }

            KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                encryptionKeyWrapMetadata.Name,
                encryptionKeyWrapMetadata.Value,
                this.DekProvider.MdeKeyWrapProvider.EncryptionKeyStoreProvider);

            ProtectedDataEncryptionKey protectedDataEncryptionKey = new ProtectedDataEncryptionKey(
                encryptionKeyWrapMetadata.Name,
                keyEncryptionKey);

            byte[] wrappedDek = protectedDataEncryptionKey.EncryptedValue;
            EncryptionKeyWrapMetadata updatedMetadata = encryptionKeyWrapMetadata;

            return(wrappedDek, updatedMetadata);
        }
Esempio n. 12
0
        public void CacheMasterKeyCorrectlyWhenCallingGetOrCreate()
        {
            Mock <EncryptionKeyStoreProvider> mockKeyStoreProvider1 = new Mock <EncryptionKeyStoreProvider>();
            Mock <EncryptionKeyStoreProvider> mockKeyStoreProvider2 = new Mock <EncryptionKeyStoreProvider>();


            KeyEncryptionKey encryptionkey1 = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path"), mockKeyStoreProvider1.Object, true);
            KeyEncryptionKey encryptionkey2 = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path"), mockKeyStoreProvider1.Object, true);

            Assert.Same(encryptionkey1, encryptionkey2);

            KeyEncryptionKey encryptionkey3 = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path"), mockKeyStoreProvider1.Object, true);
            KeyEncryptionKey encryptionkey4 = KeyEncryptionKey.GetOrCreate(new string("Test_MK_Other"), new string("Test_Path"), mockKeyStoreProvider1.Object, true);

            Assert.NotSame(encryptionkey3, encryptionkey4);

            KeyEncryptionKey encryptionkey5 = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path"), mockKeyStoreProvider1.Object, true);
            KeyEncryptionKey encryptionkey6 = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path_Other"), mockKeyStoreProvider1.Object, true);

            Assert.NotSame(encryptionkey5, encryptionkey6);

            KeyEncryptionKey encryptionkey7 = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path"), mockKeyStoreProvider1.Object, true);
            KeyEncryptionKey encryptionkey8 = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path"), mockKeyStoreProvider2.Object, true);

            Assert.NotSame(encryptionkey7, encryptionkey8);

            KeyEncryptionKey encryptionkey9  = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path"), mockKeyStoreProvider1.Object, true);
            KeyEncryptionKey encryptionkey10 = KeyEncryptionKey.GetOrCreate(new string("Test_MK"), new string("Test_Path"), mockKeyStoreProvider1.Object, false);

            Assert.NotSame(encryptionkey9, encryptionkey10);

            KeyEncryptionKey encryptionkey11 = KeyEncryptionKey.GetOrCreate(new string("Test_MK_Other"), new string("Test_Path_Other"), mockKeyStoreProvider2.Object, false);
            KeyEncryptionKey encryptionkey12 = KeyEncryptionKey.GetOrCreate(new string("Test_MK_Other"), new string("Test_Path_Other"), mockKeyStoreProvider2.Object, false);

            Assert.Same(encryptionkey11, encryptionkey12);
        }
Esempio n. 13
0
        public void UpdateSystemAssignedToUserAssigned()
        {
            var resourceGroupName = TestUtilities.GenerateName("SdkRg");
            var jobName           = TestUtilities.GenerateName("SdkJob");
            //var jobName = "SdkJob5929";
            ContactDetails  contactDetails          = GetDefaultContactDetails();
            ShippingAddress shippingAddress         = GetDefaultShippingAddress();
            Sku             sku                     = GetDefaultSku();
            var             destinationAccountsList = new List <StorageAccountDetails>
            {
                new StorageAccountDetails
                {
                    StorageAccountId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/databoxbvt1/providers/Microsoft.Storage/storageAccounts/databoxbvttestaccount2"
                }
            };
            JobDetails jobDetails = new DataBoxJobDetails
            {
                ContactDetails  = contactDetails,
                ShippingAddress = shippingAddress
            };

            jobDetails.DataImportDetails = new List <DataImportDetails>();
            jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault()));

            var jobResource = new JobResource
            {
                Sku      = sku,
                Location = TestConstants.DefaultResourceLocation,
                Details  = jobDetails,
            };

            this.RMClient.ResourceGroups.CreateOrUpdate(
                resourceGroupName,
                new ResourceGroup
            {
                Location = TestConstants.DefaultResourceLocation
            });

            var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource);

            ValidateJobWithoutDetails(jobName, sku, job);
            Assert.Equal(StageName.DeviceOrdered, job.Status);

            // Set Msi details.
            string tenantId     = "72f988bf-86f1-41af-91ab-2d7cd011db47";
            string identityType = "SystemAssigned";
            var    identity     = new ResourceIdentity(identityType, Guid.NewGuid().ToString(), tenantId);
            var    updateParams = new JobResourceUpdateParameter
            {
                Identity = identity
            };

            var updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams);

            ValidateJobWithoutDetails(jobName, sku, updateJob);

            var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details);

            ValidateJobWithoutDetails(jobName, sku, job);
            ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled);

            Assert.Equal(StageName.DeviceOrdered, updateJob.Status);
            Assert.Equal(identityType, updateJob.Identity.Type);

            //Updating to User Assigned
            var uaiId            = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.ManagedIdentity/userAssignedIdentities/sdkIdentity";
            var keyEncryptionKey = new KeyEncryptionKey(KekType.CustomerManaged)
            {
                KekUrl             = @"https://sdkkeyvault.vault.azure.net/keys/SSDKEY/",
                KekVaultResourceID =
                    "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.KeyVault/vaults/SDKKeyVault",
                IdentityProperties = new IdentityProperties
                {
                    Type         = "UserAssigned",
                    UserAssigned = new UserAssignedProperties {
                        ResourceId = uaiId
                    }
                }
            };

            UserAssignedIdentity uid = new UserAssignedIdentity();

            identity = new ResourceIdentity//ResourceIdentity checked by auto mapper
            {
                Type = "SystemAssigned,UserAssigned",
                UserAssignedIdentities = new Dictionary <string, UserAssignedIdentity>
                {
                    { uaiId, uid }
                },
            };

            var details = new UpdateJobDetails
            {
                KeyEncryptionKey = keyEncryptionKey
            };

            updateParams = new JobResourceUpdateParameter
            {
                Details  = details,
                Identity = identity
            };

            updateJob = this.Client.Jobs.Update(resourceGroupName, jobName, updateParams);
            ValidateJobWithoutDetails(jobName, sku, updateJob);
            getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details);
            ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled);
            Assert.Equal(StageName.DeviceOrdered, getJob.Status);
            Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].ClientId));
            Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].PrincipalId));
        }
Esempio n. 14
0
        /// <summary>
        /// Create a Client Encryption Key used to Encrypt data.
        /// </summary>
        /// <param name="database">Regular cosmos database.</param>
        /// <param name="clientEncryptionKeyId"> Client Encryption Key id.</param>
        /// <param name="dataEncryptionKeyAlgorithm"> Encryption Algorthm. </param>
        /// <param name="encryptionKeyWrapMetadata"> EncryptionKeyWrapMetadata.</param>
        /// <param name="cancellationToken"> cancellation token </param>
        /// <returns>Container to perform operations supporting client-side encryption / decryption.</returns>
        /// <example>
        /// This example shows how to create a new Client Encryption Key.
        ///
        /// <code language="c#">
        /// <![CDATA[
        /// ClientEncryptionKeyResponse response = await this.cosmosDatabase.CreateClientEncryptionKeyAsync(
        ///     "testKey",
        ///     DataEncryptionKeyAlgorithm.AEAD_AES_256_CBC_HMAC_SHA256,
        ///     new EncryptionKeyWrapMetadata("metadataName", "MetadataValue"));
        /// ]]>
        /// </code>
        /// </example>
        public static async Task <ClientEncryptionKeyResponse> CreateClientEncryptionKeyAsync(
            this Database database,
            string clientEncryptionKeyId,
            DataEncryptionKeyAlgorithm dataEncryptionKeyAlgorithm,
            EncryptionKeyWrapMetadata encryptionKeyWrapMetadata,
            CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (string.IsNullOrWhiteSpace(clientEncryptionKeyId))
            {
                throw new ArgumentNullException(nameof(clientEncryptionKeyId));
            }

            string encryptionAlgorithm = dataEncryptionKeyAlgorithm.ToString();

            if (!string.Equals(encryptionAlgorithm, DataEncryptionKeyAlgorithm.AEAD_AES_256_CBC_HMAC_SHA256.ToString()))
            {
                throw new ArgumentException($"Invalid Encryption Algorithm '{encryptionAlgorithm}' passed. Please refer to https://aka.ms/CosmosClientEncryption for more details. ");
            }

            if (encryptionKeyWrapMetadata == null)
            {
                throw new ArgumentNullException(nameof(encryptionKeyWrapMetadata));
            }

            EncryptionCosmosClient encryptionCosmosClient;

            if (database is EncryptionDatabase encryptionDatabase)
            {
                encryptionCosmosClient = encryptionDatabase.EncryptionCosmosClient;
            }
            else
            {
                throw new ArgumentException("Creating a ClientEncryptionKey resource requires the use of an encryption - enabled client. Please refer to https://aka.ms/CosmosClientEncryption for more details. ");
            }

            EncryptionKeyStoreProvider encryptionKeyStoreProvider = encryptionCosmosClient.EncryptionKeyStoreProvider;

            KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                encryptionKeyWrapMetadata.Name,
                encryptionKeyWrapMetadata.Value,
                encryptionKeyStoreProvider);

            ProtectedDataEncryptionKey protectedDataEncryptionKey = new ProtectedDataEncryptionKey(
                clientEncryptionKeyId,
                keyEncryptionKey);

            byte[] wrappedDataEncryptionKey = protectedDataEncryptionKey.EncryptedValue;

            ClientEncryptionKeyProperties clientEncryptionKeyProperties = new ClientEncryptionKeyProperties(
                clientEncryptionKeyId,
                encryptionAlgorithm,
                wrappedDataEncryptionKey,
                encryptionKeyWrapMetadata);

            ClientEncryptionKeyResponse clientEncryptionKeyResponse = await database.CreateClientEncryptionKeyAsync(
                clientEncryptionKeyProperties,
                cancellationToken : cancellationToken);

            return(clientEncryptionKeyResponse);
        }
Esempio n. 15
0
        /// <summary>
        /// Rewrap an existing Client Encryption Key.
        /// </summary>
        /// <param name="database">Regular cosmos database.</param>
        /// <param name="clientEncryptionKeyId"> Client Encryption Key id.</param>
        /// <param name="newEncryptionKeyWrapMetadata"> EncryptionKeyWrapMetadata.</param>
        /// <param name="cancellationToken"> cancellation token </param>
        /// <returns>Container to perform operations supporting client-side encryption / decryption.</returns>
        /// <example>
        /// This example shows how to rewrap a Client Encryption Key.
        ///
        /// <code language="c#">
        /// <![CDATA[
        /// ClientEncryptionKeyResponse response = await this.cosmosDatabase.RewrapClientEncryptionKeyAsync(
        ///     "keyToRewrap",
        ///     new EncryptionKeyWrapMetadata("metadataName", "UpdatedMetadataValue")));
        /// ]]>
        /// </code>
        /// </example>
        public static async Task <ClientEncryptionKeyResponse> RewrapClientEncryptionKeyAsync(
            this Database database,
            string clientEncryptionKeyId,
            EncryptionKeyWrapMetadata newEncryptionKeyWrapMetadata,
            CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (string.IsNullOrWhiteSpace(clientEncryptionKeyId))
            {
                throw new ArgumentNullException(nameof(clientEncryptionKeyId));
            }

            if (newEncryptionKeyWrapMetadata == null)
            {
                throw new ArgumentNullException(nameof(newEncryptionKeyWrapMetadata));
            }

            ClientEncryptionKey clientEncryptionKey = database.GetClientEncryptionKey(clientEncryptionKeyId);

            EncryptionCosmosClient encryptionCosmosClient;

            if (database is EncryptionDatabase encryptionDatabase)
            {
                encryptionCosmosClient = encryptionDatabase.EncryptionCosmosClient;
            }
            else
            {
                throw new ArgumentException("Rewraping a ClientEncryptionKey requires the use of an encryption - enabled client. Please refer to https://aka.ms/CosmosClientEncryption for more details. ");
            }

            EncryptionKeyStoreProvider encryptionKeyStoreProvider = encryptionCosmosClient.EncryptionKeyStoreProvider;

            ClientEncryptionKeyProperties clientEncryptionKeyProperties = await clientEncryptionKey.ReadAsync(cancellationToken : cancellationToken);

            RequestOptions requestOptions = new RequestOptions
            {
                IfMatchEtag = clientEncryptionKeyProperties.ETag,
            };

            KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                clientEncryptionKeyProperties.EncryptionKeyWrapMetadata.Name,
                clientEncryptionKeyProperties.EncryptionKeyWrapMetadata.Value,
                encryptionKeyStoreProvider);

            byte[] unwrappedKey = keyEncryptionKey.DecryptEncryptionKey(clientEncryptionKeyProperties.WrappedDataEncryptionKey);

            keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                newEncryptionKeyWrapMetadata.Name,
                newEncryptionKeyWrapMetadata.Value,
                encryptionKeyStoreProvider);

            byte[] rewrappedKey = keyEncryptionKey.EncryptEncryptionKey(unwrappedKey);

            clientEncryptionKeyProperties = new ClientEncryptionKeyProperties(
                clientEncryptionKeyId,
                clientEncryptionKeyProperties.EncryptionAlgorithm,
                rewrappedKey,
                newEncryptionKeyWrapMetadata);

            ClientEncryptionKeyResponse clientEncryptionKeyResponse = await clientEncryptionKey.ReplaceAsync(
                clientEncryptionKeyProperties,
                requestOptions,
                cancellationToken : cancellationToken);

            return(clientEncryptionKeyResponse);
        }
Esempio n. 16
0
        /// <summary>
        /// Creates a client encryption key.
        /// This generates a cryptographically random data encryption key, wraps it using
        /// information provided in the encryptionKeyWrapMetadata using the IKeyEncryptionKeyResolver instance configured on the client,
        /// and saves the wrapped data encryption key along with the encryptionKeyWrapMetadata at the Cosmos DB service.
        /// </summary>
        /// <param name="database">Database supporting encryption in which the client encryption key properties will be saved.</param>
        /// <param name="clientEncryptionKeyId">Identifier for the client encryption key.</param>
        /// <param name="encryptionAlgorithm">Algorithm which will be used for encryption with this key.</param>
        /// <param name="encryptionKeyWrapMetadata">Metadata used to wrap the data encryption key with a key encryption key.</param>
        /// <param name="cancellationToken">Token for request cancellation.</param>
        /// <returns>Response from the Cosmos DB service with <see cref="ClientEncryptionKeyProperties"/>.</returns>
        /// <example>
        /// This example shows how to create a client encryption key.
        ///
        /// <code language="c#">
        /// <![CDATA[
        /// Azure.Core.TokenCredential tokenCredential = new Azure.Identity.DefaultAzureCredential();
        /// Azure.Core.Cryptography.IKeyEncryptionKeyResolver keyResolver = new Azure.Security.KeyVault.Keys.Cryptography.KeyResolver(tokenCredential);
        /// CosmosClient client = (new CosmosClient(endpoint, authKey)).WithEncryption(keyResolver, KeyEncryptionKeyResolverName.AzureKeyVault);
        ///
        /// EncryptionKeyWrapMetadata wrapMetadata = new EncryptionKeyWrapMetadata(
        ///    type: KeyEncryptionKeyResolverName.AzureKeyVault,
        ///    name: "myKek",
        ///    value: "https://contoso.vault.azure.net/keys/myKek/78deebed173b48e48f55abf87ed4cf71",
        ///    algorithm: Azure.Security.KeyVault.Keys.Cryptography.EncryptionAlgorithm.RsaOaep.ToString());
        ///
        ///  ClientEncryptionKeyResponse response = await client.GetDatabase("databaseId").CreateClientEncryptionKeyAsync(
        ///    "myCek",
        ///    DataEncryptionAlgorithm.AeadAes256CbcHmacSha256,
        ///    wrapMetadata);
        /// ]]>
        /// </code>
        /// </example>
        /// <remarks>
        /// See <see href="https://aka.ms/CosmosClientEncryption">client-side encryption documentation</see> for more details.
        /// </remarks>
        public static async Task <ClientEncryptionKeyResponse> CreateClientEncryptionKeyAsync(
            this Database database,
            string clientEncryptionKeyId,
            string encryptionAlgorithm,
            EncryptionKeyWrapMetadata encryptionKeyWrapMetadata,
            CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (string.IsNullOrWhiteSpace(clientEncryptionKeyId))
            {
                throw new ArgumentNullException(nameof(clientEncryptionKeyId));
            }

            if (!string.Equals(encryptionAlgorithm, DataEncryptionAlgorithm.AeadAes256CbcHmacSha256))
            {
                throw new ArgumentException($"Invalid encryption algorithm '{encryptionAlgorithm}' passed. Please refer to https://aka.ms/CosmosClientEncryption for more details.");
            }

            if (encryptionKeyWrapMetadata == null)
            {
                throw new ArgumentNullException(nameof(encryptionKeyWrapMetadata));
            }

            if (encryptionKeyWrapMetadata.Algorithm != EncryptionKeyStoreProviderImpl.RsaOaepWrapAlgorithm)
            {
                throw new ArgumentException($"Invalid key wrap algorithm '{encryptionKeyWrapMetadata.Algorithm}' passed. Please refer to https://aka.ms/CosmosClientEncryption for more details.");
            }

            EncryptionCosmosClient encryptionCosmosClient = database is EncryptionDatabase encryptionDatabase
                ? encryptionDatabase.EncryptionCosmosClient
                : throw new ArgumentException("Creating a client encryption key requires the use of an encryption-enabled client. Please refer to https://aka.ms/CosmosClientEncryption for more details.");

            if (!string.Equals(encryptionKeyWrapMetadata.Type, encryptionCosmosClient.KeyEncryptionKeyResolverName))
            {
                throw new ArgumentException($"The Type of the EncryptionKeyWrapMetadata '{encryptionKeyWrapMetadata.Type}' does not match"
                                            + $" with the keyEncryptionKeyResolverName '{encryptionCosmosClient.KeyEncryptionKeyResolverName}' configured."
                                            + " Please refer to https://aka.ms/CosmosClientEncryption for more details.");
            }

            KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                encryptionKeyWrapMetadata.Name,
                encryptionKeyWrapMetadata.Value,
                encryptionCosmosClient.EncryptionKeyStoreProviderImpl);

            ProtectedDataEncryptionKey protectedDataEncryptionKey = new ProtectedDataEncryptionKey(
                clientEncryptionKeyId,
                keyEncryptionKey);

            byte[] wrappedDataEncryptionKey = protectedDataEncryptionKey.EncryptedValue;

            // cache it.
            ProtectedDataEncryptionKey.GetOrCreate(
                clientEncryptionKeyId,
                keyEncryptionKey,
                wrappedDataEncryptionKey);

            ClientEncryptionKeyProperties clientEncryptionKeyProperties = new ClientEncryptionKeyProperties(
                clientEncryptionKeyId,
                encryptionAlgorithm,
                wrappedDataEncryptionKey,
                encryptionKeyWrapMetadata);

            ClientEncryptionKeyResponse clientEncryptionKeyResponse = await database.CreateClientEncryptionKeyAsync(
                clientEncryptionKeyProperties,
                cancellationToken : cancellationToken);

            return(clientEncryptionKeyResponse);
        }
Esempio n. 17
0
        /// <summary>
        /// Rewraps a client encryption key.
        /// This wraps the existing data encryption key using information provided in the newEncryptionKeyWrapMetadata
        /// using the IKeyEncryptionKeyResolver instance configured on the client,
        /// and saves the wrapped data encryption key along with the newEncryptionKeyWrapMetadata at the Cosmos DB service.
        /// </summary>
        /// <param name="database">Database supporting encryption in which the client encryption key properties will be updated.</param>
        /// <param name="clientEncryptionKeyId">Identifier for the client encryption key.</param>
        /// <param name="newEncryptionKeyWrapMetadata">Metadata used to wrap the data encryption key with a key encryption key.</param>
        /// <param name="cancellationToken">Token for request cancellation.</param>
        /// <returns>Response from the Cosmos DB service with updated <see cref="ClientEncryptionKeyProperties"/>.</returns>
        /// <example>
        /// This example shows how to rewrap a client encryption key.
        ///
        /// <code language="c#">
        /// <![CDATA[
        /// Azure.Core.TokenCredential tokenCredential = new Azure.Identity.DefaultAzureCredential();
        /// Azure.Core.Cryptography.IKeyEncryptionKeyResolver keyResolver = new Azure.Security.KeyVault.Keys.Cryptography.KeyResolver(tokenCredential);
        /// CosmosClient client = (new CosmosClient(endpoint, authKey)).WithEncryption(keyResolver, KeyEncryptionKeyResolverName.AzureKeyVault);
        ///
        /// EncryptionKeyWrapMetadata wrapMetadataForNewKeyVersion = new EncryptionKeyWrapMetadata(
        ///    type: KeyEncryptionKeyResolverName.AzureKeyVault,
        ///    name: "myKek",
        ///    value: "https://contoso.vault.azure.net/keys/myKek/0698c2156c1a4e1da5b6bab6f6422fd6",
        ///    algorithm: Azure.Security.KeyVault.Keys.Cryptography.EncryptionAlgorithm.RsaOaep.ToString());
        ///
        ///  ClientEncryptionKeyResponse response = await client.GetDatabase("databaseId").RewrapClientEncryptionKeyAsync(
        ///    "myCek",
        ///    wrapMetadataForNewKeyVersion);
        /// ]]>
        /// </code>
        /// </example>
        /// <remarks>
        /// See <see href="https://aka.ms/CosmosClientEncryption">client-side encryption documentation</see> for more details.
        /// </remarks>
        public static async Task <ClientEncryptionKeyResponse> RewrapClientEncryptionKeyAsync(
            this Database database,
            string clientEncryptionKeyId,
            EncryptionKeyWrapMetadata newEncryptionKeyWrapMetadata,
            CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();

            if (string.IsNullOrWhiteSpace(clientEncryptionKeyId))
            {
                throw new ArgumentNullException(nameof(clientEncryptionKeyId));
            }

            if (newEncryptionKeyWrapMetadata == null)
            {
                throw new ArgumentNullException(nameof(newEncryptionKeyWrapMetadata));
            }

            if (newEncryptionKeyWrapMetadata.Algorithm != EncryptionKeyStoreProviderImpl.RsaOaepWrapAlgorithm)
            {
                throw new ArgumentException($"Invalid key wrap algorithm '{newEncryptionKeyWrapMetadata.Algorithm}' passed. Please refer to https://aka.ms/CosmosClientEncryption for more details.");
            }

            ClientEncryptionKey clientEncryptionKey = database.GetClientEncryptionKey(clientEncryptionKeyId);

            EncryptionCosmosClient encryptionCosmosClient = database is EncryptionDatabase encryptionDatabase
                ? encryptionDatabase.EncryptionCosmosClient
                : throw new ArgumentException("Rewrapping a client encryption key requires the use of an encryption-enabled client. Please refer to https://aka.ms/CosmosClientEncryption for more details.");

            if (!string.Equals(newEncryptionKeyWrapMetadata.Type, encryptionCosmosClient.KeyEncryptionKeyResolverName))
            {
                throw new ArgumentException($"The Type of the EncryptionKeyWrapMetadata '{newEncryptionKeyWrapMetadata.Type}' does not match"
                                            + $" with the keyEncryptionKeyResolverName '{encryptionCosmosClient.KeyEncryptionKeyResolverName}' configured."
                                            + " Please refer to https://aka.ms/CosmosClientEncryption for more details.");
            }

            ClientEncryptionKeyProperties clientEncryptionKeyProperties = await clientEncryptionKey.ReadAsync(cancellationToken : cancellationToken);

            RequestOptions requestOptions = new RequestOptions
            {
                IfMatchEtag = clientEncryptionKeyProperties.ETag,
            };

            KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                clientEncryptionKeyProperties.EncryptionKeyWrapMetadata.Name,
                clientEncryptionKeyProperties.EncryptionKeyWrapMetadata.Value,
                encryptionCosmosClient.EncryptionKeyStoreProviderImpl);

            byte[] unwrappedKey = keyEncryptionKey.DecryptEncryptionKey(clientEncryptionKeyProperties.WrappedDataEncryptionKey);

            keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
                newEncryptionKeyWrapMetadata.Name,
                newEncryptionKeyWrapMetadata.Value,
                encryptionCosmosClient.EncryptionKeyStoreProviderImpl);

            byte[] rewrappedKey = keyEncryptionKey.EncryptEncryptionKey(unwrappedKey);

            clientEncryptionKeyProperties = new ClientEncryptionKeyProperties(
                clientEncryptionKeyId,
                clientEncryptionKeyProperties.EncryptionAlgorithm,
                rewrappedKey,
                newEncryptionKeyWrapMetadata);

            ClientEncryptionKeyResponse clientEncryptionKeyResponse = await clientEncryptionKey.ReplaceAsync(
                clientEncryptionKeyProperties,
                requestOptions,
                cancellationToken : cancellationToken);

            return(clientEncryptionKeyResponse);
        }
Esempio n. 18
0
        public void CreateJobWithUserAssignedIdentity()
        {
            var resourceGroupName = TestUtilities.GenerateName("SdkRg");
            var jobName           = TestUtilities.GenerateName("SdkJob");
            //var jobName = "SdkJob5929";
            ContactDetails  contactDetails          = GetDefaultContactDetails();
            ShippingAddress shippingAddress         = GetDefaultShippingAddress();
            Sku             sku                     = GetDefaultSku();
            var             destinationAccountsList = new List <StorageAccountDetails>
            {
                new StorageAccountDetails
                {
                    StorageAccountId = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/databoxbvt1/providers/Microsoft.Storage/storageAccounts/databoxbvttestaccount2"
                }
            };

            var uaiId      = "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.ManagedIdentity/userAssignedIdentities/sdkIdentity";
            var kekDetails = new KeyEncryptionKey(KekType.CustomerManaged)
            {
                KekType            = KekType.CustomerManaged,
                KekUrl             = @"https://sdkkeyvault.vault.azure.net/keys/SSDKEY/",
                KekVaultResourceID =
                    "/subscriptions/fa68082f-8ff7-4a25-95c7-ce9da541242f/resourceGroups/akvenkat/providers/Microsoft.KeyVault/vaults/SDKKeyVault",
                IdentityProperties = new IdentityProperties
                {
                    Type         = "UserAssigned",
                    UserAssigned = new UserAssignedProperties {
                        ResourceId = uaiId
                    }
                }
            };
            JobDetails jobDetails = new DataBoxJobDetails(contactDetails,
                                                          default(IList <JobStages>), shippingAddress, default(PackageShippingDetails),
                                                          default(PackageShippingDetails), default(IList <DataImportDetails>),
                                                          default(IList <DataExportDetails>), default(Preferences),
                                                          default(IList <CopyLogDetails>), default(string), default(string),
                                                          kekDetails);

            jobDetails.DataImportDetails = new List <DataImportDetails>();
            jobDetails.DataImportDetails.Add(new DataImportDetails(destinationAccountsList.FirstOrDefault()));

            var jobResource = new JobResource
            {
                Sku      = sku,
                Location = TestConstants.DefaultResourceLocation,
                Details  = jobDetails,
            };


            UserAssignedIdentity uid = new UserAssignedIdentity();
            var identity             = new ResourceIdentity//ResourceIdentity checked by auto mapper
            {
                Type = "UserAssigned",
                UserAssignedIdentities = new Dictionary <string, UserAssignedIdentity>
                {
                    { uaiId, uid }
                },
            };

            jobResource.Identity = identity;

            this.RMClient.ResourceGroups.CreateOrUpdate(
                resourceGroupName,
                new ResourceGroup
            {
                Location = TestConstants.DefaultResourceLocation
            });

            var job = this.Client.Jobs.Create(resourceGroupName, jobName, jobResource);

            ValidateJobWithoutDetails(jobName, sku, job);
            Assert.Equal(StageName.DeviceOrdered, job.Status);
            String iden = "UserAssigned";

            Assert.Equal(iden, job.Identity.Type);
            var getJob = this.Client.Jobs.Get(resourceGroupName, jobName, TestConstants.Details);

            ValidateJobWithoutDetails(jobName, sku, getJob);
            ValidateJobDetails(contactDetails, shippingAddress, getJob, JobDeliveryType.NonScheduled);
            Assert.Equal(StageName.DeviceOrdered, getJob.Status);
            Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].ClientId));
            Assert.True(!string.IsNullOrEmpty(getJob.Identity.UserAssignedIdentities[uaiId].PrincipalId));
            Assert.Equal(KekType.CustomerManaged, getJob.Details.KeyEncryptionKey.KekType);
        }