使用加密

适用于:SQL Server Azure SQL 数据库 azure Synapse Analytics Azure SQL 托管实例

在 SMO 中,服务主密钥由 ServiceMasterKey 对象表示。 它是由 ServiceMasterKey 对象的 Server 属性引用的。 可以通过使用 Regenerate 方法重新生成服务主密钥。

数据库主密钥由 MasterKey 对象表示。 IsEncryptedByServer 属性指示是否通过服务主密钥对数据库主密钥进行加密。 数据库主密钥发生变化时,主数据库中的加密副本会自动进行更新。

可以采用 DropServiceKeyEncryption 方法删除服务密钥加密,并使用密码加密数据库主密钥。 在这种情况下,您必须显式打开数据库主密钥,然后才能访问已受到安全保护的私钥。

将数据库附加到 SQL Server 实例时,必须提供数据库主密钥的密码,或执行 AddServiceKeyEncryption 该方法,使数据库主密钥的未加密副本可用于使用服务主密钥进行加密。 建议执行此步骤,从而无需显式打开数据库主密钥。

Regenerate 方法将重新生成数据库主密钥。 当重新生成数据库主密钥时,会对所有使用该数据库主密钥加密的密钥进行解密,然后使用新的数据库主密钥对其进行加密。 DropServiceKeyEncryption 方法将通过服务主密钥删除对数据库主密钥的加密。 AddServiceKeyEncryption 可以通过服务主密钥对主密钥的副本进行加密,然后将副本存储在当前数据库和主数据库中。

在 SMO 中,证书由 Certificate 对象表示。 Certificate 对象具有指定公钥、主题名称、有效期以及有关颁发者的信息的属性。 可采用 GrantRevokeDeny 方法控制对证书的访问权限。

示例

对于下列代码示例,您必须选择编程环境、编程模板和编程语言才能创建应用程序。 有关详细信息,请参阅 在 Visual Studio .NET 中创建 Visual C# SMO 项目。

在 Visual C# 中添加证书

该代码示例使用加密密码创建简单证书。 与其他对象不同,Create 方法具有若干种重载。 该示例中所使用的重载将使用加密密码创建一个新证书。

{  
            //Connect to the local, default instance of SQL Server.   
            {  
                Server srv = new Server();  
  
                //Reference the AdventureWorks2022 database.   
                Database db = srv.Databases["AdventureWorks2022"];  
  
                //Define a Certificate object variable by supplying the parent database and name in the constructor.   
                Certificate c = new Certificate(db, "Test_Certificate");  
  
                //Set the start date, expiry date, and description.   
                System.DateTime dt;  
                DateTime.TryParse("January 01, 2010", out dt);  
                c.StartDate = dt;  
                DateTime.TryParse("January 01, 2015", out dt);  
                c.ExpirationDate = dt;  
                c.Subject = "This is a test certificate.";  
                //Create the certificate on the instance of SQL Server by supplying the certificate password argument.   
                c.Create("pGFD4bb925DGvbd2439587y");  
            }  
        }   

在 PowerShell 中添加证书

该代码示例使用加密密码创建简单证书。 与其他对象不同,Create 方法具有若干种重载。 该示例中所使用的重载将使用加密密码创建一个新证书。

# Set the path context to the local, default instance of SQL Server and get a reference to AdventureWorks2022  
CD \sql\localhost\default\databases  
$db = get-item AdventureWorks2022  
  
#Create a certificate  
  
$c = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Certificate -argumentlist $db, "Test_Certificate"  
$c.StartDate = "January 01, 2010"  
$c.Subject = "This is a test certificate."  
$c.ExpirationDate = "January 01, 2015"  
  
#Create the certificate on the instance of SQL Server by supplying the certificate password argument.  
$c.Create("pGFD4bb925DGvbd2439587y")  
  

另请参阅

使用加密密钥