【问题标题】:Entity Framework - Always Encrypted - AzureKeyVault实体框架 - 始终加密 - AzureKeyVault
【发布时间】:2018-12-18 21:07:01
【问题描述】:

我已使用 AzureKeyVault 加密 SQL 中的一些社会保障号列。这些列定义是 varchar(11) NULL。

我的代码中的模型具有以下属性:

    [StringLength(11)]
    [Column(TypeName = "varchar")]
    [RegularExpression(RegExValidators.SSNRegex, ErrorMessage = "SSN must be a number")]
    public string SSN { get; set; }

但是,我偶尔会在我的数据库日志中看到此错误:

System.Data.SqlClient.SqlException: Operand type clash: varchar is incompatible with varchar(11) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto2', column_encryption_key_database_name = 'DB NAME') collation_name = 'Latin1_General_BIN2'
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)

奇怪的是,这种情况并不总是发生......只是每隔一段时间。我在 Global.asax Application_Start() 函数中运行此代码:

public static class AzureKeyVaultInit
    {
        private static string _clientId = ConfigurationManager.AppSettings["AzureKeyVaultAppClientId"];
        private static string _clientSecret = ConfigurationManager.AppSettings["AzureKeyVaultAppSecret"];
        private static ClientCredential _clientCredential;
        private static bool _isInitialized = false;
        private static readonly object _isInitializedLock = new object();

        public static void InitializeAzureKeyVaultProvider()
        {

            if (string.IsNullOrEmpty(_clientId)) return;

            lock (_isInitializedLock)
            {
                if (!_isInitialized)
                {
                    _clientCredential = new ClientCredential(_clientId, _clientSecret);

                    SqlColumnEncryptionAzureKeyVaultProvider azureKeyVaultProvider = new SqlColumnEncryptionAzureKeyVaultProvider(GetToken);

                    Dictionary<string, SqlColumnEncryptionKeyStoreProvider> providers = new Dictionary<string, SqlColumnEncryptionKeyStoreProvider>();
                    providers.Add(SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, azureKeyVaultProvider);

                    SqlConnection.RegisterColumnEncryptionKeyStoreProviders(providers);

                    _isInitialized = true;

                    Core.Log.Info($"Initialized Azure Key Vault");
                }
            }
        }

有什么明显的原因为什么我每隔一段时间就会收到这个错误?

【问题讨论】:

  • thisthis
  • 现在有任何进程吗?

标签: entity-framework azure azure-web-app-service azure-keyvault always-encrypted


【解决方案1】:

任何以加密列为目标的值都需要在应用程序内部进行加密。尝试插入/修改或按加密列上的纯文本值过滤将导致像您这样的错误。

为防止此类错误,请确保:

1. 为针对加密列的应用程序查询启用始终加密(在连接字符串或SqlCommand 对象中为特定查询设置Column Encryption Setting=enabled)。

2.使用SqlParameter 发送针对加密列的数据。

更多详情可以参考这个article

【讨论】:

  • 谢谢,我确实在连接字符串中启用了列加密设置=。我目前正在使用实体框架,我认为它会自动参数化查询......但也许我错了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多