Manage HMAC keys for service accounts  |  Cloud Storage  |  Google Cloud (2024)

Stay organized with collections Save and categorize content based on your preferences.

Overview

This page shows you how to create, disable, and delete Hash-based MessageAuthentication Code (HMAC) keys associated with service accounts in yourproject.

Before you begin

Before using this feature in Cloud Storage, you must meet the followingrequirements:

  1. Have sufficient permission to work with HMAC keys in the selected project:

    • If you own the project, you most likely have the necessary permissions.

    • You should have the IAM permissions that are prefixed withstorage.hmacKeys for the project. See Using IAM Permissions forinstructions on how to get a role, such as Storage HMAC Key Admin,that has these permissions.

  2. Have a service account in your project that you intend to create HMAC keysfor. See Creating a service account if you don't currently have one.

  3. Have the restrictAuthTypes constraint disabled for HMAC keyauthentication. See Creating and managing organization policies forinstructions on how to check and disable the constraint.

Create an HMAC key

To create an HMAC key for a service account:

Console

  1. In the Google Cloud console, go to the Cloud Storage Settings page.

    Go to Settings

  2. Select the Interoperability tab.

  3. Click add_boxCreate a key for a service account.

  4. Select the service account you want the HMAC key to be associated with.

  5. Click Create key.

To learn how to get detailed error information about failed Cloud Storage operations in the Google Cloud console, see Troubleshooting.

Command line

Use the hmac create command:

gcloud storage hmac create SERVICE_ACCOUNT_EMAIL

Where SERVICE_ACCOUNT_EMAIL is the email addressassociated with your service account. For example,service-7550275089395@my-pet-project.iam.gserviceaccount.com.

If successful, the response contains an HMAC key resource,including values for the accessId and secret.

Client libraries

C++

For more information, see the Cloud Storage C++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

namespace gcs = ::google::cloud::storage;using ::google::cloud::StatusOr;return [](gcs::Client client, std::string const& service_account_email) { StatusOr<std::pair<gcs::HmacKeyMetadata, std::string>> key_info = client.CreateHmacKey(service_account_email); if (!key_info) throw std::move(key_info).status(); std::cout << "The base64 encoded secret is: " << key_info->second << "\nDo not miss that secret, there is no API to recover it." << "\nThe HMAC key metadata is: " << key_info->first << "\n"; return key_info->first.access_id();}

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

using Google.Apis.Storage.v1.Data;using Google.Cloud.Storage.V1;using System;public class CreateHmacKeySample{ public HmacKey CreateHmacKey( string projectId = "your-project-id", string serviceAccountEmail = "dev@iam.gserviceaccount.com") { var storage = StorageClient.Create(); var key = storage.CreateHmacKey(projectId, serviceAccountEmail); var secret = key.Secret; var metadata = key.Metadata; Console.WriteLine($"The Base64 encoded secret is: {secret}"); Console.WriteLine("Make sure to save that secret, there's no API to recover it."); Console.WriteLine("The HMAC key metadata is:"); Console.WriteLine($"ID: {metadata.Id}"); Console.WriteLine($"Access ID: {metadata.AccessId}"); Console.WriteLine($"Project ID: {metadata.ProjectId}"); Console.WriteLine($"Service Account Email: {metadata.ServiceAccountEmail}"); Console.WriteLine($"State: {metadata.State}"); Console.WriteLine($"Time Created: {metadata.TimeCreated}"); Console.WriteLine($"Time Updated: {metadata.Updated}"); Console.WriteLine($"ETag: {metadata.ETag}"); return key; }}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import ("context""fmt""io""time""cloud.google.com/go/storage")// createHMACKey creates a new HMAC key using the given project and service account.func createHMACKey(w io.Writer, projectID string, serviceAccountEmail string) (*storage.HMACKey, error) {ctx := context.Background()// Initialize client.client, err := storage.NewClient(ctx)if err != nil {return nil, fmt.Errorf("storage.NewClient: %w", err)}defer client.Close() // Closing the client safely cleans up background resources.ctx, cancel := context.WithTimeout(ctx, time.Minute)defer cancel()key, err := client.CreateHMACKey(ctx, projectID, serviceAccountEmail)if err != nil {return nil, fmt.Errorf("CreateHMACKey: %w", err)}fmt.Fprintf(w, "%s\n", key)fmt.Fprintf(w, "The base64 encoded secret is %s\n", key.Secret)fmt.Fprintln(w, "Do not miss that secret, there is no API to recover it.")fmt.Fprintln(w, "The HMAC key metadata is")fmt.Fprintf(w, "%+v", key)return key, nil}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.storage.HmacKey;import com.google.cloud.storage.ServiceAccount;import com.google.cloud.storage.Storage;import com.google.cloud.storage.StorageException;import com.google.cloud.storage.StorageOptions;import java.util.Date;public class CreateHmacKey { public static void createHmacKey(String serviceAccountEmail, String projectId) throws StorageException { // The service account email for which the new HMAC key will be created. // String serviceAccountEmail = "service-account@iam.gserviceaccount.com"; // The ID of the project to which the service account belongs. // String projectId = "project-id"; Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService(); ServiceAccount account = ServiceAccount.of(serviceAccountEmail); HmacKey hmacKey = storage.createHmacKey(account, Storage.CreateHmacKeyOption.projectId(projectId)); String secret = hmacKey.getSecretKey(); HmacKey.HmacKeyMetadata metadata = hmacKey.getMetadata(); System.out.println("The Base64 encoded secret is: " + secret); System.out.println("Do not lose that secret, there is no API to recover it."); System.out.println("The HMAC key metadata is:"); System.out.println("ID: " + metadata.getId()); System.out.println("Access ID: " + metadata.getAccessId()); System.out.println("Project ID: " + metadata.getProjectId()); System.out.println("Service Account Email: " + metadata.getServiceAccount().getEmail()); System.out.println("State: " + metadata.getState().toString()); System.out.println("Time Created: " + new Date(metadata.getCreateTime()).toString()); System.out.println("Time Updated: " + new Date(metadata.getUpdateTime()).toString()); System.out.println("ETag: " + metadata.getEtag()); }}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/** * TODO(developer): Uncomment the following lines before running the sample. */// The service account email for which the new HMAC key will be created// const serviceAccountEmail = 'service-account@iam.gserviceaccount.com';// The ID of the project to which the service account belongs// const projectId = 'project-id';// Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage');// Creates a clientconst storage = new Storage();// Create HMAC SA Keyasync function createHmacKey() { const [hmacKey, secret] = await storage.createHmacKey(serviceAccountEmail, { projectId, }); console.log(`The base64 encoded secret is: ${secret}`); console.log('Do not miss that secret, there is no API to recover it.'); console.log('The HMAC key metadata is:'); for (const [key, value] of Object.entries(hmacKey.metadata)) { console.log(`${key}: ${value}`); }}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Storage\StorageClient;/** * Create a new HMAC key. * * @param string $projectId The ID of your Google Cloud Platform project. * (e.g. 'my-project-id') * @param string $serviceAccountEmail Service account email to associate with the new HMAC key. * (e.g. 'service-account@iam.gserviceaccount.com') */function create_hmac_key(string $projectId, string $serviceAccountEmail): void{ $storage = new StorageClient(); // By default createHmacKey will use the projectId used by StorageClient(). $hmacKeyCreated = $storage->createHmacKey($serviceAccountEmail, ['projectId' => $projectId]); printf('The base64 encoded secret is: %s' . PHP_EOL, $hmacKeyCreated->secret()); print('Do not miss that secret, there is no API to recover it.' . PHP_EOL); printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKeyCreated->hmacKey()->info(), true));}

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import storagedef create_key(project_id, service_account_email): """ Create a new HMAC key using the given project and service account. """ # project_id = 'Your Google Cloud project ID' # service_account_email = 'Service account used to generate the HMAC key' storage_client = storage.Client(project=project_id) hmac_key, secret = storage_client.create_hmac_key( service_account_email=service_account_email, project_id=project_id ) print(f"The base64 encoded secret is {secret}") print("Do not miss that secret, there is no API to recover it.") print("The HMAC key metadata is:") print(f"Service Account Email: {hmac_key.service_account_email}") print(f"Key ID: {hmac_key.id}") print(f"Access ID: {hmac_key.access_id}") print(f"Project ID: {hmac_key.project}") print(f"State: {hmac_key.state}") print(f"Created At: {hmac_key.time_created}") print(f"Updated At: {hmac_key.updated}") print(f"Etag: {hmac_key.etag}") return hmac_key

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def create_hmac_key service_account_email: # The service account email used to generate an HMAC key # service_account_email = "service-my-project-number@gs-project-accounts.iam.gserviceaccount.com" require "google/cloud/storage" storage = Google::Cloud::Storage.new # By default Storage#create_hmac_key uses the Storage client project_id hmac_key = storage.create_hmac_key service_account_email puts "The base64 encoded secret is: #{hmac_key.secret}" puts "Do not miss that secret, there is no API to recover it." puts "\nThe HMAC key metadata is:" puts "Key ID: #{hmac_key.id}" puts "Service Account Email: #{hmac_key.service_account_email}" puts "Access ID: #{hmac_key.access_id}" puts "Project ID: #{hmac_key.project_id}" puts "Active: #{hmac_key.active?}" puts "Created At: #{hmac_key.created_at}" puts "Updated At: #{hmac_key.updated_at}" puts "Etag: #{hmac_key.etag}"end

