gpt4 book ai didi

sql-server - "Invalid use of a side-effecting operator ' OPEN SYMMETRIC KEY 打开对称 key 时出现 ' within a function."错误

转载 作者:行者123 更新时间:2023-12-02 23:27:11 36 4
gpt4 key购买 nike

我正在尝试在两个函数内打开对称 key 。像这样:

CREATE FUNCTION DECRYPTDATA 
(
@CipherText NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Result NVARCHAR(MAX)
OPEN SYMMETRIC KEY MyKEY DECRYPTION BY CERTIFICATE MyCERT
SELECT @Result = CONVERT(VARCHAR(MAX),DECRYPTBYKEY(@CipherText))
RETURN @Result

END
GO
CREATE FUNCTION ENCRYPTDATA
(
@Text NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
DECLARE @Result NVARCHAR(MAX)
OPEN SYMMETRIC KEY MyKEY DECRYPTION BY CERTIFICATE MyCERT
SELECT @Result = ENCRYPTBYKEY(Key_GUID('MyKEY'),@Text)
RETURN @Result

END
GO

但我收到此错误:

Invalid use of a side-effecting operator 'OPEN SYMMETRIC KEY' within a function.

为什么会发生这种情况?

最佳答案

实际上,您可以在函数中执行此操作,而无需使用 DECRYPTBYKEYAUTOCERT 打开对称 key 。功能:

Decrypts by using a symmetric key that is automatically decrypted with a certificate.

以下示例演示了这一点:

CREATE MASTER KEY ENCRYPTION
BY PASSWORD = 'sm_long_password@'
GO

CREATE CERTIFICATE CERT_01
WITH SUBJECT = 'CERT_01'
GO

CREATE SYMMETRIC KEY SK_01
WITH ALGORITHM = AES_256 ENCRYPTION
BY CERTIFICATE CERT_01
GO

CREATE FUNCTION [dbo].[TEST] (@encryptedValue VARBINARY(256))
RETURNS NVARCHAR(128)
AS
BEGIN;
RETURN CONVERT(NVARCHAR(128),DECRYPTBYKEYAUTOCERT(CERT_ID('CERT_01'), NULL, @encryptedValue));
END
GO


DECLARE @encryptedValue VARBINARY(256);


OPEN SYMMETRIC KEY SK_01 DECRYPTION
BY CERTIFICATE CERT_01

SET @encryptedValue = ENCRYPTBYKEY(KEY_GUID('SK_01'), N'Stack Overflow')

CLOSE SYMMETRIC KEY SK_01;


SELECT [dbo].[TEST] (@encryptedValue);


DROP FUNCTION [dbo].[TEST];
DROP SYMMETRIC KEY SK_01;
DROP CERTIFICATE CERT_01;
DROP MASTER KEY;

关于sql-server - "Invalid use of a side-effecting operator ' OPEN SYMMETRIC KEY 打开对称 key 时出现 ' within a function."错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30696265/

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