2013-12-10 61 views
0

我試着列數據轉換到新的encrpted data.I得到這個錯誤如何在SQL中加密列數據?

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。

+0

DecryptByKey函數通過使用對稱密鑰來解密數據。在這個函數中的第一個參數是用密鑰加密並且是varbinary的數據。所以錯誤是相同的。你不能傳遞一個int。您可以參考下面的鏈接以獲取更多信息:http://technet.microsoft.com/en-us/library/ms181860(v = sql.100).aspx – Deepshikha

回答

1

要列數據轉換到新的encrpted數據,你可以這樣做如下:

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 

對於您可以參考以下鏈接瞭解更多信息: http://technet.microsoft.com/en-us/library/ms179331(v=sql.100).aspx

希望這有助於!