简体   繁体   中英

How to Encrypt Column Data in SQL?

I tried convert column data to new encrpted data.I get this error

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

Query :

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

FROM Table1

DeviceID is int.

To convert column data to new encrpted data you can do something like below:

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

For more information you can refer to following link: http://technet.microsoft.com/en-us/library/ms179331(v=sql.100).aspx

Hope this helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM