ENCRYPTBYKEY sql server 2008仅加密第一个字符

时间:2013-07-13 13:16:08

标签: sql sql-server-2008 encryption

当我在插入查询中使用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";

2 个答案:

答案 0 :(得分: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();

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

答案 1 :(得分:0)

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

尝试如下

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

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