Terraform

You can use a Terraform resource to create an HMAC key. This sample also includes a resource to create a serviceaccount.

# Create a new service accountresource "google_service_account" "service_account" { account_id = "my-svc-acc"}# Create the HMAC key for the associated service accountresource "google_storage_hmac_key" "key" { service_account_email = google_service_account.service_account.email}

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, in order to generate an access token for the Authorization header.

    Alternatively, you can create an access token using theOAuth 2.0 Playgroundand include it in the Authorization header.

  2. Use cURL to call the JSON API with aPOST hmacKeys request,:

    curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/projects/PROJECT_IDENTIFIER/hmacKeys?serviceAccountEmail=SERVICE_ACCOUNT_EMAIL"

    Where:

    • PROJECT_IDENTIFIER is the ID or number forthe project associated with the key you want to create. Forexample, my-pet-project.
    • SERVICE_ACCOUNT_EMAIL is the emailaddress associated with your service account. For example,service-7550275089395@my-pet-project.iam.gserviceaccount.com.

XML API

  1. Have gcloud CLI installed and initialized, in order to generate an access token for the Authorization header.

    Alternatively, you can create an access token using theOAuth 2.0 Playgroundand include it in the Authorization header.

  2. Use cURL to call the XML API with a POST HMAC Keyrequest:

    curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/?Action=CreateAccessKey&UserName=SERVICE_ACCOUNT_EMAIL"

    Where SERVICE_ACCOUNT_EMAIL is the emailaddress associated with your service account. For example,service-7550275089395@my-pet-project.iam.gserviceaccount.com.

Get HMAC key information

To list the HMAC keys for a project, and get information about the keys:

Console

  1. In the Google Cloud console, go to the Cloud Storage Settings page.

    Go to Settings

  2. Select the Interoperability tab.

    Service accounts that have HMAC keys associated with them appear in theAccess keys for service accounts subsection of theService account HMAC section.

  3. Click the name of a specific service account to see the HMAC keysassociated with it and the status of those keys.

Command line

  1. Use the hmac list command to list hmac keys in your project:

    gcloud storage hmac list

    If successful, the command returns a list of hmac key access IDs,along with the state of each key and the service account associatedwith each key.

  2. Use the hmac describe command to retrieve metadata for aspecific key:

    gcloud storage hmac describe KEY_ACCESS_ID 

    Where KEY_ACCESS_ID is the access ID for thedesired key.

Client libraries

C++

For more information, see the Cloud Storage C++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample retrieves a list of HMAC keys associated with a project:

namespace gcs = ::google::cloud::storage;using ::google::cloud::StatusOr;[](gcs::Client client) { int count = 0; gcs::ListHmacKeysReader hmac_keys_list = client.ListHmacKeys(); for (auto& key : hmac_keys_list) { if (!key) throw std::move(key).status(); std::cout << "service_account_email = " << key->service_account_email() << "\naccess_id = " << key->access_id() << "\n"; ++count; } if (count == 0) { std::cout << "No HMAC keys in default project\n"; }}

The following sample retrieves information for a specific HMAC key:

namespace gcs = ::google::cloud::storage;using ::google::cloud::StatusOr;[](gcs::Client client, std::string const& access_id) { StatusOr<gcs::HmacKeyMetadata> hmac_key = client.GetHmacKey(access_id); if (!hmac_key) throw std::move(hmac_key).status(); std::cout << "The HMAC key metadata is: " << *hmac_key << "\n";}

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample retrieves a list of HMAC keys associated with a project:

using Google.Apis.Storage.v1.Data;using Google.Cloud.Storage.V1;using System;using System.Collections.Generic;public class ListHmacKeysSample{ public IEnumerable<HmacKeyMetadata> ListHmacKeys(string projectId = "your-project-id") { var storage = StorageClient.Create(); var keys = storage.ListHmacKeys(projectId); foreach (var key in keys) { Console.WriteLine($"Service Account Email: {key.ServiceAccountEmail}"); Console.WriteLine($"Access ID: {key.AccessId}"); } return keys; }}

The following sample retrieves information for a specific HMAC key:

using Google.Apis.Storage.v1.Data;using Google.Cloud.Storage.V1;using System;public class GetHmacKeySample{ public HmacKeyMetadata GetHmacKey( string projectId = "your-project-id", string accessId = "your-access-id") { var storage = StorageClient.Create(); var metadata = storage.GetHmacKey(projectId, accessId); Console.WriteLine("The HMAC key metadata is:"); Console.WriteLine($"ID: {metadata.Id}"); Console.WriteLine($"Access ID: {metadata.AccessId}"); Console.WriteLine($"Project ID: {metadata.ProjectId}"); Console.WriteLine($"Service Account Email: {metadata.ServiceAccountEmail}"); Console.WriteLine($"State: {metadata.State}"); Console.WriteLine($"Time Created: {metadata.TimeCreated}"); Console.WriteLine($"Time Updated: {metadata.Updated}"); Console.WriteLine($"ETag: {metadata.ETag}"); return metadata; }}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample retrieves a list of HMAC keys associated with a project:

import ("context""fmt""io""time""cloud.google.com/go/storage""google.golang.org/api/iterator")// listHMACKeys lists all HMAC keys associated with the project.func listHMACKeys(w io.Writer, projectID string) ([]*storage.HMACKey, error) {ctx := context.Background()// Initialize client.client, err := storage.NewClient(ctx)if err != nil {return nil, fmt.Errorf("storage.NewClient: %w", err)}defer client.Close() // Closing the client safely cleans up background resources.ctx, cancel := context.WithTimeout(ctx, time.Minute)defer cancel()iter := client.ListHMACKeys(ctx, projectID)var keys []*storage.HMACKeyfor {key, err := iter.Next()if err == iterator.Done {break}if err != nil {return nil, fmt.Errorf("ListHMACKeys: %w", err)}fmt.Fprintf(w, "Service Account Email: %s\n", key.ServiceAccountEmail)fmt.Fprintf(w, "Access ID: %s\n", key.AccessID)keys = append(keys, key)}return keys, nil}

The following sample retrieves information for a specific HMAC key:

import ("context""fmt""io""time""cloud.google.com/go/storage")// getHMACKey retrieves the HMACKeyMetadata with the given access id.func getHMACKey(w io.Writer, accessID string, projectID string) (*storage.HMACKey, error) {ctx := context.Background()// Initialize client.client, err := storage.NewClient(ctx)if err != nil {return nil, fmt.Errorf("storage.NewClient: %w", err)}defer client.Close() // Closing the client safely cleans up background resources.handle := client.HMACKeyHandle(projectID, accessID)ctx, cancel := context.WithTimeout(ctx, time.Minute)defer cancel()key, err := handle.Get(ctx)if err != nil {return nil, fmt.Errorf("Get: %w", err)}fmt.Fprintln(w, "The HMAC key metadata is:")fmt.Fprintf(w, "%+v", key)return key, nil}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample retrieves a list of HMAC keys associated with a project:

import com.google.api.gax.paging.Page;import com.google.cloud.storage.HmacKey;import com.google.cloud.storage.Storage;import com.google.cloud.storage.StorageException;import com.google.cloud.storage.StorageOptions;public class ListHmacKeys { public static void listHmacKeys(String projectId) throws StorageException { // The ID of the project to which the service account belongs. // String projectId = "project-id"; Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService(); Page<HmacKey.HmacKeyMetadata> page = storage.listHmacKeys(Storage.ListHmacKeysOption.projectId(projectId)); for (HmacKey.HmacKeyMetadata metadata : page.iterateAll()) { System.out.println("Service Account Email: " + metadata.getServiceAccount().getEmail()); System.out.println("Access ID: " + metadata.getAccessId()); } }}

The following sample retrieves information for a specific HMAC key:

import com.google.cloud.storage.HmacKey;import com.google.cloud.storage.Storage;import com.google.cloud.storage.StorageException;import com.google.cloud.storage.StorageOptions;import java.util.Date;public class GetHmacKey { public static void getHmacKey(String accessId, String projectId) throws StorageException { // The access ID of the HMAC key. // String accessId = "GOOG0234230X00"; // The ID of the project to which the service account belongs. // String projectId = "project-id"; Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService(); HmacKey.HmacKeyMetadata metadata = storage.getHmacKey(accessId, Storage.GetHmacKeyOption.projectId(projectId)); System.out.println("The HMAC key metadata is:"); System.out.println("ID: " + metadata.getId()); System.out.println("Access ID: " + metadata.getAccessId()); System.out.println("Project ID: " + metadata.getProjectId()); System.out.println("Service Account Email: " + metadata.getServiceAccount().getEmail()); System.out.println("State: " + metadata.getState().toString()); System.out.println("Time Created: " + new Date(metadata.getCreateTime()).toString()); System.out.println("Time Updated: " + new Date(metadata.getUpdateTime()).toString()); System.out.println("ETag: " + metadata.getEtag()); }}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample retrieves a list of HMAC keys associated with a project:

/** * TODO(developer): Uncomment the following lines before running the sample. */// The ID of the project to which the service account belongs// const projectId = 'project-id';// Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage');// Creates a clientconst storage = new Storage();// List HMAC SA Keys' Metadataasync function listHmacKeys() { const [hmacKeys] = await storage.getHmacKeys({projectId}); // hmacKeys is an array of HmacKey objects. for (const hmacKey of hmacKeys) { console.log( `Service Account Email: ${hmacKey.metadata.serviceAccountEmail}` ); console.log(`Access Id: ${hmacKey.metadata.accessId}`); }}

The following sample retrieves information for a specific HMAC key:

/** * TODO(developer): Uncomment the following lines before running the sample. */// The access ID of the HMAC key// const hmacKeyAccessId = 'GOOG0234230X00';// The ID of the project to which the service account belongs// const projectId = 'project-id';// Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage');// Creates a clientconst storage = new Storage();// Get HMAC SA Key Metadataasync function getHmacKey() { const hmacKey = storage.hmacKey(hmacKeyAccessId, {projectId}); // Populate the hmacKey object with metadata from server. await hmacKey.getMetadata(); console.log('The HMAC key metadata is:'); for (const [key, value] of Object.entries(hmacKey.metadata)) { console.log(`${key}: ${value}`); }}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample retrieves a list of HMAC keys associated with a project:

use Google\Cloud\Storage\StorageClient;/** * List HMAC keys. * * @param string $projectId The ID of your Google Cloud Platform project. * (e.g. 'my-project-id') */function list_hmac_keys(string $projectId): void{ $storage = new StorageClient(); // By default hmacKeys will use the projectId used by StorageClient() to list HMAC Keys. $hmacKeys = $storage->hmacKeys(['projectId' => $projectId]); printf('HMAC Key\'s:' . PHP_EOL); foreach ($hmacKeys as $hmacKey) { printf('Service Account Email: %s' . PHP_EOL, $hmacKey->info()['serviceAccountEmail']); printf('Access Id: %s' . PHP_EOL, $hmacKey->info()['accessId']); }}

The following sample retrieves information for a specific HMAC key:

use Google\Cloud\Storage\StorageClient;/** * Get an HMAC key. * * @param string $projectId The ID of your Google Cloud Platform project. * (e.g. 'my-project-id') * @param string $accessId Access ID for an HMAC key. (e.g. 'GOOG0234230X00') */function get_hmac_key(string $projectId, string $accessId): void{ $storage = new StorageClient(); $hmacKey = $storage->hmacKey($accessId, $projectId); printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKey->info(), true));}

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample retrieves a list of HMAC keys associated with a project:

from google.cloud import storagedef list_keys(project_id): """ List all HMAC keys associated with the project. """ # project_id = "Your Google Cloud project ID" storage_client = storage.Client(project=project_id) hmac_keys = storage_client.list_hmac_keys(project_id=project_id) print("HMAC Keys:") for hmac_key in hmac_keys: print( f"Service Account Email: {hmac_key.service_account_email}" ) print(f"Access ID: {hmac_key.access_id}") return hmac_keys

The following sample retrieves information for a specific HMAC key:

from google.cloud import storagedef get_key(access_id, project_id): """ Retrieve the HMACKeyMetadata with the given access id. """ # project_id = "Your Google Cloud project ID" # access_id = "ID of an HMAC key" storage_client = storage.Client(project=project_id) hmac_key = storage_client.get_hmac_key_metadata( access_id, project_id=project_id ) print("The HMAC key metadata is:") print(f"Service Account Email: {hmac_key.service_account_email}") print(f"Key ID: {hmac_key.id}") print(f"Access ID: {hmac_key.access_id}") print(f"Project ID: {hmac_key.project}") print(f"State: {hmac_key.state}") print(f"Created At: {hmac_key.time_created}") print(f"Updated At: {hmac_key.updated}") print(f"Etag: {hmac_key.etag}") return hmac_key

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample retrieves a list of HMAC keys associated with a project:

def list_hmac_keys require "google/cloud/storage" storage = Google::Cloud::Storage.new # By default Storage#hmac_keys uses the Storage client project_id hmac_keys = storage.hmac_keys puts "HMAC Keys:" hmac_keys.all do |hmac_key| puts "Service Account Email: #{hmac_key.service_account_email}" puts "Access ID: #{hmac_key.access_id}" endend

The following sample retrieves information for a specific HMAC key:

def get_hmac_key access_id: # The access ID of the HMAC key # access_id = "GOOG0234230X00" require "google/cloud/storage" storage = Google::Cloud::Storage.new # By default Storage#hmac_keys uses the Storage client project_id hmac_key = storage.hmac_key access_id puts "The HMAC key metadata is:" puts "Key ID: #{hmac_key.id}" puts "Service Account Email: #{hmac_key.service_account_email}" puts "Access ID: #{hmac_key.access_id}" puts "Project ID: #{hmac_key.project_id}" puts "Active: #{hmac_key.active?}" puts "Created At: #{hmac_key.created_at}" puts "Updated At: #{hmac_key.updated_at}" puts "Etag: #{hmac_key.etag}"end

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, in order to generate an access token for the Authorization header.

    Alternatively, you can create an access token using theOAuth 2.0 Playgroundand include it in the Authorization header.

  2. Use cURL to call the JSON API with aLIST hmacKeys request:

    curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ "https://storage.googleapis.com/storage/v1/projects/PROJECT_IDENTIFIER/hmacKeys"

    Where PROJECT_IDENTIFIER is the ID or numberfor the project associated with the keys you want to list. Forexample, my-pet-project.

XML API

  1. Have gcloud CLI installed and initialized, in order to generate an access token for the Authorization header.

    Alternatively, you can create an access token using theOAuth 2.0 Playgroundand include it in the Authorization header.

  2. Use cURL to call the XML API with a GET HMAC Keyrequest:

    curl -X GET \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/?Action=ListAccessKeys&UserName=SERVICE_ACCOUNT_EMAIL"

    Where SERVICE_ACCOUNT_EMAIL is the emailaddress associated with your service account. For example,service-7550275089395@my-pet-project.iam.gserviceaccount.com.

Update the state of an HMAC key

To switch an HMAC key between being active and inactive:

Console

  1. In the Google Cloud console, go to the Cloud Storage Settings page.

    Go to Settings

  2. Select the Interoperability tab.

  3. In the Access keys for service accounts subsection, click the name ofthe service account associated with the HMAC key whose status you wantto update.

  4. Click the status of the key you want to update.

    • If you are changing the key's state from Inactive to Active, clickDeactivate in the window that appears.

    • If you are changing the key's state from Active to Inactive, noadditional steps are required.

Command line

Use the hmac update command:

gcloud storage hmac update ACCESS_KEY_ID STATE

Where:

  • ACCESS_KEY_ID is the access ID associated withthe key you are updating.
  • STATE is either --activate or--deactivate.

If successful, the command returns the updated metadata of the HMAC key.

Client libraries

C++

For more information, see the Cloud Storage C++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample deactivates an HMAC key:

namespace gcs = ::google::cloud::storage;using ::google::cloud::StatusOr;[](gcs::Client client, std::string const& access_id) { StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey( access_id, gcs::HmacKeyMetadata().set_state( gcs::HmacKeyMetadata::state_inactive())); if (!updated) throw std::move(updated).status(); if (updated->state() != gcs::HmacKeyMetadata::state_inactive()) { throw std::runtime_error("The HMAC key is active, this is unexpected"); } std::cout << "The HMAC key is now inactive\nFull metadata: " << *updated << "\n";}

The following sample activates an HMAC key:

namespace gcs = ::google::cloud::storage;using ::google::cloud::StatusOr;[](gcs::Client client, std::string const& access_id) { StatusOr<gcs::HmacKeyMetadata> updated = client.UpdateHmacKey( access_id, gcs::HmacKeyMetadata().set_state(gcs::HmacKeyMetadata::state_active())); if (!updated) throw std::move(updated).status(); if (updated->state() != gcs::HmacKeyMetadata::state_active()) { throw std::runtime_error( "The HMAC key is NOT active, this is unexpected"); } std::cout << "The HMAC key is now active\nFull metadata: " << *updated << "\n";}

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample deactivates an HMAC key:

using Google.Apis.Storage.v1.Data;using Google.Cloud.Storage.V1;using System;public class DeactivateHmacKeySample{ public HmacKeyMetadata DeactivateHmacKey( string projectId = "your-project-id", string accessId = "your-access-id") { var storage = StorageClient.Create(); var metadata = storage.GetHmacKey(projectId, accessId); metadata.State = HmacKeyStates.Inactive; var updatedMetadata = storage.UpdateHmacKey(metadata); Console.WriteLine("The HMAC key is now inactive."); Console.WriteLine("The HMAC key metadata is:"); Console.WriteLine($"ID: {updatedMetadata.Id}"); Console.WriteLine($"Access ID: {updatedMetadata.AccessId}"); Console.WriteLine($"Project ID: {updatedMetadata.ProjectId}"); Console.WriteLine($"Service Account Email: {updatedMetadata.ServiceAccountEmail}"); Console.WriteLine($"State: {updatedMetadata.State}"); Console.WriteLine($"Time Created: {updatedMetadata.TimeCreated}"); Console.WriteLine($"Time Updated: {updatedMetadata.Updated}"); Console.WriteLine($"ETag: {updatedMetadata.ETag}"); return updatedMetadata; }}

The following sample activates an HMAC key:

using Google.Apis.Storage.v1.Data;using Google.Cloud.Storage.V1;using System;public class ActivateHmacKeySample{ public HmacKeyMetadata ActivateHmacKey( string projectId = "your-project-id", string accessId = "access-id") { var storage = StorageClient.Create(); var metadata = storage.GetHmacKey(projectId, accessId); metadata.State = HmacKeyStates.Active; var updatedMetadata = storage.UpdateHmacKey(metadata); Console.WriteLine("The HMAC key is now active."); Console.WriteLine("The HMAC key metadata is:"); Console.WriteLine($"ID: {updatedMetadata.Id}"); Console.WriteLine($"Access ID: {updatedMetadata.AccessId}"); Console.WriteLine($"Project ID: {updatedMetadata.ProjectId}"); Console.WriteLine($"Service Account Email: {updatedMetadata.ServiceAccountEmail}"); Console.WriteLine($"State: {updatedMetadata.State}"); Console.WriteLine($"Time Created: {updatedMetadata.TimeCreated}"); Console.WriteLine($"Time Updated: {updatedMetadata.Updated}"); Console.WriteLine($"ETag: {updatedMetadata.ETag}"); return updatedMetadata; }}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample deactivates an HMAC key:

import ("context""fmt""io""time""cloud.google.com/go/storage")// deactivateHMACKey deactivates the HMAC key with the given access ID.func deactivateHMACKey(w io.Writer, accessID string, projectID string) (*storage.HMACKey, error) {ctx := context.Background()// Initialize client.client, err := storage.NewClient(ctx)if err != nil {return nil, fmt.Errorf("storage.NewClient: %w", err)}defer client.Close() // Closing the client safely cleans up background resources.ctx, cancel := context.WithTimeout(ctx, time.Minute)defer cancel()handle := client.HMACKeyHandle(projectID, accessID)key, err := handle.Update(ctx, storage.HMACKeyAttrsToUpdate{State: "INACTIVE"})if err != nil {return nil, fmt.Errorf("Update: %w", err)}fmt.Fprintln(w, "The HMAC key metadata is:")fmt.Fprintf(w, "%+v", key)return key, nil}

The following sample activates an HMAC key:

import ("context""fmt""io""time""cloud.google.com/go/storage")// activateHMACKey activates the HMAC key with the given access ID.func activateHMACKey(w io.Writer, accessID string, projectID string) (*storage.HMACKey, error) {ctx := context.Background()// Initialize client.client, err := storage.NewClient(ctx)if err != nil {return nil, fmt.Errorf("storage.NewClient: %w", err)}defer client.Close() // Closing the client safely cleans up background resources.handle := client.HMACKeyHandle(projectID, accessID)ctx, cancel := context.WithTimeout(ctx, time.Minute)defer cancel()key, err := handle.Update(ctx, storage.HMACKeyAttrsToUpdate{State: "ACTIVE"})if err != nil {return nil, fmt.Errorf("Update: %w", err)}fmt.Fprintln(w, "The HMAC key metadata is:")fmt.Fprintf(w, "%+v", key)return key, nil}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample deactivates an HMAC key:

import com.google.cloud.storage.HmacKey;import com.google.cloud.storage.Storage;import com.google.cloud.storage.StorageException;import com.google.cloud.storage.StorageOptions;import java.util.Date;public class DeactivateHmacKey { public static void deactivateHmacKey(String accessId, String projectId) throws StorageException { // The access ID of the HMAC key. // String accessId = "GOOG0234230X00"; // The ID of the project to which the service account belongs. // String projectId = "project-id"; Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService(); HmacKey.HmacKeyMetadata metadata = storage.getHmacKey(accessId, Storage.GetHmacKeyOption.projectId(projectId)); HmacKey.HmacKeyMetadata newMetadata = storage.updateHmacKeyState(metadata, HmacKey.HmacKeyState.INACTIVE); System.out.println("The HMAC key is now inactive."); System.out.println("The HMAC key metadata is:"); System.out.println("ID: " + newMetadata.getId()); System.out.println("Access ID: " + newMetadata.getAccessId()); System.out.println("Project ID: " + newMetadata.getProjectId()); System.out.println("Service Account Email: " + newMetadata.getServiceAccount().getEmail()); System.out.println("State: " + newMetadata.getState().toString()); System.out.println("Time Created: " + new Date(newMetadata.getCreateTime()).toString()); System.out.println("Time Updated: " + new Date(newMetadata.getUpdateTime()).toString()); System.out.println("ETag: " + newMetadata.getEtag()); }}

The following sample activates an HMAC key:

import com.google.cloud.storage.HmacKey;import com.google.cloud.storage.Storage;import com.google.cloud.storage.StorageException;import com.google.cloud.storage.StorageOptions;import java.util.Date;public class ActivateHmacKey { public static void activateHmacKey(String accessId, String projectId) throws StorageException { // The access ID of the HMAC key. // String accessId = "GOOG0234230X00"; // The ID of the project to which the service account belongs. // String projectId = "project-id"; Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService(); HmacKey.HmacKeyMetadata metadata = storage.getHmacKey(accessId, Storage.GetHmacKeyOption.projectId(projectId)); HmacKey.HmacKeyMetadata newMetadata = storage.updateHmacKeyState(metadata, HmacKey.HmacKeyState.ACTIVE); System.out.println("The HMAC key is now active."); System.out.println("The HMAC key metadata is:"); System.out.println("ID: " + newMetadata.getId()); System.out.println("Access ID: " + newMetadata.getAccessId()); System.out.println("Project ID: " + newMetadata.getProjectId()); System.out.println("Service Account Email: " + newMetadata.getServiceAccount().getEmail()); System.out.println("State: " + newMetadata.getState().toString()); System.out.println("Time Created: " + new Date(newMetadata.getCreateTime()).toString()); System.out.println("Time Updated: " + new Date(newMetadata.getUpdateTime()).toString()); System.out.println("ETag: " + newMetadata.getEtag()); }}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample deactivates an HMAC key:

/** * TODO(developer): Uncomment the following lines before running the sample. */// The access ID of the HMAC key// const hmacKeyAccessId = 'GOOG0234230X00';// The ID of the project to which the service account belongs// const projectId = 'project-id';// Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage');// Creates a clientconst storage = new Storage();// Deactivate HMAC SA Keyasync function deactivateHmacKey() { const hmacKey = storage.hmacKey(hmacKeyAccessId, {projectId}); const [hmacKeyMetadata] = await hmacKey.setMetadata({state: 'INACTIVE'}); console.log('The HMAC key is now inactive.'); console.log('The HMAC key metadata is:'); for (const [key, value] of Object.entries(hmacKeyMetadata)) { console.log(`${key}: ${value}`); }}

The following sample activates an HMAC key:

/** * TODO(developer): Uncomment the following lines before running the sample. */// The access ID of the HMAC key// const hmacKeyAccessId = 'GOOG0234230X00';// The ID of the project to which the service account belongs// const projectId = 'project-id';// Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage');// Creates a clientconst storage = new Storage();// Activate HMAC SA Keyasync function activateHmacKey() { const hmacKey = storage.hmacKey(hmacKeyAccessId, {projectId}); const [hmacKeyMetadata] = await hmacKey.setMetadata({state: 'ACTIVE'}); console.log('The HMAC key is now active.'); console.log('The HMAC key metadata is:'); for (const [key, value] of Object.entries(hmacKeyMetadata)) { console.log(`${key}: ${value}`); }}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample deactivates an HMAC key:

use Google\Cloud\Storage\StorageClient;/** * Deactivate an HMAC key. * * @param string $projectId The ID of your Google Cloud Platform project. * (e.g. 'my-project-id') * @param string $accessId Access ID for an inactive HMAC key. * (e.g. 'GOOG0234230X00') */function deactivate_hmac_key(string $projectId, string $accessId): void{ $storage = new StorageClient(); // By default hmacKey will use the projectId used by StorageClient(). $hmacKey = $storage->hmacKey($accessId, $projectId); $hmacKey->update('INACTIVE'); print('The HMAC key is now inactive.' . PHP_EOL); printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKey->info(), true));}

The following sample activates an HMAC key:

use Google\Cloud\Storage\StorageClient;/** * Activate an HMAC key. * * @param string $projectId The ID of your Google Cloud Platform project. * (e.g. 'my-project-id') * @param string $accessId Access ID for an inactive HMAC key. * (e.g. 'GOOG0234230X00') */function activate_hmac_key(string $projectId, string $accessId): void{ $storage = new StorageClient(); // By default hmacKey will use the projectId used by StorageClient(). $hmacKey = $storage->hmacKey($accessId, $projectId); $hmacKey->update('ACTIVE'); print('The HMAC key is now active.' . PHP_EOL); printf('HMAC key Metadata: %s' . PHP_EOL, print_r($hmacKey->info(), true));}

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample deactivates an HMAC key:

from google.cloud import storagedef deactivate_key(access_id, project_id): """ Deactivate the HMAC key with the given access ID. """ # project_id = "Your Google Cloud project ID" # access_id = "ID of an active HMAC key" storage_client = storage.Client(project=project_id) hmac_key = storage_client.get_hmac_key_metadata( access_id, project_id=project_id ) hmac_key.state = "INACTIVE" hmac_key.update() print("The HMAC key is now inactive.") print("The HMAC key metadata is:") print(f"Service Account Email: {hmac_key.service_account_email}") print(f"Key ID: {hmac_key.id}") print(f"Access ID: {hmac_key.access_id}") print(f"Project ID: {hmac_key.project}") print(f"State: {hmac_key.state}") print(f"Created At: {hmac_key.time_created}") print(f"Updated At: {hmac_key.updated}") print(f"Etag: {hmac_key.etag}") return hmac_key

The following sample activates an HMAC key:

from google.cloud import storagedef activate_key(access_id, project_id): """ Activate the HMAC key with the given access ID. """ # project_id = "Your Google Cloud project ID" # access_id = "ID of an inactive HMAC key" storage_client = storage.Client(project=project_id) hmac_key = storage_client.get_hmac_key_metadata( access_id, project_id=project_id ) hmac_key.state = "ACTIVE" hmac_key.update() print("The HMAC key metadata is:") print(f"Service Account Email: {hmac_key.service_account_email}") print(f"Key ID: {hmac_key.id}") print(f"Access ID: {hmac_key.access_id}") print(f"Project ID: {hmac_key.project}") print(f"State: {hmac_key.state}") print(f"Created At: {hmac_key.time_created}") print(f"Updated At: {hmac_key.updated}") print(f"Etag: {hmac_key.etag}") return hmac_key

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

The following sample deactivates an HMAC key:

def deactivate_hmac_key access_id: # The access ID of the HMAC key # access_id = "GOOG0234230X00" require "google/cloud/storage" storage = Google::Cloud::Storage.new # By default Storage#hmac_keys uses the Storage client project_id hmac_key = storage.hmac_key access_id hmac_key.inactive! puts "The HMAC key is now inactive." puts "The HMAC key metadata is:" puts "Key ID: #{hmac_key.id}" puts "Service Account Email: #{hmac_key.service_account_email}" puts "Access ID: #{hmac_key.access_id}" puts "Project ID: #{hmac_key.project_id}" puts "Active: #{hmac_key.active?}" puts "Created At: #{hmac_key.created_at}" puts "Updated At: #{hmac_key.updated_at}" puts "Etag: #{hmac_key.etag}"end

The following sample activates an HMAC key:

def activate_hmac_key access_id: # The access ID of the HMAC key # access_id = "GOOG0234230X00" require "google/cloud/storage" storage = Google::Cloud::Storage.new # By default Storage#hmac_keys uses the Storage client project_id hmac_key = storage.hmac_key access_id hmac_key.active! puts "The HMAC key is now active." puts "The HMAC key metadata is:" puts "Key ID: #{hmac_key.id}" puts "Service Account Email: #{hmac_key.service_account_email}" puts "Access ID: #{hmac_key.access_id}" puts "Project ID: #{hmac_key.project_id}" puts "Active: #{hmac_key.active?}" puts "Created At: #{hmac_key.created_at}" puts "Updated At: #{hmac_key.updated_at}" puts "Etag: #{hmac_key.etag}"end

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, in order to generate an access token for the Authorization header.

    Alternatively, you can create an access token using theOAuth 2.0 Playgroundand include it in the Authorization header.

  2. Create a JSON file that contains the following information:

    {"state": "STATE"}

    Where STATE is the desired state forthe key. For example, INACTIVE.

  3. Use cURL to call the JSON API with aPUT hmacKeys request:

    curl -X PUT --data-binary @JSON_FILE_NAME \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ "https://storage.googleapis.com/storage/v1/projects/PROJECT_IDENTIFIER/hmacKeys/ACCESS_KEY_ID"

    Where:

    • JSON_FILE_NAME is the path for the filethat you created in Step 2.
    • PROJECT_IDENTIFIER is the ID or numberfor the project associated with the key you want to update. Forexample, my-pet-project.
    • ACCESS_KEY_ID is the access ID associatedwith the key you are updating.

XML API

  1. Have gcloud CLI installed and initialized, in order to generate an access token for the Authorization header.

    Alternatively, you can create an access token using theOAuth 2.0 Playgroundand include it in the Authorization header.

  2. Use cURL to call the XML API with a POST HMAC Keyrequest:

    curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/?Action=UpdateAccessKey&AccessKeyId=ACCESS_KEY_ID&Status=STATUS"

    Where:

    • ACCESS_KEY_ID is the access ID associatedwith the key you are updating.
    • STATUS is the desired status for thekey. For example, Inactive.

When you change the state of an HMAC key, it takes up to 3 minutes for thestate change to propagate through the Cloud Storage system. For thisreason, you should wait at least 3 minutes between making an HMAC key inactiveand deleting the key.

Delete an HMAC key

An HMAC key must be in an inactive state in order to delete it.To delete an inactive HMAC key:

Console

  1. In the Google Cloud console, go to the Cloud Storage Settings page.

    Go to Settings

  2. Select the Interoperability tab.

  3. In the Access keys for service accounts subsection, click the name ofthe service account associated with the HMAC key you want to delete.

  4. Click the Trash icon associated with the key you want to delete.

  5. In the dialog that appears, enter the first 10 characters of theaccess key ID as they are given in the window.

  6. Click Delete.

Command line

Use the hmac delete command:

gcloud storage hmac delete ACCESS_KEY_ID

Where ACCESS_KEY_ID is the access ID associatedwith the key you are deleting.

If successful, the command does not return a response.

Client libraries

C++

For more information, see the Cloud Storage C++ API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

namespace gcs = ::google::cloud::storage;[](gcs::Client client, std::string const& access_id) { google::cloud::Status status = client.DeleteHmacKey(access_id); if (!status.ok()) throw std::runtime_error(status.message()); std::cout << "The key is deleted, though it may still appear" << " in ListHmacKeys() results.\n";}

C#

For more information, see the Cloud Storage C# API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

using Google.Cloud.Storage.V1;using System;public class DeleteHmacKeySample{ public void DeleteHmacKey( string projectId = "your-project-id", string accessId = "your-access-id") { var storage = StorageClient.Create(); storage.DeleteHmacKey(projectId, accessId); Console.WriteLine($"Key {accessId} was deleted."); }}

Go

For more information, see the Cloud Storage Go API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import ("context""fmt""io""time""cloud.google.com/go/storage")// deleteHMACKey deletes the HMAC key with the given access ID. Key must have state// INACTIVE in order to succeed.func deleteHMACKey(w io.Writer, accessID string, projectID string) error {ctx := context.Background()// Initialize client.client, err := storage.NewClient(ctx)if err != nil {return fmt.Errorf("storage.NewClient: %w", err)}defer client.Close() // Closing the client safely cleans up background resources.handle := client.HMACKeyHandle(projectID, accessID)ctx, cancel := context.WithTimeout(ctx, time.Minute)defer cancel()if err = handle.Delete(ctx); err != nil {return fmt.Errorf("Delete: %w", err)}fmt.Fprintln(w, "The key is deleted, though it may still appear in ListHMACKeys results.")return nil}

Java

For more information, see the Cloud Storage Java API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.storage.HmacKey;import com.google.cloud.storage.Storage;import com.google.cloud.storage.StorageException;import com.google.cloud.storage.StorageOptions;public class DeleteHmacKey { public static void deleteHmacKey(String accessId, String projectId) throws StorageException { // The access ID of the HMAC key. // String accessId = "GOOG0234230X00"; // The ID of the project to which the service account belongs. // String projectId = "project-id"; Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService(); HmacKey.HmacKeyMetadata metadata = storage.getHmacKey(accessId, Storage.GetHmacKeyOption.projectId(projectId)); storage.deleteHmacKey(metadata); System.out.println( "The key is deleted, though it will still appear in " + "getHmacKeys() results if called with showDeletedKey."); }}

Node.js

For more information, see the Cloud Storage Node.js API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/** * TODO(developer): Uncomment the following lines before running the sample. */// The access ID of the HMAC key// const hmacKeyAccessId = 'GOOG0234230X00';// The ID of the project to which the service account belongs// const projectId = 'project-id';// Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage');// Creates a clientconst storage = new Storage();// Delete HMAC SA Keyasync function deleteHmacKey() { const hmacKey = storage.hmacKey(hmacKeyAccessId, {projectId}); await hmacKey.delete(); console.log( 'The key is deleted, though it may still appear in getHmacKeys() results.' );}

PHP

For more information, see the Cloud Storage PHP API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

use Google\Cloud\Storage\StorageClient;/** * Delete an HMAC key. * * @param string $projectId The ID of your Google Cloud Platform project. * (e.g. 'my-project-id') * @param string $accessId Access ID for an HMAC key. (e.g. 'GOOG0234230X00') */function delete_hmac_key(string $projectId, string $accessId): void{ $storage = new StorageClient(); // By default hmacKey will use the projectId used by StorageClient(). $hmacKey = $storage->hmacKey($accessId, $projectId); $hmacKey->delete(); print( 'The key is deleted, though it may still appear in the results of calls ' . 'to StorageClient.hmacKeys([\'showDeletedKeys\' => true])' . PHP_EOL );}

Python

For more information, see the Cloud Storage Python API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

from google.cloud import storagedef delete_key(access_id, project_id): """ Delete the HMAC key with the given access ID. Key must have state INACTIVE in order to succeed. """ # project_id = "Your Google Cloud project ID" # access_id = "ID of an HMAC key (must be in INACTIVE state)" storage_client = storage.Client(project=project_id) hmac_key = storage_client.get_hmac_key_metadata( access_id, project_id=project_id ) hmac_key.delete() print( "The key is deleted, though it may still appear in list_hmac_keys()" " results." )

Ruby

For more information, see the Cloud Storage Ruby API reference documentation.

To authenticate to Cloud Storage, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

def delete_hmac_key access_id: # The access ID of the HMAC key # access_id = "GOOG0234230X00" require "google/cloud/storage" storage = Google::Cloud::Storage.new # By default Storage#hmac_keys uses the Storage client project_id hmac_key = storage.hmac_key access_id hmac_key.delete! puts "The key is deleted, though it may still appear in Client#hmac_keys results."end

REST APIs

JSON API

  1. Have gcloud CLI installed and initialized, in order to generate an access token for the Authorization header.

    Alternatively, you can create an access token using theOAuth 2.0 Playgroundand include it in the Authorization header.

  2. Use cURL to call the JSON API with aDELETE hmacKeys request:

    curl -X DELETE \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/storage/v1/projects/PROJECT_IDENTIFIER/hmacKeys/ACCESS_KEY_ID"

    Where:

    • PROJECT_IDENTIFIER is the ID or number forthe project associated with the key you want to delete. Forexample, my-pet-project.
    • ACCESS_KEY_ID is the access ID associatedwith the key you are deleting.

XML API

  1. Have gcloud CLI installed and initialized, in order to generate an access token for the Authorization header.

    Alternatively, you can create an access token using theOAuth 2.0 Playgroundand include it in the Authorization header.

  2. Use cURL to call the XML API with a POST HMAC Keyrequest:

    curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ "https://storage.googleapis.com/?Action=DeleteAccessKey&AccessKeyId=ACCESS_KEY_ID"

    Where ACCESS_KEY_ID is the access IDassociated with the key you are deleting.

What's next

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2024-07-25 UTC.

Manage HMAC keys for service accounts  |  Cloud Storage  |  Google Cloud (2024)

FAQs

Can you generate access keys for service accounts in GCP? ›

Create credentials for a service account

In the Google Cloud console, go to Menu menu > IAM & Admin > Service Accounts. Select your service account. Click Keys > Add key > Create new key. Select JSON, then click Create.

Where to store HMAC keys? ›

Storing secrets

To create an HMAC key for a user account, you must be logged into the Google Cloud console with the user account and go to the Interoperability tab in the Cloud Storage Settings menu of a project for which you have the resourcemanager. projects.

What are HMAC keys? ›

Hash-based message authentication code (or HMAC) is a cryptographic authentication technique that uses a hash function and a secret key. With HMAC, you can achieve authentication and verify that data is correct and authentic with shared secrets, as opposed to approaches that use signatures and asymmetric cryptography.

How would you create and manage access keys for users that need to access AWS services from the AWS command line interface? ›

You can use the create-access-key command to create an access key for a user. An access key is a set of security credentials that consists of an access key ID and a secret key. A user can create only two access keys at one time.

How to create a key for a service account? ›

  1. In the Google Cloud console, go to the Service accounts page. Go to Service accounts. ...
  2. Select a project.
  3. Click the email address of the service account that you want to create a key for.
  4. Click the Keys tab.
  5. Click the Add key drop-down menu, then select Create new key.
  6. Select JSON as the Key type and click Create.

What is the difference between HMAC key and AES key? ›

AES encryption is used to encrypt data while HMAC is used to authenticate data. Both operations use the same symmetric key, but they use the key in different ways. AES encryption uses the key to encrypt the data, while HMAC uses the key to generate a message authentication code (MAC) for the data.

How do I find my HMAC key? ›

Get HMAC key information
  1. In the Google Cloud console, go to the Cloud Storage Settings page. Go to Settings.
  2. Select the Interoperability tab. ...
  3. Click the name of a specific service account to see the HMAC keys associated with it and the status of those keys.

How do I add a HMAC key? ›

Add HMAC keys for your app

From the top menu, select Settings. Select Connect in the INTEGRATIONS section in the left menu. In the horizontal navigation at the top of the Connect page, select Connect Keys, then generate at least one HMAC key by choosing Add Secret Key.

How to access Google Cloud Storage using a service account? ›

Access a GCS bucket directly with a Google Cloud service account key
  1. Click IAM and Admin in the left navigation pane.
  2. Click Service Accounts.
  3. Click + CREATE SERVICE ACCOUNT.
  4. Enter the service account name and description.
  5. Click CREATE.
  6. Click CONTINUE.
  7. Click DONE.
Jul 26, 2024

How do I download the service account key for Google cloud? ›

The service account key JSON file is automatically downloaded to your local machine.
  1. Login to GCP Home Page.
  2. Create the service account.
  3. Grant the service account access to project.
  4. Select the newly created service account.
  5. Create key for the service account.
  6. Generate the service account JSON key and download.

How to get Google Cloud Storage API key? ›

To create your application's API key:
  1. Go to the API Console.
  2. From the projects list, select a project or create a new one.
  3. If the APIs & services page isn't already open, open the left side menu and select APIs & services.
  4. On the left, choose Credentials.
  5. Click Create credentials and then select API key.

What are the disadvantages of HMAC? ›

Disadvantages of HMAC

HMACs uses shared key which may lead to non-repudiation. If either sender or receiver's key is compromised then it will be easy for attackers to create unauthorized messages. Securely managing and distributing secret keys can be challenging.

Why should I use HMAC? ›

Ultimately, HMAC provides a great layer of security for companies that have sensitive data that needs protecting. It's an important measure to protect data integrity from attackers and offers a clear indication if data has been compromised.

Why does HMAC use two keys? ›

Cryptographic keys.

An encryption algorithm alters data, and a recipient needs a specific code (or key) to make it readable once more. HMAC relies on two sets of keys. One is public, and one is private.

How to create service account credentials in GCP? ›

  1. In the Google Cloud console, go to the Create service account page. ...
  2. Select a Google Cloud project.
  3. Enter a service account name to display in the Google Cloud console. ...
  4. Optional: Enter a description of the service account.
  5. If you don't want to set access controls now, click Done to finish creating the service account.

How do I get the public key for Google service account? ›

To get the public key data for a service account key:

To find the key's ID, list all keys for the service account, identify the key that you want to get, and then copy its ID. SA_NAME : The name of the service account whose public key you want to get. PROJECT_ID : Your Google Cloud project ID.

How to give permission to service account in GCP? ›

Give service account user permission
  1. In the Google Cloud console, go to the Service Accounts page. ...
  2. Click Select a project, choose a project where the service account you want to use for the Dataproc cluster is located, and then click Open.
  3. Click the email address of the Dataproc service account.

How do I give service account access to another project in GCP? ›

Go to the Permissions tab and find the section Principals with access to this service account. Click person_add Grant access, and then enter the email address of the service agent. Click Select a role, type Service Account Token Creator , and click the role. Click Save to save your changes.

Top Articles
Blockchain bridge Wormhole confirms that exploiter stole $320 million worth of crypto assets | TechCrunch
Why You Should Consider a Static Website First
Bon plan – Le smartphone Motorola Edge 50 Fusion "4 étoiles" à 339,99 €
Non-Identity Functions
Sixth Circuit Denies Qualified Immunity for State University Officials Who Allegedly Violated Professor's First Amendment Rights
Goodall Brazier hiring Vice President in Arizona, United States | LinkedIn
Jodie Sweetin Breast Reduction
Tamilyogi Download 2021
Jocelyne Mirando
Uptown Cheapskate Fort Lauderdale
What Auto Parts Stores Are Open
Cbs Fantasy Trade Values
888-490-1703
Courierpress Obit
Sand Castle Parents Guide
Pip Calculator | Myfxbook
Naughty Neighbor Tumblr
Gdp E239 Bts
Craigslist Tools Las Cruces Nm
Dabs Utah State Liquor Store #09 - Murray
Last minute moving service van local mover junk hauling pack loading - labor / hauling / moving - craigslist
Inspire Brands.csod.com Arby's
Aaf Seu
Bakkt Theater Purse Policy
Mugshots In Waco Texas
Indian Restaurants In Cape Cod
Sheetz Unlimited Drinks Ending
Caldwell Idaho Craigslist
Rural King Credit Card Minimum Credit Score
‘There’s no Planet B’: UNLV first Nevada university to launch climate change plan
Loterie Midi 30 Aujourd'hui
Abby's Caribbean Cafe
Ottumwa Evening Post Obits
R Mariokarttour
Koinonikos Tourismos
Search results for: Kert\u00E9sz, Andr\u00E9, page 1
Gracex Rayne
David Mayries
Paris 2024: The first Games to achieve full gender parity
Family Violence Prevention Program - YWCA Wheeling
Recharging Iban Staff
Helixnet Rfums
Planet Zoo Obstructed
Rwby Crossover Fanfiction Archive
5128 Se Bybee Blvd
Premier Nails Lebanon Pa
1984 Argo JM16 GTP for sale by owner - Holland, MI - craigslist
Road Techs
Pinellas Fire Active Calls
Lowlifesymptoms Twitter
The Complete Guide to Chicago O'Hare International Airport (ORD)
Ap Chem 2022 Frq Scoring Guidelines
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 6406

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.