我可以使用对称密钥对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列和Percentage。
我正在使用此代码进行加密:
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日期类型也是如此
答案 0 :(得分:0)
嗨,我已经在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
我认为您在使用Deletebykey时必须将源类型转换为
CONVERT(NVARCHAR(60), DECRYPTBYKEY(idencry )), *
您的“ Id”列类型是什么?
您可以尝试:
CONVERT(INT, DECRYPTBYKEY(idencry )), *