Sql server 2008 如何在SQL中加密列数据?

Sql server 2008 如何在SQL中加密列数据?,sql-server-2008,tsql,encryption,Sql Server 2008,Tsql,Encryption,我尝试将列数据转换为新的加密数据。出现此错误 Argument data type int is invalid for argument 1 of DecryptByKey function. 查询: SELECT ID,FirmName,newDeviceID=CONVERT(VARCHAR(MAX),DecryptByKey(DeviceID)) FROM Table1 DeviceID为int.要将列数据转换为新的加密数据,可以执行以下操作: create table Tabl

我尝试将列数据转换为新的加密数据。出现此错误

  Argument data type int is invalid for argument 1 of DecryptByKey function.
查询:

SELECT ID,FirmName,newDeviceID=CONVERT(VARCHAR(MAX),DecryptByKey(DeviceID))

FROM Table1

DeviceID为int.

要将列数据转换为新的加密数据,可以执行以下操作:

create table Table1( id int, FirmName varchar(10),DeviceID int);
insert into Table1 values (1,'Firm1','123');

--If there is no master key, create one now. 
IF NOT EXISTS 
    (SELECT * FROM sys.symmetric_keys WHERE symmetric_key_id = 101)
    CREATE MASTER KEY ENCRYPTION BY 
    PASSWORD = '23987hxJKL969#ghf0%94467GRkjg5k3fd117r$$#1946kcj$n44nhdlj'
GO

CREATE CERTIFICATE Table1
   WITH SUBJECT = 'Table1 Device ID';
GO

CREATE SYMMETRIC KEY SSN_Key_01
    WITH ALGORITHM = AES_256
    ENCRYPTION BY CERTIFICATE Table1;
GO


-- Create a column in which to store the encrypted data.
ALTER TABLE Table1
    ADD EncryptedDeviceID varbinary(128); 
GO

-- Open the symmetric key with which to encrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE Table1;

-- Encrypt the value in column DeviceID with symmetric 
-- key SSN_Key_01. Save the result in column EncryptedDeviceID.
UPDATE Table1
SET EncryptedDeviceID = EncryptByKey(Key_GUID('SSN_Key_01'), convert(nvarchar,DeviceID));
GO

-- Verify the encryption.
-- First, open the symmetric key with which to decrypt the data.
OPEN SYMMETRIC KEY SSN_Key_01
   DECRYPTION BY CERTIFICATE Table1;
GO

-- Now list the original ID, the encrypted ID, and the 
-- decrypted ciphertext. If the decryption worked, the original
-- and the decrypted ID will match.
SELECT ID,FirmName, EncryptedDeviceID
    AS 'Encrypted ID Number',
    CONVERT(nvarchar, DecryptByKey(EncryptedDeviceID)) 
    AS 'Decrypted ID Number'
    FROM Table1;
GO
有关更多信息,请参阅以下链接:


希望这有帮助

DecryptByKey函数使用对称密钥解密数据。此函数中的第一个参数是已使用密钥加密的数据,它是varbinary。因此,错误是相同的。您不能传递int。有关详细信息,请参阅下面的链接: