• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# KeyVault.SymmetricKey类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Microsoft.Azure.KeyVault.SymmetricKey的典型用法代码示例。如果您正苦于以下问题:C# SymmetricKey类的具体用法?C# SymmetricKey怎么用?C# SymmetricKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



SymmetricKey类属于Microsoft.Azure.KeyVault命名空间,在下文中一共展示了SymmetricKey类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: SetUpKeyVaultSecret

        /// <summary>
        /// Creates a secret in Azure Key Vault and returns its ID.
        /// </summary>
        /// <param name="secretName">The name of the secret to create.</param>
        /// <returns>The ID of the secret created.</returns>
        public static string SetUpKeyVaultSecret(string secretName)
        {
            KeyVaultClient cloudVault = new KeyVaultClient(GetAccessToken);
            string vaultUri = CloudConfigurationManager.GetSetting("VaultUri");

            try
            {
                // Delete the secret if it exists.
                cloudVault.DeleteSecretAsync(vaultUri, secretName).GetAwaiter().GetResult();
            }
            catch (KeyVaultClientException ex)
            {
                if (ex.Status != System.Net.HttpStatusCode.NotFound)
                {
                    Console.WriteLine("Unable to access the specified vault. Please confirm the KVClientId, KVClientKey, and VaultUri are valid in the app.config file.");
                    Console.WriteLine("Also ensure that the client ID has previously been granted full permissions for Key Vault secrets using the Set-AzureKeyVaultAccessPolicy command with the -PermissionsToSecrets parameter.");
                    Console.WriteLine("Press any key to exit");
                    Console.ReadLine();
                    throw;
                }
            }

            // Create a 256bit symmetric key and convert it to Base64.
            SymmetricKey symmetricKey = new SymmetricKey(secretName, SymmetricKey.KeySize256);
            string symmetricBytes = Convert.ToBase64String(symmetricKey.Key);

            // Store the Base64 of the key in the key vault. Note that the content-type of the secret must
            // be application/octet-stream or the KeyVaultKeyResolver will not load it as a key.
            Secret cloudSecret = cloudVault.SetSecretAsync(vaultUri, secretName, symmetricBytes, null, "application/octet-stream").GetAwaiter().GetResult();

            // Return the base identifier of the secret. This will be resolved to the current version of the secret.
            return cloudSecret.SecretIdentifier.BaseIdentifier;
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:38,代码来源:KeyVaultUtility.cs


示例2: CloudQueueAddUpdateEncryptedMessage

        public void CloudQueueAddUpdateEncryptedMessage()
        {
            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");
            RsaKey rsaKey = new RsaKey("asymencryptionkey");

            // Create the resolver to be used for unwrapping.
            DictionaryKeyResolver resolver = new DictionaryKeyResolver();
            resolver.Add(aesKey);
            resolver.Add(rsaKey);

            DoCloudQueueAddUpdateEncryptedMessage(aesKey, resolver);
            DoCloudQueueAddUpdateEncryptedMessage(rsaKey, resolver);
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:14,代码来源:CloudQueueMessageEncryptionTests.cs


示例3: TableEncryptingUnsupportedPropertiesShouldThrow

        public void TableEncryptingUnsupportedPropertiesShouldThrow()
        {
            // Insert Entity
            DynamicTableEntity ent = new DynamicTableEntity() { PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString() };
            ent.Properties.Add("foo2", new EntityProperty(string.Empty));
            ent.Properties.Add("fooint", new EntityProperty(1234));

            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            TableRequestOptions options = new TableRequestOptions()
            {
                EncryptionPolicy = new TableEncryptionPolicy(aesKey, null),

                EncryptionResolver = (pk, rk, propName) =>
                {
                    if (propName.StartsWith("foo"))
                    {
                        return true;
                    }

                    return false;
                }
            };

            StorageException e = TestHelper.ExpectedException<StorageException>(
                () => currentTable.Execute(TableOperation.Insert(ent), options, null),
                "Encrypting non-string properties should fail");
            Assert.IsInstanceOfType(e.InnerException, typeof(InvalidOperationException));

            ent.Properties.Remove("fooint");
            ent.Properties.Add("foo", null);

            e = TestHelper.ExpectedException<StorageException>(
                () => currentTable.Execute(TableOperation.Insert(ent), options, null),
                "Encrypting null properties should fail");
            Assert.IsInstanceOfType(e.InnerException, typeof(InvalidOperationException));
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:38,代码来源:TableEntityEncryptionTests.cs


示例4: DoTableOperationValidateEncryption

        private void DoTableOperationValidateEncryption(TablePayloadFormat format)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = format;

            // Insert Entity
            DynamicTableEntity ent = new DynamicTableEntity() { PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString() };
            ent.Properties.Add("encprop", new EntityProperty(String.Empty));
            ent.Properties.Add("encprop2", new EntityProperty(String.Empty));
            ent.Properties.Add("encprop3", new EntityProperty("bar"));
            ent.Properties.Add("notencprop", new EntityProperty(1234));

            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            TableRequestOptions uploadOptions = new TableRequestOptions()
            {
                PropertyResolver = (pk, rk, propName, propValue) =>
                {
                    if (propName == "notencprop")
                    {
                        return EdmType.Int32;
                    }

                    return (EdmType)0;
                },

                EncryptionPolicy = new TableEncryptionPolicy(aesKey, null),

                EncryptionResolver = (pk, rk, propName) =>
                {
                    if (propName.StartsWith("encprop"))
                    {
                        return true;
                    }

                    return false;
                }
            };

            currentTable.Execute(TableOperation.Insert(ent), uploadOptions, null);

            TableRequestOptions downloadOptions = new TableRequestOptions()
            {
                PropertyResolver = (pk, rk, propName, propValue) =>
                {
                    if (propName == "notencprop")
                    {
                        return EdmType.Int32;
                    }

                    return (EdmType)0;
                }
            };

            // Retrieve Entity without decrypting
            TableOperation operation = TableOperation.Retrieve(ent.PartitionKey, ent.RowKey);
            Assert.IsFalse(operation.IsTableEntity);
            TableResult result = currentTable.Execute(operation, downloadOptions, null);

            DynamicTableEntity retrievedEntity = result.Result as DynamicTableEntity;
            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);

            // Properties having the same value should be encrypted to different values.
            if (format == TablePayloadFormat.JsonNoMetadata)
            {
                // With DTE and Json no metadata, if an encryption policy is not set, the client lib just reads the byte arrays as strings.
                Assert.AreNotEqual(retrievedEntity.Properties["encprop"].StringValue, retrievedEntity.Properties["encprop2"].StringValue);
            }
            else
            {
                CollectionAssert.AreNotEqual(retrievedEntity.Properties["encprop"].BinaryValue, retrievedEntity.Properties["encprop2"].BinaryValue);
                Assert.AreNotEqual(ent.Properties["encprop"].PropertyType, retrievedEntity.Properties["encprop"].PropertyType);
                Assert.AreNotEqual(ent.Properties["encprop2"].PropertyType, retrievedEntity.Properties["encprop2"].PropertyType);
                Assert.AreNotEqual(ent.Properties["encprop3"].PropertyType, retrievedEntity.Properties["encprop3"].PropertyType);
            }

            Assert.AreEqual(ent.Properties["notencprop"].Int32Value, retrievedEntity.Properties["notencprop"].Int32Value);
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:80,代码来源:TableEntityEncryptionTests.cs


示例5: DoTableBatchInsertOrReplaceEncryption

        private void DoTableBatchInsertOrReplaceEncryption(TablePayloadFormat format)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = format;

            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            TableRequestOptions options = new TableRequestOptions()
            {
                EncryptionPolicy = new TableEncryptionPolicy(aesKey, null),

                EncryptionResolver = (pk, rk, propName) =>
                {
                    if (propName == "A" || propName == "B")
                    {
                        return true;
                    }

                    return false;
                }
            };

            // Insert Or Replace with no pre-existing entity
            DynamicTableEntity insertOrReplaceEntity = new DynamicTableEntity("insertOrReplace entity", "foo" + format.ToString());
            insertOrReplaceEntity.Properties.Add("A", new EntityProperty("a"));

            TableBatchOperation batch = new TableBatchOperation();
            batch.InsertOrReplace(insertOrReplaceEntity);
            currentTable.ExecuteBatch(batch, options);

            // Retrieve Entity & Verify Contents
            // Create the resolver to be used for unwrapping.
            DictionaryKeyResolver resolver = new DictionaryKeyResolver();
            resolver.Add(aesKey);

            TableRequestOptions retrieveOptions = new TableRequestOptions() { EncryptionPolicy = new TableEncryptionPolicy(null, resolver) };
            TableResult result = currentTable.Execute(TableOperation.Retrieve(insertOrReplaceEntity.PartitionKey, insertOrReplaceEntity.RowKey), retrieveOptions);
            DynamicTableEntity retrievedEntity = result.Result as DynamicTableEntity;
            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(insertOrReplaceEntity.Properties.Count, retrievedEntity.Properties.Count);

            DynamicTableEntity replaceEntity = new DynamicTableEntity(insertOrReplaceEntity.PartitionKey, insertOrReplaceEntity.RowKey);
            replaceEntity.Properties.Add("B", new EntityProperty("b"));

            TableBatchOperation batch2 = new TableBatchOperation();
            batch2.InsertOrReplace(replaceEntity);
            currentTable.ExecuteBatch(batch2, options);

            // Retrieve Entity & Verify Contents
            result = currentTable.Execute(TableOperation.Retrieve(insertOrReplaceEntity.PartitionKey, insertOrReplaceEntity.RowKey), retrieveOptions);
            retrievedEntity = result.Result as DynamicTableEntity;
            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(1, retrievedEntity.Properties.Count);
            Assert.AreEqual(replaceEntity.Properties["B"], retrievedEntity.Properties["B"]);
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:55,代码来源:TableEntityEncryptionTests.cs


示例6: DoTableQueryDTEProjectionEncryption

        private void DoTableQueryDTEProjectionEncryption(TablePayloadFormat format, SymmetricKey aesKey)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = format;

            // Create the resolver to be used for unwrapping.
            DictionaryKeyResolver resolver = new DictionaryKeyResolver();
            resolver.Add(aesKey);

            TableRequestOptions options = new TableRequestOptions() { EncryptionPolicy = new TableEncryptionPolicy(null, resolver) };

            TableQuery query = new TableQuery().Select(new List<string>() { "A" });

            foreach (DynamicTableEntity ent in currentTable.ExecuteQuery(query, options))
            {
                Assert.IsNotNull(ent.PartitionKey);
                Assert.IsNotNull(ent.RowKey);
                Assert.IsNotNull(ent.Timestamp);

                Assert.IsTrue(ent.Properties["A"].StringValue == "a" || ent.Properties["A"].StringValue == String.Empty);
            }
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:21,代码来源:TableEntityEncryptionTests.cs


示例7: TableQueryProjectionEncryptionNoSelect

        public void TableQueryProjectionEncryptionNoSelect()
        {
            // Insert Entity
            EncryptedBaseEntity ent1 = new EncryptedBaseEntity() { PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString() };
            ent1.Populate();

            EncryptedBaseEntity ent2 = new EncryptedBaseEntity() { PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString() };
            ent2.Populate();

            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            TableRequestOptions options = new TableRequestOptions() { EncryptionPolicy = new TableEncryptionPolicy(aesKey, null) };
            currentTable.Execute(TableOperation.Insert(ent1), options, null);
            currentTable.Execute(TableOperation.Insert(ent2), options, null);

            tableClient.DefaultRequestOptions.PayloadFormat = TablePayloadFormat.Json;

            // Create the resolver to be used for unwrapping.
            DictionaryKeyResolver resolver = new DictionaryKeyResolver();
            resolver.Add(aesKey);
            TableEncryptionPolicy encryptionPolicy = new TableEncryptionPolicy(null, resolver);

            IEnumerable<EncryptedBaseEntity> entities = null;
            CloudTableClient encryptingTableClient = new CloudTableClient(this.tableClient.StorageUri, this.tableClient.Credentials);
            encryptingTableClient.DefaultRequestOptions.EncryptionPolicy = encryptionPolicy;
            encryptingTableClient.DefaultRequestOptions.RequireEncryption = true;

            entities = encryptingTableClient.GetTableReference(currentTable.Name).CreateQuery<EncryptedBaseEntity>().Select(ent => ent);

            foreach (EncryptedBaseEntity ent in entities)
            {
                ent.Validate();
            }
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:35,代码来源:TableEntityEncryptionTests.cs


示例8: TableQueryPOCOProjectionEncryption

        public void TableQueryPOCOProjectionEncryption()
        {
            // Insert Entity
            EncryptedBaseEntity ent1 = new EncryptedBaseEntity() { PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString() };
            ent1.Populate();

            EncryptedBaseEntity ent2 = new EncryptedBaseEntity() { PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString() };
            ent2.Populate();

            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            TableRequestOptions options = new TableRequestOptions() { EncryptionPolicy = new TableEncryptionPolicy(aesKey, null) };
            currentTable.Execute(TableOperation.Insert(ent1), options, null);
            currentTable.Execute(TableOperation.Insert(ent2), options, null);

            // Query with different payload formats.
            DoTableQueryPOCOProjectionEncryption(TablePayloadFormat.Json, aesKey);
            DoTableQueryPOCOProjectionEncryption(TablePayloadFormat.JsonNoMetadata, aesKey);
            DoTableQueryPOCOProjectionEncryption(TablePayloadFormat.JsonFullMetadata, aesKey);
            DoTableQueryPOCOProjectionEncryption(TablePayloadFormat.AtomPub, aesKey);
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:22,代码来源:TableEntityEncryptionTests.cs


示例9: CloudBlockBlobEncryptionValidateWrappers

        public void CloudBlockBlobEncryptionValidateWrappers()
        {
            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");
            RsaKey rsaKey = new RsaKey("asymencryptionkey");

            // Create the resolver to be used for unwrapping.
            DictionaryKeyResolver resolver = new DictionaryKeyResolver();
            resolver.Add(aesKey);
            resolver.Add(rsaKey);

            DoCloudBlockBlobEncryptionValidateWrappers(aesKey, resolver);
            DoCloudBlockBlobEncryptionValidateWrappers(rsaKey, resolver);
        }
开发者ID:renlesterdg,项目名称:azure-storage-net,代码行数:14,代码来源:BlobEncryptionTests.cs


示例10: CloudBlobEncryptionWithText

        public void CloudBlobEncryptionWithText()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();
                string data = "String data";

                CloudBlockBlob blob = container.GetBlockBlobReference("blockblob");

                // Create the Key to be used for wrapping.
                SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

                // Create the resolver to be used for unwrapping.
                DictionaryKeyResolver resolver = new DictionaryKeyResolver();
                resolver.Add(aesKey);

                // Create the encryption policy to be used for upload.
                BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(aesKey, null);

                // Set the encryption policy on the request options.
                BlobRequestOptions uploadOptions = new BlobRequestOptions() { EncryptionPolicy = uploadPolicy };

                // Upload the encrypted contents to the blob.
                blob.UploadText(data, null, null, uploadOptions, null);

                // Download the encrypted blob.
                // Create the decryption policy to be used for download. There is no need to specify the
                // key when the policy is only going to be used for downloads. Resolver is sufficient.
                BlobEncryptionPolicy downloadPolicy = new BlobEncryptionPolicy(null, resolver);

                // Set the decryption policy on the request options.
                BlobRequestOptions downloadOptions = new BlobRequestOptions() { EncryptionPolicy = downloadPolicy };

                // Download and decrypt the encrypted contents from the blob.
                string outputData = blob.DownloadText(null, null, downloadOptions, null);

                // Compare that the decrypted contents match the input data.
                Assert.AreEqual(data, outputData);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
开发者ID:renlesterdg,项目名称:azure-storage-net,代码行数:46,代码来源:BlobEncryptionTests.cs


示例11: CloudBlobEncryptionWithByteArray

        public void CloudBlobEncryptionWithByteArray()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();
                int size = 5 * 1024 * 1024;
                byte[] buffer = GetRandomBuffer(size);
                byte[] outputBuffer = new byte[size];

                CloudBlockBlob blob = container.GetBlockBlobReference("blockblob");

                // Create the Key to be used for wrapping.
                SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

                // Create the resolver to be used for unwrapping.
                DictionaryKeyResolver resolver = new DictionaryKeyResolver();
                resolver.Add(aesKey);

                // Create the encryption policy to be used for upload.
                BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(aesKey, null);

                // Set the encryption policy on the request options.
                BlobRequestOptions uploadOptions = new BlobRequestOptions() { EncryptionPolicy = uploadPolicy };

                // Upload the encrypted contents to the blob.
                blob.UploadFromByteArray(buffer, 0, buffer.Length, null, uploadOptions, null);

                // Download the encrypted blob.
                // Create the decryption policy to be used for download. There is no need to specify the
                // key when the policy is only going to be used for downloads. Resolver is sufficient.
                BlobEncryptionPolicy downloadPolicy = new BlobEncryptionPolicy(null, resolver);

                // Set the decryption policy on the request options.
                BlobRequestOptions downloadOptions = new BlobRequestOptions() { EncryptionPolicy = downloadPolicy };

                // Download and decrypt the encrypted contents from the blob.
                blob.DownloadToByteArray(outputBuffer, 0, null, downloadOptions, null);

                // Compare that the decrypted contents match the input data.
                TestHelper.AssertBuffersAreEqual(buffer, outputBuffer);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
开发者ID:renlesterdg,项目名称:azure-storage-net,代码行数:48,代码来源:BlobEncryptionTests.cs


示例12: CloudBlobEncryptionWithFile

        public void CloudBlobEncryptionWithFile()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();
                int size = 5 * 1024 * 1024;
                byte[] buffer = GetRandomBuffer(size);

                CloudBlockBlob blob = container.GetBlockBlobReference("blockblob");

                // Create the Key to be used for wrapping.
                SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

                // Create the resolver to be used for unwrapping.
                DictionaryKeyResolver resolver = new DictionaryKeyResolver();
                resolver.Add(aesKey);

                // Create the encryption policy to be used for upload.
                BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(aesKey, null);

                // Set the encryption policy on the request options.
                BlobRequestOptions uploadOptions = new BlobRequestOptions() { EncryptionPolicy = uploadPolicy };

                string inputFileName = Path.GetTempFileName();
                string outputFileName = Path.GetTempFileName();

                using (FileStream file = new FileStream(inputFileName, FileMode.Create, FileAccess.Write))
                {
                    file.Write(buffer, 0, buffer.Length);
                }

                // Upload the encrypted contents to the blob.
                blob.UploadFromFile(inputFileName, FileMode.Open, null, uploadOptions, null);

                // Download the encrypted blob.
                // Create the decryption policy to be used for download. There is no need to specify the
                // key when the policy is only going to be used for downloads. Resolver is sufficient.
                BlobEncryptionPolicy downloadPolicy = new BlobEncryptionPolicy(null, resolver);

                // Set the decryption policy on the request options.
                BlobRequestOptions downloadOptions = new BlobRequestOptions() { EncryptionPolicy = downloadPolicy };

                // Download and decrypt the encrypted contents from the blob.
                blob.DownloadToFile(outputFileName, FileMode.Create, null, downloadOptions, null);

                // Compare that the decrypted contents match the input data.
                using (FileStream inputFileStream = new FileStream(inputFileName, FileMode.Open, FileAccess.Read),
                        outputFileStream = new FileStream(outputFileName, FileMode.Open, FileAccess.Read))
                {
                    TestHelper.AssertStreamsAreEqual(inputFileStream, outputFileStream);
                }
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
开发者ID:renlesterdg,项目名称:azure-storage-net,代码行数:59,代码来源:BlobEncryptionTests.cs


示例13: DoCloudBlobEncryptionAPM

        private static void DoCloudBlobEncryptionAPM(BlobType type, bool partial)
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();
                int size = 5 * 1024 * 1024;
                byte[] buffer = GetRandomBuffer(size);

                if (partial)
                {
                    size = 2 * 1024 * 1024;
                }

                ICloudBlob blob = GetCloudBlobReference(type, container);

                // Create the Key to be used for wrapping.
                SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

                // Create the resolver to be used for unwrapping.
                DictionaryKeyResolver resolver = new DictionaryKeyResolver();
                resolver.Add(aesKey);

                // Create the encryption policy to be used for upload.
                BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(aesKey, null);

                // Set the encryption policy on the request options.
                BlobRequestOptions uploadOptions = new BlobRequestOptions() { EncryptionPolicy = uploadPolicy };

                MemoryStream stream;
                // Upload the encrypted contents to the blob.
                using (stream = new MemoryStream(buffer))
                {
                    using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                    {
                        ICancellableAsyncResult result = blob.BeginUploadFromStream(
                                            stream, size, null, uploadOptions, null, ar => waitHandle.Set(), null);
                        waitHandle.WaitOne();
                        blob.EndUploadFromStream(result);
                    }

                    // Ensure that the user stream is open.
                    Assert.IsTrue(stream.CanSeek);
                }

                // Download the encrypted blob.
                // Create the decryption policy to be used for download. There is no need to specify the encryption mode 
                // and the key wrapper when the policy is only going to be used for downloads.
                BlobEncryptionPolicy downloadPolicy = new BlobEncryptionPolicy(null, resolver);

                // Set the decryption policy on the request options.
                BlobRequestOptions downloadOptions = new BlobRequestOptions() { EncryptionPolicy = downloadPolicy };

                // Download and decrypt the encrypted contents from the blob.
                MemoryStream outputStream = new MemoryStream();
                using (AutoResetEvent waitHandle = new AutoResetEvent(false))
                {
                    ICancellableAsyncResult result = blob.BeginDownloadToStream(outputStream, null, downloadOptions, null, ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    blob.EndDownloadToStream(result);
                }

                // Ensure that the user stream is open.
                outputStream.Seek(0, SeekOrigin.Begin);

                // Compare that the decrypted contents match the input data.
                byte[] outputArray = outputStream.ToArray();
                TestHelper.AssertBuffersAreEqualUptoIndex(outputArray, buffer, size - 1);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
开发者ID:renlesterdg,项目名称:azure-storage-net,代码行数:75,代码来源:BlobEncryptionTests.cs


示例14: CloudBlobEncryptionWithStrictModeOnPartialBlob

        public void CloudBlobEncryptionWithStrictModeOnPartialBlob()
        {
            CloudBlobContainer container = GetRandomContainerReference();

            int size = 5 * 1024 * 1024;
            byte[] buffer = GetRandomBuffer(size);

            ICloudBlob blob;
            MemoryStream stream = new MemoryStream(buffer);
            String blockId = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

            BlobRequestOptions options = new BlobRequestOptions()
            {
                RequireEncryption = true
            };

            blob = container.GetBlockBlobReference("blob1");
            try
            {
                ((CloudBlockBlob)blob).PutBlock(blockId, stream, null, null, options, null);
                Assert.Fail("PutBlock with RequireEncryption on should fail.");
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, SR.EncryptionPolicyMissingInStrictMode);
            }

            blob = container.GetPageBlobReference("blob1");
            try
            {
                ((CloudPageBlob)blob).WritePages(stream, 0, null, null, options, null);
                Assert.Fail("WritePages with RequireEncryption on should fail.");
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, SR.EncryptionPolicyMissingInStrictMode);
            }

            blob = container.GetAppendBlobReference("blob1");
            try
            {
                ((CloudAppendBlob)blob).AppendBlock(stream, null, null, options, null);
                Assert.Fail("AppendBlock with RequireEncryption on should fail.");
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, SR.EncryptionPolicyMissingInStrictMode);
            }

            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");
            options.EncryptionPolicy = new BlobEncryptionPolicy(aesKey, null);

            blob = container.GetBlockBlobReference("blob1");
            try
            {
                ((CloudBlockBlob)blob).PutBlock(blockId, stream, null, null, options, null);
                Assert.Fail("PutBlock with an EncryptionPolicy should fail.");
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, SR.EncryptionNotSupportedForOperation);
            }

            blob = container.GetPageBlobReference("blob1");
            try
            {
                ((CloudPageBlob)blob).WritePages(stream, 0, null, null, options, null);
                Assert.Fail("WritePages with an EncryptionPolicy should fail.");
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, SR.EncryptionNotSupportedForOperation);
            }

            blob = container.GetAppendBlobReference("blob1");
            try
            {
                ((CloudAppendBlob)blob).AppendBlock(stream, null, null, options, null);
                Assert.Fail("AppendBlock with an EncryptionPolicy should fail.");
            }
            catch (InvalidOperationException ex)
            {
                Assert.AreEqual(ex.Message, SR.EncryptionNotSupportedForOperation);
            }
        }
开发者ID:renlesterdg,项目名称:azure-storage-net,代码行数:86,代码来源:BlobEncryptionTests.cs


示例15: DoCloudBlobEncryptionWithStrictMode

        private void DoCloudBlobEncryptionWithStrictMode(BlobType type)
        {
            CloudBlobContainer container = GetRandomContainerReference();

            try
            {
                container.Create();
                int size = 5 * 1024 * 1024;
                byte[] buffer = GetRandomBuffer(size);

                ICloudBlob blob;

                if (type == BlobType.BlockBlob)
                {
                    blob = container.GetBlockBlobReference("blob1");
                }
                else
                {
                    blob = container.GetPageBlobReference("blob1");
                }

                // Create the Key to be used for wrapping.
                SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

                // Create the resolver to be used for unwrapping.
                DictionaryKeyResolver resolver = new DictionaryKeyResolver();
                resolver.Add(aesKey);

                // Create the encryption policy to be used for upload.
                BlobEncryptionPolicy uploadPolicy = new BlobEncryptionPolicy(aesKey, null);

                // Set the encryption policy on the request options.
                BlobRequestOptions uploadOptions = new BlobRequestOptions() { EncryptionPolicy = uploadPolicy };

                // Set RequireEncryption flag to true.
                uploadOptions.RequireEncryption = true;

                // Upload an encrypted blob with the policy set.
                MemoryStream stream = new MemoryStream(buffer);
                blob.UploadFromStream(stream, size, null, uploadOptions, null);

                // Upload the blob when RequireEncryption is true and no policy is set. This should throw an error.
                uploadOptions.EncryptionPolicy = null;

                stream = new MemoryStream(buffer);
                TestHelper.ExpectedException<InvalidOperationException>( 
                    () => blob.UploadFromStream(stream, size, null, uploadOptions, null),
                    "Not specifying a policy when RequireEnryption is set to true should throw.");

                // Create the encryption policy to be used for download.
                BlobEncryptionPolicy downloadPolicy = new BlobEncryptionPolicy(null, resolver);

                // Set the encryption policy on the request options.
                BlobRequestOptions downloadOptions = new BlobRequestOptions() { EncryptionPolicy = downloadPolicy };

                // Set RequireEncryption flag to true.
                downloadOptions.RequireEncryption = true;

                // Download the encrypted blob.
                MemoryStream outputStream = new MemoryStream();
                blob.DownloadToStream(outputStream, null, downloadOptions, null);

                blob.Metadata.Clear();

                // Upload a plain text blob.
                stream = new MemoryStream(buffer);
                blob.UploadFromStream(stream, size);

                // Try to download an encrypted blob with RequireEncryption set to true. This should throw.
                outputStream = new MemoryStream();
                TestHelper.ExpectedException<StorageException>(
                    () => blob.DownloadToStream(outputStream, null, downloadOptions, null),
                    "Downloading with RequireEncryption set to true and no metadata on the service should fail.");

                // Set RequireEncryption to false and download.
                downloadOptions.RequireEncryption = false;
                blob.DownloadToStream(outputStream, null, downloadOptions, null);
            }
            finally
            {
                container.DeleteIfExists();
            }
        }
