2

我正在使用我创建的存储过程:

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= 'Test', Password_Encrypted= NULL。为什么最后一个给出null而不是字符串'Test'的加密?

4

1 回答 1

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
于 2013-08-08T21:07:35.490 回答