共用方式為


使用加密

適用於:SQL ServerAzure SQL DatabaseAzure SQL 受控執行個體Azure Synapse Analytics

在 SMO 中,服務主要金鑰是由 ServiceMasterKey 物件表示。 這是由 ServiceMasterKey 物件的 屬性 Server 所參考。 您可以使用 方法重新產生 Regenerate 它。

資料庫主要金鑰是由 MasterKey 物件表示。 屬性 IsEncryptedByServer 會指出資料庫主要金鑰是否由服務主要金鑰加密。 每當資料庫主要金鑰變更時,master 資料庫中的加密複本就會自動更新。

您可以使用 方法卸載服務金鑰加密 DropServiceKeyEncryption ,並使用密碼加密資料庫主要金鑰。 在此情況下,您必須先明確開啟資料庫主要金鑰,才能存取已保護的私密金鑰。

當資料庫附加至 SQL Server 實例時,您必須提供資料庫主要金鑰的密碼,或執行 AddServiceKeyEncryption 方法,讓資料庫主要金鑰的未加密複本可供使用服務主要金鑰進行加密。 建議您執行此步驟,以避免需要明確開啟資料庫主要金鑰。

方法會 Regenerate 重新產生資料庫主要金鑰。 重新產生資料庫主要金鑰時,所有使用資料庫主要金鑰加密的金鑰都會解密,然後使用新的資料庫主要金鑰加密它們。 方法 DropServiceKeyEncryption 會移除服務主要金鑰的資料庫主要金鑰加密。 AddServiceKeyEncryption 會使用服務主要金鑰來加密主要金鑰複本,並儲存在目前資料庫和 master 資料庫中。

在 SMO 中,憑證會以 Certificate 物件表示。 物件 Certificate 具有屬性,可指定公開金鑰、主體名稱、有效期間,以及簽發者的相關資訊。 存取憑證的許可權是使用 Grant Revoke Deny 方法來控制。

範例

針對下列程式碼範例,您必須選取程式設計環境、程式設計範本和程式設計語言,才能建立您的應用程式。 如需詳細資訊,請參閱 在 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")  
  

另請參閱

使用加密金鑰