This page demonstrates how to set an encryption key in Cloud Speech-to-Text to
encrypt Speech-to-Text resources.

Speech-to-Text lets you provide [Cloud Key Management Service](https://docs.cloud.google.com/security-key-management)
encryption keys and encrypts data with the provided key. To learn more about
encryption, see [Introduction to encryption](https://docs.cloud.google.com/speech-to-text/docs/encryption.md.txt).

## Before you begin

1. Client libraries can use [Application Default Credentials](https://docs.cloud.google.com/docs/authentication/application-default-credentials.md.txt) to easily authenticate with Google APIs and send requests to those APIs. With Application Default Credentials, you can test your application locally and deploy it without changing the underlying code. For more information, see [Authenticate for using client libraries](https://docs.cloud.google.com/docs/authentication/client-libraries.md.txt).
2.

   If you're using a local shell, then create local authentication credentials for your user
   account:

   ```bash
   gcloud auth application-default login
   ```

   You don't need to do this if you're using Cloud Shell.


   If an authentication error is returned, and you are using an external identity provider
   (IdP), confirm that you have
   [signed in to the gcloud CLI with your federated identity](https://docs.cloud.google.com/iam/docs/workforce-log-in-gcloud.md.txt).

Also ensure you have [installed the client library](https://docs.cloud.google.com/speech-to-text/docs/libraries.md.txt).

## Enable access to Cloud Key Management Service keys

Cloud Speech-to-Text uses a service account to access your Cloud KMS keys.
By default, the service account has no access to Cloud KMS keys.

The service account email address is the following:

    service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com

To encrypt Speech-to-Text resources using Cloud KMS
keys, you can give this service account the
`roles/cloudkms.cryptoKeyEncrypterDecrypter` role:

```bash
gcloud projects add-iam-policy-binding PROJECT_NUMBER \
    --member=serviceAccount:service-PROJECT_NUMBER@gcp-sa-speech.iam.gserviceaccount.com \
    --role=roles/cloudkms.cryptoKeyEncrypterDecrypter
```

More information about project Identity and Access Management (IAM) policy is available at
[Manage access to projects, folders, and organizations](https://docs.cloud.google.com/iam/docs/granting-changing-revoking-access.md.txt).

More information about managing access to Cloud Storage is available at
[Create and Manage access control lists](https://docs.cloud.google.com/storage/docs/access-control/create-manage-lists.md.txt) in the
Cloud Storage documentation.

## Specify an encryption key

Here is an example of providing an encryption key to Cloud Speech-to-Text using the
[`Config`](https://docs.cloud.google.com/speech-to-text/docs/reference/rpc/google.cloud.speech.v2.md.txt#config) resource:

### Python

```python
import os

from google.cloud.speech_v2 import SpeechClient
from google.cloud.speech_v2.types import cloud_speech

PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")


def enable_cmek(
    kms_key_name: str,
) -> cloud_speech.Config:
    """Enable Customer-Managed Encryption Keys (CMEK) in a project and region.
    Args:
        kms_key_name (str): The full resource name of the KMS key to be used for encryption.
            E.g,: projects/{PROJECT_ID}/locations/{LOCATION}/keyRings/{KEY_RING}/cryptoKeys/{KEY_NAME}
    Returns:
        cloud_speech.Config: The response from the update configuration request,
        containing the updated configuration details.
    """
    # Instantiates a client
    client = SpeechClient()

    request = cloud_speech.UpdateConfigRequest(
        config=cloud_speech.Config(
            name=f"projects/{PROJECT_ID}/locations/global/config",
            kms_key_name=kms_key_name,
        ),
        update_mask={"paths": ["kms_key_name"]},
    )

    # Updates the KMS key for the project and region.
    response = client.update_config(request=request)

    print(f"Updated KMS key: {response.kms_key_name}")
    return response

```

When an encryption key is specified in the `Config` resource of your project,
any new resources created in the corresponding location are encrypted using this
key. See [Introduction to encryption](https://docs.cloud.google.com/speech-to-text/docs/encryption.md.txt) page for more information on what is
encrypted and when.

Encrypted resources have the `kms_key_name` and `kms_key_version_name` fields
populated in Speech-to-Text API responses.

## Remove encryption

To prevent future resources from being encrypted with an encryption key, use the
code above and provide the empty string (`""`) as the key in the request. This
ensures that new resources aren't encrypted. This command doesn't decrypt
existing resources.

## Key rotation and deletion

On key rotation, resources that are encrypted with a previous version of the
Cloud KMS key remain encrypted with that version. Any resources created
after the key rotation are encrypted with the new default version of the key.
Any resources updated (using `Update*` methods) after the key rotation are
re-encrypted with the new default version of the key.

On key deletion, Speech-to-Text can't decrypt your data and can't create
resources or access resources encrypted with the deleted key. Likewise, when you
revoke Speech-to-Text
permission for a key, Speech-to-Text can't decrypt your data and can't
create resources or access resources encrypted with the Speech-to-Text
permission-revoked key.

## Re-encrypt data

To re-encrypt your resources, you can call the corresponding `Update*` method
for each resource after updating the key specification in the `Config` resource.

## Clean up

To avoid incurring charges to your Google Cloud account for the resources used on this page, follow these steps.

1.
   Optional: Revoke the authentication credentials that you created, and delete the local
   credential file.

   ```bash
   gcloud auth application-default revoke
   ```
2.
   Optional: Revoke credentials from the gcloud CLI.

   ```bash
   gcloud auth revoke
   ```

### Console


> [!CAUTION]
> **Caution** : Deleting a project has the following effects:
>
> - **Everything in the project is deleted.** If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
> - **Custom project IDs are lost.** When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as an `appspot.com` URL, delete selected resources inside the project instead of deleting the whole project.
>
>
> If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects
> can help you avoid exceeding project quota limits.

- In the Google Cloud console, go to the **Manage resources** page.

  [Go to Manage resources](https://console.cloud.google.com/iam-admin/projects)
- In the project list, select the project that you want to delete, and then click **Delete**.
- In the dialog, type the project ID, and then click **Shut down** to delete the project.

### gcloud


> [!CAUTION]
> **Caution** : Deleting a project has the following effects:
>
> - **Everything in the project is deleted.** If you used an existing project for the tasks in this document, when you delete it, you also delete any other work you've done in the project.
> - **Custom project IDs are lost.** When you created this project, you might have created a custom project ID that you want to use in the future. To preserve the URLs that use the project ID, such as an `appspot.com` URL, delete selected resources inside the project instead of deleting the whole project.
>
>
> If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects
> can help you avoid exceeding project quota limits.

Delete a Google Cloud project:

```
gcloud projects delete PROJECT_ID
```

<br />

## What's next

- Learn more about [what is encrypted](https://docs.cloud.google.com/speech-to-text/docs/encryption.md.txt) when specifying encryption keys in Speech-to-Text
- Learn how to [transcribe streaming audio](https://docs.cloud.google.com/speech-to-text/docs/streaming-recognize.md.txt).
- Learn how to [transcribe long audio files](https://docs.cloud.google.com/speech-to-text/docs/batch-recognize.md.txt).
- Learn how to [transcribe short audio files](https://docs.cloud.google.com/speech-to-text/docs/sync-recognize.md.txt).
- For best performance, accuracy, and other tips, see the [best practices](https://docs.cloud.google.com/speech-to-text/docs/best-practices.md.txt) documentation.