加密数据的存储过程

时间:2013-08-08 14:24:05

标签: sql sql-server stored-procedures encryption

我正在使用我创建的商店程序:

USE [database_name]
GO
OPEN SYMMETRIC KEY Password_Key
   DECRYPTION BY CERTIFICATE PasswordCertificate;
GO
CREATE PROCEDURE dbo.AddPassword
    @ID int,
    @Password varchar(50)
WITH ENCRYPTION
AS
INSERT INTO .EncryptionTest (ID,Password,Password_Encrypted)
VALUES (@ID,@Password,EncryptByKey(Key_GUID('Password_Key')
    , @Password, 1, HashBytes('SHA1', CONVERT(varbinary,@ID))))
GO

执行时:

USE [database_name]
GO
EXEC dbo.AddPassword @ID = 1, @Password = 'Test';
GO

它添加了一行ID = 1,Password ='测试',Password_Encrypted = NULL。为什么最后一个给出null而不是字符串'Test'的加密?

1 个答案:

答案 0 :(得分:2)

我怀疑您是从不同的范围执行该过程,或者自创建过程后您的连接已被切断。当然,您不能指望用户每次执行存储过程时都会打开对称密钥,因此应该在程序内部而不是创建过程的步骤。

ALTER PROCEDURE dbo.AddPassword
  @ID int,
  @Password varchar(50)
WITH ENCRYPTION
AS
BEGIN
  SET NOCOUNT ON;

  OPEN SYMMETRIC KEY Password_Key
   DECRYPTION BY CERTIFICATE PasswordCertificate;

  -- for debugging 101:    
  SELECT EncryptByKey(Key_GUID('Password_Key')
    , @Password, 1, HashBytes('SHA1', CONVERT(varbinary(128),@ID)));

  INSERT INTO dbo.EncryptionTest(ID,Password,Password_Encrypted)
  VALUES (@ID,@Password,EncryptByKey(Key_GUID('Password_Key')
    , @Password, 1, HashBytes('SHA1', CONVERT(varbinary(128),@ID))));
END
GO