1

我在插入查询中ENCRYPTBYKEY使用参数化查询时遇到问题。SQL它只加密和解密第一个字符。

这是我的代码:

    sqlParameters[0, 0] = "@DatabaseVersion";
    sqlParameters[0, 1] = this.TextBox1.Text.Trim();

    queryString = "OPEN SYMMETRIC KEY Sym_password " +
                    "DECRYPTION BY CERTIFICATE Cert_Password WITH PASSWORD      = 'myPassword'" +
                    "Insert Into zz_database_version " +
                    "( " +
                    "  DatabaseVersion " +
                    ") " +
                    "Values " +
                    "( " +
                    "ENCRYPTBYKEY(KEY_GUID('Sym_password'), @DatabaseVersion)     " +
                    ") " +
                    "CLOSE SYMMETRIC KEY Sym_password";
4

2 回答 2

2

好吧好吧,打开SQL Server管理工作室,然后新建一个查询面板(ctrl+n),创建如下存储过程(F5运行)

use mydb;--change the workstation to the desire database
go;
alter table zz_database_version alter column DatabaseVersion varbinary(8000) not null;--make sure the target field is varbinary too, if is, don't run this command
go;
create proc _encrypt(@data varchar(8000)) as begin
open symmetric key Sym_password certificate Cert_Password with password='myPassword'
insert zz_database_version(DatabaseVersion) select encryptbykey(key_guid('Sym_password'),@data);
close symmetric key Sym_password;
end

然后在您的 C# 代码中调用该过程

SqlConnection connection = new SqlConnection("Connection string here");
string sp = "_encrypt";
SqlCommand spcmd = new SqlCommand(sp, connection);
//
spcmd.CommandType = CommandType.StoredProcedure 
//
SqlParameter theOrderID = new SqlParameter("@data", SqlDbType.String);
theOrderID = "The value needs to be encrypted";
SqlDataReader dr;
spcmd.Parameters.Add(theOrderID);
connection.Open();
spcmd.ExecuteScalar();

任何失败或成功的反馈:)

于 2013-07-14T15:00:19.890 回答
0

CONVERT与您正在加密更新的值的数据类型和大小一起使用。看起来EncryptByKey无法按照列架构正确识别数据。

尝试如下

ENCRYPTBYKEY(KEY_GUID('Sym_password'), CONVERT(varchar(128),@DatabaseVersion))

假设 @DatabaseVersion 的类型为 varchar(128)

于 2020-01-01T07:56:38.793 回答