实现Sql2005非对称加密的方法

实现Sql2005非对称加密的方法


--1) 创建非对称密钥

CREATE ASYMMETRIC KEY AsyTestKey WITH ALGORITHM = RSA_1024
ENCRYPTION BY PASSWORD = 'walp#$sdine894!sdasdf>seddv'
GO

SELECT * FROM sys.asymmetric_keys

--2) 创建示例表
USE TestDb
IF EXIST EmpSalary DROP TABLE EmpSalary;

CREATE TABLE SysEmployee(
WorkNo int,
WorkName nvarchar(50),
Passwd varbinary(500)
)
GO

--3) 向表中插入数据,并对Salary列的数据进行加密
INSERT INTO SysEmployee VALUES (1, '王贤', EncryptByAsymKey(AsymKey_ID('AsyTestKey'), '123#sined'))
INSERT INTO SysEmployee VALUES (2, '李宁', EncryptByAsymKey(AsymKey_ID('AsyTestKey'), 'disf>!we'))
INSERT INTO SysEmployee VALUES (3, '陈飞', EncryptByAsymKey(AsymKey_ID('AsyTestKey'), '877erECe'))
GO

--4) 查看表中存放的数据
SELECT * FROM SysEmployee


--5) 解密被加密了的数据列

SELECT WorkNo, WorkName,CONVERT(varchar(20),
DecryptByAsymKey( AsymKey_Id('AsyTestKey'),
Passwd, N'walp#$sdine894!sdasdf>seddv' )) as DecryptPasswd,Passwd as EncryptPasswd
FROM SysEmployee