SQL服务器加密内置这里是我的书采取了一些示例代码有关安全性(SQL Server 2012的安全性食谱):
USE marketing ;
-- create the database master key
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'a very strong password';
-- a sample table
CREATE TABLE dbo.Customer (
CustomerId int NOT NULL IDENTITY(1,1) PRIMARY KEY,
Firstname varchar(50) NOT NULL,
Lastname varchar(50) NOT NULL,
CreditCardInfo varbinary(2000) NOT NULL
)
-- a certificate to protect the encryption key
CREATE CERTIFICATE KeyProtectionCert
WITH SUBJECT = 'to protect symmetric encryption keys';
-- the symmetric encryption key
CREATE SYMMETRIC KEY CreditCardSKey
WITH ALGORITHM = AES_256,
KEY_SOURCE = '4frT-7FGHFDfTh98#6erZ3dq#«',
IDENTITY_VALUE = 'l·Fg{([email protected]&4efVql'
ENCRYPTION BY CERTIFICATE KeyProtectionCert;
-- using the encryption key
OPEN SYMMETRIC KEY CreditCardSKey
DECRYPTION BY CERTIFICATE KeyProtectionCert;
INSERT INTO dbo.Customer (Firstname, LastName, CreditCardInfo)
VALUES ('Jim', 'Murphy',
EncryptByKey(Key_Guid('CreditCardSKey'), '1111222233334444;12/13,456', 1, 'JimMurphy')
);
CLOSE SYMMETRIC KEY CreditCardSKey;
--To read the data and get back the original unencrypted data (the plaintext), we use the DecryptByKey() function:
OPEN SYMMETRIC KEY CreditCardSKey DECRYPTION BY CERTIFICATE KeyProtectionCert;
SELECT Firstname, Lastname,
CAST(DecryptByKey(CreditCardInfo, 1, Firstname + Lastname) as varchar(50))
FROM dbo.Customer;
CLOSE SYMMETRIC KEY CreditCardSKey;
-- or without opening it :
SELECT Firstname, Lastname,
CAST(DecryptByKeyAutoCert(CERT_ID('KeyProtectionCert'), NULL, CreditCardInfo, 1, Firstname + Lastname) as varchar(50))
FROM dbo.Customer;