我正在尝试使用证书和对称密钥加密数据库列。
我使用以下方法成功创建了证书和对称密钥:
CREATE CERTIFICATE MyCertificate
ENCRYPTION BY PASSWORD = 'password'
WITH SUBJECT = 'Public Access Data'
GO
CREATE SYMMETRIC KEY MySSNKey
WITH ALGORITHM = AES_256
ENCRYPTION BY CERTIFICATE MyCertificate
我尝试使用以下方法加密和解密某些数据:
DECLARE @Text VARCHAR(100)
SET @Text = 'Some Text'
DECLARE @EncryptedText VARBINARY(128)
-- Open the symmetric key with which to encrypt the data.
OPEN SYMMETRIC KEY MySSNKey
DECRYPTION BY CERTIFICATE MyCertificate;
SELECT @EncryptedText = EncryptByKey(Key_GUID('MySSNKey'), @Text)
SELECT CONVERT(VARCHAR(100), DecryptByKey(@EncryptedText)) AS DecryptedText
当我这样做时,收到以下错误消息:
证书具有受用户定义保护的私钥 密码。需要提供该密码才能使用 私钥。
最终,我要做的是编写一个存储过程,将一些未加密的数据作为输入,加密,然后将其存储为加密的varbinary。然后我想编写第二个存储过程,它将执行相反的操作 - 即,解密加密的varbinary并将其转换回人类可读的数据类型。我宁愿不必直接在存储过程中指定密码。有没有办法做到这一点?我在上面的代码中做错了什么?
感谢。
答案 0 :(得分:5)
你只需要使用:
OPEN SYMMETRIC KEY MySSNKey
DECRYPTION BY CERTIFICATE MyCertificate WITH PASSWORD = 'password';
答案 1 :(得分:0)
你必须使用MASTER KEY
示例:
CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'MasterPassword';
CREATE CERTIFICATE MyCertificate WITH SUBJECT = 'Public Access Data';
CREATE SYMMETRIC KEY MySSNKey WITH ALGORITHM = AES_256 ENCRYPTION BY CERTIFICATE MyCertificate;
OPEN SYMMETRIC KEY MySSNKey DECRYPTION BY CERTIFICATE MyCertificate;
SELECT Customer_id, Credit_card_number_encrypt AS 'Encrypted Credit Card Number',
CONVERT(varchar, DecryptByKey(Credit_card_number_encrypt)) AS 'Decrypted Credit Card Number'
FROM dbo.Customer_data;
CLOSE SYMMETRIC KEY MySSNKey ;