0

我正在研究数据库加密,即SQL Server 2008 Express 中基于单元的对称加密。但问题是插入的参数化查询不起作用。请帮帮我 。. .

编辑:

我使用以下查询作为示例:

foreach (var list in from DataRow row in dataTable.Rows select new ArrayList
                           {
                                 String.Format("@var1, {0}", row["Column1"]), 
                                 String.Format("@var2, {0}", row["Column2"]),
                                 String.Format("@var3, {0}", row["Column3"])
                           })
    {
         var query = String.Format(@"OPEN SYMMETRIC KEY {0} DECRYPTION BY CERTIFICATE {1} 
                     INSERT INTO TableA (Column1, Column2, Column3) VALUES (@ENCRYPTBYKEY(KEY_GUID('symKey'), '{2}'), ENCRYPTBYKEY(KEY_GUID('symKey'), '{3}'), ENCRYPTBYKEY(KEY_GUID('symKey'), '{4}'))", symKey, symCer, "@var1", "@var2", "@var3");
         con.Execute.ExecuteParameterizedQuery(query, list);
    }

public string ExecuteParameterizedQuery(string query, ArrayList parametersList)
{
      errorFlag = Connect(un, pasw, 3);
      if ((String.CompareOrdinal(errorFlag, "Open") == 0))
      {
          var myTran = myConnection.BeginTransaction();
          cmd = new SqlCommand(query, myConnection) { Transaction = myTran };
          for (var i = 0; i < parametersList.Count; i++)
          {
              var split = parametersList[i].ToString().Split(',');
              cmd.Parameters.AddWithValue(split[0], split[1]);
          }
          try
          {
              cmd.CommandText = query;
              cmd.ExecuteNonQuery();
              myTran.Commit();
              errorFlag = string.Empty;
          }
          catch (Exception e)
          {
              errorFlag = e.Message;
          }
          finally
          {
              myConnection.Close();
              myConnection.Dispose();
          }
          return errorFlag;
      }
      myConnection.Close();
      myConnection.Dispose();
      return errorFlag;
  }

编辑2:

CREATE PROCEDURE ng_encryptString
(
    @PlaneText VARCHAR(500), @SipherText VARBINARY(2000) OUT
)
AS
BEGIN
OPEN SYMMETRIC KEY symKey DECRYPTION BY CERTIFICATE SymCert 
SELECT ENCRYPTBYKEY(KEY_GUID('SymKey'), @PlaneText)
END
4

1 回答 1

1

这里我建议的是,

  1. 创建一个过程

    INSERT INTO TableA (Column1, Column2, Column3) VALUES(@val1,@val2,@val3)
    
  2. 现在在 C# 中创建一个encryptThestring(string val)函数,它应该返回给定正常输入值的加密值。

  3. 最后在 C# 中调用该过程并将参数传递为

    encryptThestring(string val1)
    encryptThestring(string val2)
    encryptThestring(string val3)
    

这是 C#.net 函数

public string EncryptString(string val)
            {
                SqlConnection sqlconn = new SqlConnection("conn_string");
                sqlconn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = sqlconn;

                cmd.CommandText = "ng_encryptString"; // This is the sproc which will encrypt the string
                cmd.CommandType = CommandType.StoredProcedure;

                SqlParameter param1 = cmd.Parameters.Add("inpuStr", SqlDbType.VarChar, 500);
                param1.Direction = ParameterDirection.Input;

                SqlParameter param3 = cmd.Parameters.Add("@encryptedStr", SqlDbType.VarChar, 2000);
                param3.Direction = ParameterDirection.Output;

                param1.Value = val;

                cmd.ExecuteNonQuery();
                sqlconn.Close();
                return (string)param3.Value;

            }

sproc ng_encryptString

CREATE Procedure [dbo].[ng_encryptString]  
@string varchar(255),  
@encryptedStr varbinary(2000)  OUTPUT  

As  
Begin  


Declare @res varbinary(2000)  

IF NOT EXISTS(select * from sys.symmetric_keys where name='##MS_DatabaseMasterKey##')  
CREATE MASTER KEY ENCRYPTION  
BY PASSWORD = 'yourpassword'  


IF NOT EXISTS(select * from sys.certificates where name='EncryptTestCert')  
CREATE CERTIFICATE EncryptTestCert  
WITH SUBJECT = 'yoursubject'  

IF NOT EXISTS(select * from sys.symmetric_keys where name='TestTableKey')   
CREATE SYMMETRIC KEY TestTableKey  
WITH ALGORITHM = TRIPLE_DES ENCRYPTION  
BY CERTIFICATE EncryptTestCert  

OPEN SYMMETRIC KEY TestTableKey DECRYPTION  
BY CERTIFICATE EncryptTestCert  


SELECT @encryptedStr=ENCRYPTBYKEY(KEY_GUID('TestTableKey'),@string)  

end  
于 2012-08-13T06:09:01.290 回答