4

我正在尝试使用证书和对称密钥加密数据库列。

我使用以下方法成功创建了证书和对称密钥:

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 并将其转换回人类可读的数据类型。我宁愿不必直接在存储过程中指定密码。有没有办法做到这一点?我在上面的代码中做错了什么?

谢谢。

4

2 回答 2

5

你只需要使用:

OPEN SYMMETRIC KEY MySSNKey
   DECRYPTION BY CERTIFICATE MyCertificate WITH PASSWORD = 'password';
于 2012-09-09T03:41:11.720 回答
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 ;
于 2016-04-13T09:17:29.160 回答