开发者ID:renlesterdg,项目名称:azure-storage-net,代码行数:83,代码来源:BlobEncryptionTests.cs


示例16: DoInsertPOCOEntityEncryptionWithAttributes

        private void DoInsertPOCOEntityEncryptionWithAttributes(TablePayloadFormat format)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = format;

            // Insert Entity
            EncryptedBaseEntity ent = new EncryptedBaseEntity() { PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString() + format};
            ent.Populate();

            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            // Create the resolver to be used for unwrapping.
            DictionaryKeyResolver resolver = new DictionaryKeyResolver();
            resolver.Add(aesKey);

            TableRequestOptions insertOptions = new TableRequestOptions() { EncryptionPolicy = new TableEncryptionPolicy(aesKey, null) };
            currentTable.Execute(TableOperation.Insert(ent), insertOptions, null);

            // Retrieve Entity
            // No need for an encryption resolver while retrieving the entity.
            TableRequestOptions retrieveOptions = new TableRequestOptions() { EncryptionPolicy = new TableEncryptionPolicy(null, resolver) };

            TableOperation operation = TableOperation.Retrieve<EncryptedBaseEntity>(ent.PartitionKey, ent.RowKey);
            Assert.IsFalse(operation.IsTableEntity);
            TableResult result = currentTable.Execute(operation, retrieveOptions, null);

            EncryptedBaseEntity retrievedEntity = result.Result as EncryptedBaseEntity;
            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);
            retrievedEntity.Validate();
        }
开发者ID:benaadams,项目名称:azure-storage-net,代码行数:32,代码来源:TableEntityEncryptionTests.cs


示例17: DoInsertPOCOEntityEncryptionWithAttributesAndResolver

        private void DoInsertPOCOEntityEncryptionWithAttributesAndResolver(TablePayloadFormat format)
        {
            tableClient.DefaultRequestOptions.PayloadFormat = format;

            // Insert Entity
            EncryptedBaseEntity ent = new EncryptedBaseEntity() { PartitionKey = Guid.NewGuid().ToString(), RowKey = DateTime.Now.Ticks.ToString() + format };
            ent.Populate();

            // Create the Key to be used for wrapping.
            SymmetricKey aesKey = new SymmetricKey("symencryptionkey");

            // Create the resolver to be used for unwrapping.
            DictionaryKeyResolver resolver = new DictionaryKeyResolver();
            resolver.Add(aesKey);

            TableRequestOptions insertOptions = new TableRequestOptions() 
            { 
                EncryptionPolicy = new TableEncryptionPolicy(aesKey, null),

                EncryptionResolver = (pk, rk, propName) =>
                {
                    if (propName == "B")
                    {
                        return true;
                    }

                    return false;
                }
            };

            // Since we have specified attributes and resolver, properties A, B and foo will be encrypted.
            currentTable.Execute(TableOperation.Insert(ent), insertOptions, null);

            // Retrieve entity without decryption and confirm that all 3 properties were encrypted.
            // No need for an encryption resolver while retrieving the entity.
            TableOperation operation = TableOperation.Retrieve<EncryptedBaseEntity>(ent.PartitionKey, ent.RowKey);
            Assert.IsFalse(operation.IsTableEntity);
            TableResult result = currentTable.Execute(operation, null, null);
            
            EncryptedBaseEntity retrievedEntity = result.Result as EncryptedBaseEntity;
            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(ent.PartitionKey, retrievedEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedEntity.RowKey);

            // Since we store encrypted properties as byte arrays, if a POCO entity is being read as-is, odata will not assign the binary
            // values to strings. In JSON no metadata, the service does not return the types and the client lib does the parsing and reads the 
            // base64 encoded string as-is.
            if (format == TablePayloadFormat.JsonNoMetadata)
            {
                Assert.IsNotNull(retrievedEntity.foo);
                Assert.IsNotNull(retrievedEntity.A);
                Assert.IsNotNull(retrievedEntity.B);
                Assert.AreEqual(ent.foo.GetType(), retrievedEntity.foo.GetType());
                Assert.AreEqual(ent.A.GetType(), retrievedEntity.A.GetType());
                Assert.AreEqual(ent.B.GetType(), retrievedEntity.B.GetType());
            }
            else
            {
                Assert.IsNull(retrievedEntity.foo);
                Assert.IsNull(retrievedEntity.A);
                Assert.IsNull(retrievedEntity.B);
            }

            // Retrieve entity without decryption and confirm that all 3 properties were encrypted.
            // No need for an encryption resolver while retrieving the entity.
            operation = TableOperation.Retrieve<DynamicTableEntity>(ent.PartitionKey, ent.RowKey);
            Assert.IsFalse(operation.IsTableEntity);
            result = currentTable.Execute(operation, null, null);

            DynamicTableEntity retrievedDynamicEntity = result.Result as DynamicTableEntity;
            Assert.IsNotNull(retrievedEntity);
            Assert.AreEqual(ent.PartitionKey, retrievedDynamicEntity.PartitionKey);
            Assert.AreEqual(ent.RowKey, retrievedDynamicEntity.RowKey);

            if (format == TablePayloadFormat.JsonNoMetadata)
            {
           

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Redis.RedisManagementClient类代码示例发布时间:2022-05-26
下一篇:
C# Client.DocumentClient类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap