sql-server – 在存储过程中使用密码打开对称密钥

我正在尝试编写一个存储过程来解密由Symmetric Key加密的一些数据,该对称密钥使用带密码的非对称密钥加密.

OPEN SYMMETRIC KEY需要密码的字符串文字,因此我不得不使用EXEC sp_executesql.有一个更好的方法吗?

DECLARE @open nvarchar(200), @close nvarchar(200)
SET @open = 'OPEN SYMMETRIC KEY skey DECRYPTION BY ASYMMETRIC KEY akey WITH PASSWORD = ' + quotename(@password,'''') + ';';
SET @close = 'CLOSE SYMMETRIC KEY skey;';

EXEC sp_executesql @open

SELECT [TransactionID],Convert(varchar(max),DECRYPTBYKEY([EncryptedText])) as DecryptedText FROM [dbo].[TestTable];

EXEC sp_executesql @close

如果使用错误的密码执行它,则会引发以下错误:

Msg 15466, Level 16, State 1, Line 1
An error occurred during decryption.
Msg 15315, Level 16, State 1, Line 1
The key 'skey' is not open. Please open the key before using it.

我应该在TRY … CATCH中包装EXEC sp_executesql @open并返回NULL还是有更优雅的方法来处理它?

编辑:处理使用错误密码调用此过程的人的最佳方法是什么?

最佳答案 使用密钥的示例,检查您的数据和代码:

CREATE ASYMMETRIC KEY akey WITH ALGORITHM = RSA_2048 
ENCRYPTION BY PASSWORD = 'aaa123'
GO
CREATE SYMMETRIC KEY skey WITH ALGORITHM = AES_256 ENCRYPTION BY ASYMMETRIC KEY akey
GO

DECLARE @t TABLE(plain VARCHAR(100), ciphered VARBINARY(MAX), unciphered VARCHAR(100))

INSERT @t(plain)
VALUES('11111'), ('22222'), ('33333')

OPEN SYMMETRIC KEY skey DECRYPTION BY ASYMMETRIC KEY akey WITH PASSWORD = 'aaa123'

UPDATE @t SET Ciphered = ENCRYPTBYKEY(KEY_GUID('skey'), plain)


UPDATE @t SET unciphered = CAST(DECRYPTBYKEY(ciphered) AS VARCHAR)

SELECT * FROM @t

CLOSE SYMMETRIC KEY skey
DROP SYMMETRIC KEY skey
DROP ASYMMETRIC KEY akey

要正确记录错误的密码解密尝试,请尝试以下示例,使用变量@password:

CREATE ASYMMETRIC KEY akey WITH ALGORITHM = RSA_2048 
ENCRYPTION BY PASSWORD = 'aaa123'
GO
CREATE SYMMETRIC KEY skey WITH ALGORITHM = AES_256 ENCRYPTION BY ASYMMETRIC KEY akey
GO

DECLARE @t TABLE(plain VARCHAR(100), ciphered VARBINARY(MAX), unciphered VARCHAR(100))

INSERT @t(plain)
VALUES('11111'), ('22222'), ('33333')

OPEN SYMMETRIC KEY skey DECRYPTION BY ASYMMETRIC KEY akey WITH PASSWORD = 'aaa123'

UPDATE @t SET Ciphered = ENCRYPTBYKEY(KEY_GUID('skey'), plain)
CLOSE SYMMETRIC KEY skey

DECLARE @open nvarchar(200), @close nvarchar(200), @password VARCHAR(20) = 'aaa123x'
SET @open = 'OPEN SYMMETRIC KEY skey DECRYPTION BY ASYMMETRIC KEY akey WITH PASSWORD = ' + quotename(@password,'''') + ';';
SET @close = 'CLOSE SYMMETRIC KEY skey;';
BEGIN TRY 
  EXEC sp_executesql @open
  UPDATE @t SET unciphered = CAST(DECRYPTBYKEY(ciphered) AS VARCHAR)
  SELECT * FROM @t
  EXEC sp_executesql @close
END TRY BEGIN CATCH 
  SELECT 'Do whatever you want to do here with this caller. Suspicious caller: '+SUSER_SNAME()+', at: '+CAST(GETDATE() AS VARCHAR)
END CATCH

DROP SYMMETRIC KEY skey
DROP ASYMMETRIC KEY akey
点赞