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
 
新聞熱點
疑難解答