Home > database >  How to hide secrete keys in apis
How to hide secrete keys in apis

Time:07-02

I wanna ask you how I gonna hide the secrete keys in API like database connection username, password or services API keys

When I deploy the application on virtual machine instance should I move them outside code like environment variables or I need to move them outside virtual machine to another place ?

Because the URL of the instance is publically accessable to reach API so people already has the URL of the instance .. is it safe to keep them in environment variables? Or need to move them to another place

Thanks

CodePudding user response:

There are already a number of discussions regarding storing secrets in environment variables (good to avoid committing them to version control - bad for a number of reasons). I'm not going to comment further on this but in any case, Google Cloud's Secret Manager is made exactly for that. It is made to store API keys, passwords, certificates, and other sensitive data.

You can create your secrets via a number of ways (Cloud Console, Cloud SDK, etc...) then add a secret version that will contain the actual contents of a secret.

Once done, you can retrieve them from your code using the specific client library for your programming language. For example, in Python:

    def access_secret_version(project_id, secret_id, version_id):
        """
        Access the payload for the given secret version if one exists. The version
        can be a version number as a string (e.g. "5") or an alias (e.g. "latest").
        """

        # Import the Secret Manager client library.
        from google.cloud import secretmanager

        # Create the Secret Manager client.
        client = secretmanager.SecretManagerServiceClient()

        # Build the resource name of the secret version.
        name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}"

        # Access the secret version.
        response = client.access_secret_version(request={"name": name})

        # Verify payload checksum.
        crc32c = google_crc32c.Checksum()
        crc32c.update(response.payload.data)
        if response.payload.data_crc32c != int(crc32c.hexdigest(), 16):
            print("Data corruption detected.")
        return response

        # Print the secret payload.
        #
        # WARNING: Do not print the secret in a production environment - this
        # snippet is showing how to access the secret material.
        payload = response.payload.data.decode("UTF-8")
        print("Plaintext: {}".format(payload))
  • Related