Share via


重新產生儲存體帳戶金鑰

 

Regenerate Keys 非同步作業會重新產生指定之儲存體帳戶的主要或次要存取金鑰。

要求

Regenerate Keys 要求可能會以下面方式指定。 取代 <subscription-id> 與您的訂閱 ID 和 <service-name> 所需的儲存體帳戶的名稱。

方法 要求 URI
POST https://management.core.windows.net/<subscription-id>/services/storageservices/<service-name>/keys?action=regenerate

您必須確定對管理服務發出的要求是安全的。 如需詳細資訊,請參閱 驗證服務管理要求

URI 參數

URI 參數 說明
action=regenerate 必要項。 指定必須重新產生指定之儲存體帳戶的主要或次要存取金鑰。

要求標頭

下表描述要求標頭。

要求標頭 說明
Content-Type 必要項。 此標頭設定為 application/xml
x-ms-version 必要項。 指定用於這個要求的作業版本。 此標頭應該設定為 2009年-10-01 或更高版本。 如需有關版本設定標頭的詳細資訊,請參閱 服務管理版本控制

要求本文

要求主體指出即將重新產生的金鑰是主要金鑰或次要金鑰。 要求主體的格式如下:

  
<?xml version="1.0" encoding="utf-8"?> <RegenerateKeys xmlns="https://schemas.microsoft.com/windowsazure"> <KeyType>Primary|Secondary</KeyType> </RegenerateKeys>  
  

下表說明要求主體的元素。

元素名稱 說明
KeyType 指定要重新產生的金鑰類型。 有效的值為:

- 主要
- 次要

回應

回應包括 HTTP 狀態碼、一組回應標頭和回應主體。

狀態碼

成功的作業會傳回狀態碼 200 (OK)。 如需狀態碼的相關資訊,請參閱 服務管理狀態和錯誤碼

回應標頭

這項作業的回應包括下列標頭。 回應也可能包括其他標準 HTTP 標頭。 所有標準標頭符合 HTTP/1.1 通訊協定規格

回應標頭 說明
x-ms-request-id 唯一識別對管理服務發出之要求的值。 您可以呼叫非同步作業, 取得作業狀態 以判斷作業已完成之標頭的值、 失敗,還是仍在進行中。

回應主體

回應會一併傳回主要和次要存取金鑰。 回應主體的格式如下:

  
<?xml version="1.0" encoding="utf-8"?> <StorageService xmlns="https://schemas.microsoft.com/windowsazure"> <Url>storage-service-request-uri</Url> <StorageServiceKeys> <Primary>primary-key</Primary> <Secondary>secondary-key</Secondary> </StorageServiceKeys> </StorageService>  
  

下表描述回應本文的元素。

元素名稱 說明
URL 服務管理 API 要求 URI 用來執行 取得儲存體帳戶屬性 對儲存體帳戶的要求。
主要 指定之儲存體帳戶的主要金鑰。
次要 指定之儲存體帳戶的次要金鑰。

備註

Regenerate Storage Account Keys 作業會導致重新產生儲存體帳戶服務的主要或次要金鑰。 這項作業可以搭配所傳回的儲存體帳戶 列出儲存體帳戶 作業,以自動化管理的存放區索引鍵更新。

範例

下列範例程式會採用訂閱 ID、相關聯的管理憑證指紋、作業版本字串和儲存體帳戶名稱,並且將傳回的儲存體帳戶存取金鑰列印到主控台。 然後呼叫 Regenerate Storage Account Keys 作業以重新產生儲存體帳戶,然後列印新金鑰結果的次要存取金鑰。 初始化 Version 常數是版本標頭字串、 SubscriptionId 訂閱的 GUID 識別碼 Thumbprint 與您管理憑證的指紋值,和 ServiceName 執行範例程式碼儲存體帳戶的名稱。

