实体框架-始终加密-AzureKeyVault

时间:2018-12-18 21:07:01

标签: entity-framework azure azure-web-sites azure-keyvault always-encrypted

我已使用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");
                }
            }
        }

为什么我会偶尔收到此错误?

1 个答案:

答案 0 :(得分:0)

任何针对加密列的值都需要在应用程序内部进行加密。尝试在加密列上通过明文值插入/修改或过滤会导致类似您的错误。

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

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

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

有关更多详细信息,您可以参考此article