sql server 2005加密体系(一)
sql server 2005中引入了一套完整的加密方法,具体的术语呢就偷个懒不写了,大家可以看bol么。
大致的结构呢就是在安装sql server 2005的时候利用sql server服务账号生成一个服务主密钥service master key,然后数据库的管理员可以在数据库上创建database master key,当然也可以不创建,同时数据库管理员可以为database user创建证书、对称密钥或者非对称密钥。这三种对象都可以用于加密用户数据,但一般推荐利用证书签署代码,利用证书或者非对称密钥加密对称密钥,利用对称密钥加密用户数据。
以下还是给一段代码,因为考虑到我跟王辉兄弟当时在成都宾馆里研究这个东西就是苦于找不到完整的范例代码,后来还是gtec的徐强大拿给了个link,然后我们又东拼西凑才出了一段代码,不敢独享,拿来与大家分享。
先给利用证书签署代码的范例,这段代码的好处是不用给database user大的权限,就可以让用户修改部分数据,这也是sql server 2005中权限粒度化的一种表现:
--------------------------------------------------------------------------------
--创建实验用数据库
use master
if exists(select [name] from sys.databases where [name] = 'sales')
drop database sales
create database sales
if exists(select principal_id from sys.server_principals where [name] = 'ryan' and [type] = 's')
drop login ryan
create login ryan with password = '[email protected]'
if exists(select principal_id from sys.server_principals where [name] = 'teddy' and [type] = 's')
drop login teddy
create login teddy with password = '[email protected]'
--创建用户ryan,并创建数据库主密钥
use sales
if exists(select * from sys.database_principals where [name] = 'ryan' and [type] = 's')
drop user ryan
create user ryan for login ryan with default_schema = dbo
go
create master key encryption by password = '[email protected]'
go
--创建证书
if exists(select [name] from sys.certificates where [name] = 'cert_maintain')
drop certificate cert_maintain
create certificate cert_maintain
with subject = 'certificate for database maintainance',
start_date = '01/01/2006',
expiry_date = '12/31/2015'
go
select * from sys.certificates
--利用证书创建数据库用户,并授予该用户管理数据库用户的权限
create user user_maintain for certificate cert_maintain
grant alter any user to user_maintain
--创建存储过程
if exists(select [name] from sys.procedures where [name] = 'usp_adduser')
drop procedure dbo.usp_adduser
go
create procedure dbo.usp_adduser
@username varchar(50)
as
if exists(select * from sys.database_principals where [name] = @username and [type] = 's')
exec ('drop user ' + @username)
exec ('create user ' + @username)
go
--完成准备工作,开始测试加密
grant exec on dbo.usp_adduser to ryan
execute as login = 'ryan'
begin try
exec dbo.usp_adduser 'teddy'
end try
begin catch
select error_message() as 'error msg'
end catch
revert
--利用证书签署存储过程代码
add signature to dbo.usp_adduser by certificate cert_maintain
alter certificate cert_maintain remove private key
--在此尝试执行脚本
execute as login = 'ryan'
exec dbo.usp_adduser 'teddy'
revert
新闻热点
疑难解答