0

In Sql Server I have some columns in a table encrypted, when I try to access it with this code :

            string connectionString = "Server=xxx;Database=xxx;user id=xxx;password=xxx;Column Encryption Setting=Enabled";

            using (SqlConnection connection = new SqlConnection(connectionString))
            using (SqlCommand cmd = connection.CreateCommand())
            {
                connection.Open();

                cmd.CommandText = @"SELECT * FROM PersonSample WHERE Postcode=@Postcode";

                SqlParameter parameter = new SqlParameter("@Postcode", "AB10 6EN");
                cmd.Parameters.Add(parameter);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine(@"{0}, {1}, {2}, {3}, {4}", reader[0], reader[1], reader[2], reader[3], reader[4]);
                        }
                    }
                }


            }

I get an error on the line with cmd.ExecuteReader :

Microsoft.Data.SqlClient.SqlException: 'The data types varchar(50) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'VerifiEncryptTest') collation_name = 'Latin1_General_BIN2' and nvarchar(8) encrypted with (encryption_type = 'DETERMINISTIC', encryption_algorithm_name = 'AEAD_AES_256_CBC_HMAC_SHA_256', column_encryption_key_name = 'CEK_Auto1', column_encryption_key_database_name = 'VerifiEncryptTest') 
are incompatible in the equal to operator.
Statement(s) could not be prepared.'

I have read that "Deterministic encryption must use a column collation with a binary2 sort order for character columns.", the column in question Postcode has a collation type of "Latin1_General_BIN2", surely that is binary2?

Paul
  • 856
  • 1
  • 8
  • 18

1 Answers1

1

I have found the answer, I needed to add the parameter like this (so including the VarChar Sql type) :

                SqlParameter parameter = new SqlParameter("@Postcode", SqlDbType.VarChar, 50);
                parameter.Value = "AB10 6EN";
Paul
  • 856
  • 1
  • 8
  • 18
  • I added encryption to 2 columns in my LogInUserMaster table. I am getting similar error when I execute my Stored proc from SQL management studio. (calling it from APP is still away -:) Can you help – Umesh Deshmukh Jul 03 '23 at 10:03