@H_403_0@sql Server中加密是层级的,每一个上层为下提供保护。如图:
/**
SMK(Service Master Key)在sql Server安装时生成,由Windows DPAPI(Data Protection API)提供保护
**/ @H_403_0@/**创建数据库级别DMK(Database Master Key),受SMK保护**/
create master key encryption by password=N'Passw0rd'
go @H_403_0@/**数据库内的加密对象受DMK保护
支持的对称加密算法:DES | TRIPLE_DES | TRIPLE_DES_3KEY | RC2 | RC4 | RC4_128| DESX | AES_128 | AES_192 | AES_256
非对称加密算法:RSA_512 | RSA_1024 | RSA_2048
注意避免使用RC,DESX类算法,2014之后会删除此功能
**/ @H_403_0@
--1.创建非对称密钥.
sql;">
create asymmetric key asyc_key_enc
with algorithm=RSA_1024
encryption by password=N'Pass@word'
go
@H_403_0@--2.创建对称密钥.
sql;">
create symmetric key symc_key_enc
with algorithm=Triple_DES
encryption by password=N'Pass@word'
go
@H_403_0@--3.创建证书.证书也可被其它方式保护
sql;">
create certificate cert_ENC
with subject='certificate for ENC',expiry_date='20990101'
go
@H_403_0@--4.对称密钥可由以上三种方式提供加密保护
@H_403_0@--4.1 由非对称密钥加密
sql;">
create symmetric key symc_key_enc_byAsyc
with algorithm=AES_128
encryption by asymmetric key asyc_key_enc
go
@H_403_0@--4.2 由对称密钥加密
sql;">
open symmetric key symc_key_enc
decryption by password=N'
Pass@word';
create symmetric key symc_key_enc_bySymc
with algorithm = DES
encryption by symmetric key symc_key_enc
go
@H_403_0@--4.3 由证书加密
sql;">
create symmetric key symc_key_enc_byCert
with algorithm =AES_128
encryption by certificate cert_ENC
go
@H_403_0@/**列级数据加密和解密.MSsql提供以下4对加密/解密函数对列数据加密 EncryptByCert() 和DecryptByCert()—利用证书对数据进行加密和解密
EncryptByAsymKey() and DecryptByAsymKey()—利用非对称密钥对数据进行加密和解密
EncryptByKey() and DecryptByKey()—利用对称密钥对数据进行加密和解密
EncryptByPassphrase() and DecryptByPassphrase()—利用密码字段产生对称密钥对数据进行加密和解密
注意:被加密和解密的数据,必需是varbinary类型
**/ @H_403_0@
--以ENCRYPTBYKEY为例,其它的大同小异
@H_403_0@--对***号IDN进行加密和解密
sql;">
create table tb(IDN int,Name varchar(20));
insert into tb
values (123456789,'BigBrother'),(090807001,'SpiderMan'),(336655789,'SuperMan')
go
@H_403_0@--新增列Ency_IDN存储加密数据,使用之前由非对称密钥加密的对称密钥symc_key_enc_byAsyc来加密数据
sql;">
alter table tb add Ency_IDN varbinary(128);
go
open symmetric key symc_key_enc_byAsyc
decryption by asymmetric key asyc_key_enc
with password=N'
Pass@word';
update tb
set Ency_IDN=ENCRYPTBYKEY(KEY_GUID('symc_key_enc_byAsyc'),CONVERT(Varbinary,IDN));--加密前要转成varbinary
close symmetric key symc_key_enc_byAsyc --显式关闭对称密钥
go
@H_403_0@--解密被加密的列数据
sql;">
open symmetric key symc_key_enc_byAsyc
decryption by asymmetric key asyc_key_enc
with password=N'
Pass@word';
select IDN,Ency_IDN,convert(int,DECRYPTBYKEY(Ency_IDN))as Decr_IDN
from tb;
close symmetric key symc_key_enc_byAsyc --显式关闭对称密钥
go
1
@H_403_0@以上就是本文的全部内容,希望对大家的学习有所帮助。 原文链接:https://www.f2er.com/mssql/63067.html