gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:58:18 26 4
gpt4 key购买 nike

我正在尝试编写一个存储过程来解密一些由对称 key 加密的数据,该对称 key 是用带有密码的非对称 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.

我应该把 EXEC sp_executesql @open 包裹起来吗?在 TRY ... CATCH并返回 NULL或者有没有(更)优雅的方式来处理这个问题?

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

最佳答案

示例 使用 key ,检查您的数据和代码:

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

关于sql-server - 在存储过程中使用密码打开对称 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8783819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com