gpt4 book ai didi

sql - 如何使用对称 key 加密和解密 SQL Server 中的整数数据类型列

转载 作者:行者123 更新时间:2023-12-02 05:08:39 25 4
gpt4 key购买 nike

我可以使用对称 key 加密和解密 varchar、nvarchar、char 列,但无法对 int、datetime、float、bigint 数据类型列执行相同操作

示例表:Mytable

| Id  Code  percentage  name    activity   |  
+------------------------------------------+
| 1 ad 43.43 James Running |
| 3 Pr 70.43 Sam Cooking |
| 5 nt 90.34 Lisa Walking |
| 4 ash 0.00 James Stealing |
| 2 han 0.00 James Lacking |
| 8 ant 73 Sam Cooking |

我想加密和解密ID列和百分比,它们分别是整数和 float 据类型。

我正在使用此代码进行加密:

OPEN SYMMETRIC KEY SymKey DECRYPTION BY CERTIFICATE data  

ALTER TABLE Mytable
SET ADD idencry VARBINARY(128) NULL


UPDATE Mytable
SET idencry = ENCRYPTBYKEY(KEY_GUID('datamSymKey'), CONVERT(varbinary, ID))

要解密,我使用以下代码:

SELECT 
id,
CONVERT(NVARCHAR(60), DECRYPTBYKEY(idencry )), *
FROM
Mytable

但它没有返回正确的结果... float 和 datetime 日期类型也是如此

最佳答案

嗨,我已经在 SQL Server 2016 上测试了这些代码,它可以工作:

CREATE CERTIFICATE Test04   
ENCRYPTION BY PASSWORD = 'pGFD4bb925DGvbd2439587y'
WITH SUBJECT = 'Sammamish Shipping Records',
EXPIRY_DATE = '20201031';
GO

CREATE SYMMETRIC KEY #SymKey
WITH ALGORITHM = AES_128
ENCRYPTION BY CERTIFICATE Test04;
GO

create Table #TestData
(
Id int,
Code varchar(10)
)

Insert into #TestData
(
Id,
Code
)
SELECT 1,'AA'
UNION
SELECT 2,'BB'
UNION
SELECT 3,'CC'
UNION
SELECT 4,'DD'
UNION
SELECT 5,'EE'
UNION
SELECT 6,'FF'

SELECT * FROM #TestData

OPEN SYMMETRIC KEY #SymKey DECRYPTION BY CERTIFICATE Test04 WITH PASSWORD='pGFD4bb925DGvbd2439587y'

ALTER TABLE #TestData
ADD idencry VARBINARY(128) NULL


UPDATE #TestData
SET idencry = ENCRYPTBYKEY(KEY_GUID('#SymKey'), CONVERT(varbinary, Id))



SELECT * FROM #TestData


OPEN SYMMETRIC KEY #SymKey DECRYPTION BY CERTIFICATE Test04 WITH PASSWORD='pGFD4bb925DGvbd2439587y'

SELECT
Id,
CONVERT(int, DECRYPTBYKEY(idencry)) AS 'IdDecrypted', *
FROM
#TestData


DROP TABLE #TestData

DROP SYMMETRIC KEY #SymKey

DROP CERTIFICATE Test04

我认为使用decryptbykey时必须强制转换为源类型

 CONVERT(NVARCHAR(60), DECRYPTBYKEY(idencry )), * 

您的“Id”列类型是什么?

你能尝试一下吗:

CONVERT(INT, DECRYPTBYKEY(idencry )), * 

关于sql - 如何使用对称 key 加密和解密 SQL Server 中的整数数据类型列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53984800/

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