存储数据时如何加密天蓝色表中的一两个特定列?

时间:2018-10-24 09:00:36

标签: .net azure azure-storage

我有一个带有列的天蓝色表

[PartitionKey],[RowKey],[UserId],[UserName],[Email].

我只想加密UsernameEmails。在Azure Table中有什么方法可以做到这一点? 任何帮助表示赞赏。 预先感谢。

1 个答案:

答案 0 :(得分:1)

  

Azure表中有什么方法吗?

是的,在您的实体中标记属性为EncryptProperty的属性

[EncryptProperty]
public string UserName { get; set; }
[EncryptProperty]
public string Email { get; set; }

我们也可以参考此document以获得有关如何加密表实体的更多信息。

我还为此做了一个演示,下面是详细步骤。

1。创建一个.net控制台应用程序

2。使用nuget安装WindowsAzure.StorageMicrosoft.Azure.KeyVault.Extensions

3。使用以下代码添加一个名为User的新类。

public class User:TableEntity
{
    public string UserId { get; set; }
    [EncryptProperty]
    public string UserName { get; set; }
    [EncryptProperty]
    public string Email { get; set; }
    public User()
    {
        PartitionKey = "Tom";
        RowKey = Guid.NewGuid().ToString();

    }
    public User(string userId, string userName, string email)
    {
        PartitionKey = "Tom";
        RowKey = Guid.NewGuid().ToString();
        UserId = userId;
        UserName = userName;
        Email = email;

    }

}

4。将测试代码添加到Program.cs

static void Main(string[] args)
{
      var connectionstring = "DefaultEndpointsProtocol=https;AccountName=accountName;AccountKey=accountKey";
      CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionstring);
      RsaKey key = new RsaKey("mykey" /* key identifier */);
      // Create the encryption policy to be used for upload and download.
      TableEncryptionPolicy policy = new TableEncryptionPolicy(key, null);
      TableRequestOptions options = new TableRequestOptions
       {
           EncryptionPolicy = policy
       };
       CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
       // Create the CloudTable object that represents the "tomtest" table.
       CloudTable table = tableClient.GetTableReference("tomtest");
       table.CreateIfNotExists();
       //var insertList = new List<User>();
       var user = new User { UserId = Guid.NewGuid().ToString(),UserName="tom1",Email="tom1@email.com" };
       table.Execute(TableOperation.Insert(user), options);
       TableRequestOptions retrieveoptions = new TableRequestOptions
       {
           EncryptionPolicy = policy
       };
       var query = new TableQuery<User>().Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, user.RowKey));
       var list = table.ExecuteQuery(query, retrieveoptions);
       foreach (User entity in list)
       {
          Console.WriteLine($"PartionKey:{entity.PartitionKey},RowKey:{entity.RowKey},userId:{entity.UserId},UserName: {entity.UserName},email:{entity.Email}");
       }

       Console.ReadKey();
   } 

5。使用Microsoft Azure存储浏览器进行检查

enter image description here

6。从表中检索表实体并输出到控制台

enter image description here