namespace Microsoft.WindowsAzure.ServiceManagementRESTAPI.Samples { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Xml; using System.Xml.Linq; public class Program { // Set these constants with your values to run the sample. private const string Version = "2011-10-01"; private const string Thumbprint = "management-certificate-thumbprint"; private const string SubscriptionId = "subscription-id-guid"; private const string ServiceName = "storage-account-name"; // This is the common namespace for all Service Management REST API XML data. private static XNamespace wa = "https://schemas.microsoft.com/windowsazure"; /// <summary> /// Gets or sets the certificate that matches the Thumbprint value. /// </summary> private static X509Certificate2 Certificate { get; set; } static void Main(string[] args) { try { Certificate = GetCertificate(Thumbprint); XElement initialKeys = GetStorageAccountKeys(SubscriptionId, ServiceName); Console.WriteLine( "Storage Account Keys for {0}:{1}{2}", ServiceName, Environment.NewLine, initialKeys.ToString(SaveOptions.OmitDuplicateNamespaces)); string keyType = "Secondary"; XElement regeneratedKeys = RegenerateStorageAccountKeys(SubscriptionId, ServiceName, keyType); Console.WriteLine( "Regenerated {0} Storage Account Key for {1}:{2}{3}", keyType, ServiceName, Environment.NewLine, regeneratedKeys.ToString(SaveOptions.OmitDuplicateNamespaces)); } catch (Exception ex) { Console.WriteLine("Exception caught in Main:"); Console.WriteLine(ex.Message); } Console.Write("Press any key to continue:"); Console.ReadKey(); } /// <summary> /// Gets the certificate matching the thumbprint from the local store. /// Throws an ArgumentException if a matching certificate is not found. /// </summary> /// <param name="thumbprint">The thumbprint of the certificate to find.</param> /// <returns>The certificate with the specified thumbprint.</returns> private static X509Certificate2 GetCertificate(string thumbprint) { List<StoreLocation> locations = new List<StoreLocation> { StoreLocation.CurrentUser, StoreLocation.LocalMachine }; foreach (var location in locations) { X509Store store = new X509Store("My", location); try { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection certificates = store.Certificates.Find( X509FindType.FindByThumbprint, thumbprint, false); if (certificates.Count == 1) { return certificates[0]; } } finally { store.Close(); } } throw new ArgumentException(string.Format( "A Certificate with Thumbprint '{0}' could not be located.", thumbprint)); } /// <summary> /// Calls the Get Storage Account Keys operation in the Service Management /// REST API for the specified subscription and storage account name and returns /// the StorageService XML element from the response. /// </summary> /// <param name="subscriptionId">The subscription identifier.</param> /// <param name="serviceName">The name of the storage account.</param> /// <returns>The StorageService XML element from the response.</returns> private static XElement GetStorageAccountKeys( string subscriptionId, string serviceName) { string uriFormat = "https://management.core.windows.net/{0}" + "/services/storageservices/{1}/keys"; Uri uri = new Uri(String.Format(uriFormat, subscriptionId, serviceName)); XDocument responseBody; string requestId; HttpStatusCode statusCode = InvokeRequest(uri, "GET", null, out responseBody, out requestId); VerifyResult(uri, statusCode, HttpStatusCode.OK, responseBody); return responseBody.Element(wa + "StorageService"); } /// <summary> /// Calls the Regenerate Storage Account Keys operation in the Service /// Management REST API for the specified subscription, storage account name, /// and key, and returns the StorageService XML element from the response. /// </summary> /// <param name="subscriptionId">The subscription identifier.</param> /// <param name="serviceName">The name of the storage account.</param> /// <param name="keyType">A value of "Primary" or "Secondary" to specify the key to regenerate.</param> /// <returns>The StorageService XML element from the response.</returns> private static XElement RegenerateStorageAccountKeys( string subscriptionId, string serviceName, string keyType) { string uriFormat = "https://management.core.windows.net/{0}" + "/services/storageservices/{1}/keys?action=regenerate"; Uri uri = new Uri(String.Format(uriFormat, subscriptionId, serviceName)); XDocument requestBody = new XDocument( new XDeclaration("1.0", "UTF-8", "no"), new XElement( wa + "RegenerateKeys", new XElement(wa + "KeyType", keyType))); XDocument responseBody; string requestId; HttpStatusCode statusCode = InvokeRequest(uri, "POST", requestBody, out responseBody, out requestId); VerifyResult(uri, statusCode, HttpStatusCode.OK, responseBody); return responseBody.Element(wa + "StorageService"); } /// <summary> /// A helper function to invoke a Service Management REST API operation. /// </summary> /// <param name="uri">The URI of the operation to invoke using a web request.</param> /// <param name="method">The method of the web request, GET, PUT, POST, or DELETE.</param> /// <param name="requestBody">The XML body to send with the web request. Use null to send no request body.</param> /// <param name="responseBody">The XML body returned by the request, if any.</param> /// <param name="requestId">The requestId returned by the request, if any.</param> /// <returns>The status code returned by the request.</returns> private static HttpStatusCode InvokeRequest( Uri uri, string method, XDocument requestBody, out XDocument responseBody, out string requestId) { responseBody = null; requestId = String.Empty; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.Method = method; request.Headers.Add("x-ms-Version", Version); request.ClientCertificates.Add(Certificate); request.ContentType = "application/xml"; if (requestBody != null) { using (Stream requestStream = request.GetRequestStream()) { using (StreamWriter streamWriter = new StreamWriter( requestStream, System.Text.UTF8Encoding.UTF8)) { requestBody.Save(streamWriter, SaveOptions.DisableFormatting); } } } HttpWebResponse response; HttpStatusCode statusCode = HttpStatusCode.Unused; try { response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { // GetResponse throws a WebException for 4XX and 5XX status codes response = (HttpWebResponse)ex.Response; } try { statusCode = response.StatusCode; if (response.ContentLength > 0) { using (XmlReader reader = XmlReader.Create(response.GetResponseStream())) { responseBody = XDocument.Load(reader); } } if (response.Headers != null) { requestId = response.Headers["x-ms-request-id"]; } } finally { response.Close(); } return statusCode; } /// <summary> /// A helper function to throw an ApplicationException on unexpected /// status code responses from Service Management REST API operation calls. /// </summary> /// <param name="uri">The URI of the Service Management operation.</param> /// <param name="statusCode">The status code returned by the operation.</param> /// <param name="expectedCode">The expected status code.</param> /// <param name="responseBody">The response body returned by the operation.</param> private static void VerifyResult( Uri uri, HttpStatusCode statusCode, HttpStatusCode expectedCode, XDocument responseBody) { if (!statusCode.Equals(expectedCode)) { throw new ApplicationException(string.Format( "Call to {0} returned an error:{1}Status Code: {2} ({3}):{1}{4}", uri.ToString(), Environment.NewLine, (int)statusCode, statusCode, responseBody.ToString(SaveOptions.OmitDuplicateNamespaces))); } return; } } }  
  

此範例程式會產生類似下面的結果:

Storage Account Keys for myexamplestorage1: <StorageService xmlns="https://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Url>https://management.core.windows.net/01234567-89ab-cdef-0123-456789abcdef/services/storageservices/myexamplestorage1</Url> <StorageServiceKeys> <Primary>XrmGWqu6qpgKX5G3lf+V5Bc0nFIGjGWiWhHTdMxkA5Mb4WjJ0rDV+3USWW/9fAWCrszrkr8+JUb1c5mxQdq4nw==</Primary> <Secondary>7jGHqUXHfASoUWeuClG9TXRZ59tTl5Fep8BNi5f86LFuewc0dQjDc6pyyju8BOi5947byrtgKnVtYO4f4cVdcg==</Secondary> </StorageServiceKeys> </StorageService> Regenerated Secondary Storage Account Key for myexamplestorage1: <StorageService xmlns="https://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Url>https://management.core.windows.net/01234567-89ab-cdef-0123-456789abcdef/services/storageservices/myexamplestorage1</Url> <StorageServiceKeys> <Primary>XrmGWqu6qpgKX5G3lf+V5Bc0nFIGjGWiWhHTdMxkA5Mb4WjJ0rDV+3USWW/9fAWCrszrkr8+JUb1c5mxQdq4nw==</Primary> <Secondary>2Wd7lP3MesbkFi0LAltwUd40L6uu85N9VBtokOo2RfpqKA8q39orkJ6WUV3jP4TkZuYrSQNYxkQ5axcSzzTu8A==</Secondary> </StorageServiceKeys> </StorageService> Press any key to continue: