本文整理汇总了C#中Microsoft.Azure.KeyVault.SymmetricKey类的典型用法代码示例。如果您正苦于以下问题:C# SymmetricKey类的具体用法?C# SymmetricKey怎么用?C# SymmetricKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SymmetricKey类属于Microsoft.Azure.KeyVault命名空间,在下文中一共展示了SymmetricKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
示例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);
}
示例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));
}
示例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);
}
示例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"]);
}
示例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);
}
}
示例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();
}
}
示例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);
}
示例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);
}
示例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();
}
}
示例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();
}
}
示例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();
}
}
示例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();
}
}
示例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);
}
}
示例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();
}
}