Encrypt customer private key with Google public key
Stay organized with collections
Save and categorize content based on your preferences.
This sample demonstrates how to encrypt a customer private key with the Google public key, ensuring that only Google can decrypt it.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
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.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis sample code demonstrates encrypting a customer's private key using Google's public key, ensuring only Google can decrypt it.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves downloading Google's public certificate, which is then used to encrypt the customer's private key.\u003c/p\u003e\n"],["\u003cp\u003eThe Python script utilizes the \u003ccode\u003ecryptography\u003c/code\u003e library to manage encryption, and the resulting encrypted key is encoded in base64 format.\u003c/p\u003e\n"],["\u003cp\u003eThe script can either use a user-provided private key or generate a new 256-bit key if one isn't supplied.\u003c/p\u003e\n"]]],[],null,["# Encrypt customer private key with Google public key\n\nThis sample demonstrates how to encrypt a customer private key with the Google public key, ensuring that only Google can decrypt it.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Encrypt disks with customer-supplied encryption keys](/compute/docs/disks/customer-supplied-encryption)\n\nCode sample\n-----------\n\n### Python\n\n\nBefore trying this sample, follow the Python setup instructions in the\n[Compute Engine quickstart using\nclient libraries](/compute/docs/api/using-libraries).\n\n\nFor more information, see the\n[Compute Engine Python API\nreference documentation](/python/docs/reference/compute/latest).\n\n\nTo authenticate to Compute Engine, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import argparse\n import base64\n import os\n from typing import Optional\n\n from cryptography import x509\n from cryptography.hazmat.backends import default_backend\n from cryptography.hazmat.primitives import hashes\n from cryptography.hazmat.primitives.asymmetric import padding\n from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey\n import requests\n\n\n GOOGLE_PUBLIC_CERT_URL = (\n \"https://cloud-certs.storage.googleapis.com/google-cloud-csek-ingress.pem\"\n )\n\n\n def get_google_public_cert_key() -\u003e RSAPublicKey:\n \"\"\"\n Downloads the Google public certificate.\n\n Returns:\n RSAPublicKey object with the Google public certificate.\n \"\"\"\n r = requests.get(GOOGLE_PUBLIC_CERT_URL)\n r.raise_for_status()\n\n # Load the certificate.\n certificate = x509.load_pem_x509_certificate(r.content, default_backend())\n\n # Get the certicate's public key.\n public_key = certificate.public_key()\n\n return public_key\n\n\n def wrap_rsa_key(public_key: RSAPublicKey, private_key_bytes: bytes) -\u003e bytes:\n \"\"\"\n Use the Google public key to encrypt the customer private key.\n\n This means that only the Google private key is capable of decrypting\n the customer private key.\n\n Args:\n public_key: The public key to use for encrypting.\n private_key_bytes: The private key to be encrypted.\n\n Returns:\n private_key_bytes encrypted using the public_key. Encoded using\n base64.\n \"\"\"\n wrapped_key = public_key.encrypt(\n private_key_bytes,\n padding.OAEP(\n mgf=padding.MGF1(algorithm=hashes.SHA1()),\n algorithm=hashes.SHA1(),\n label=None,\n ),\n )\n encoded_wrapped_key = base64.b64encode(wrapped_key)\n return encoded_wrapped_key\n\n\n def main(key_file: Optional[str]) -\u003e None:\n \"\"\"\n This script will encrypt a private key with Google public key.\n\n Args:\n key_file: path to a file containing your private key. If not\n provided, a new key will be generated (256 bit).\n \"\"\"\n # Generate a new 256-bit private key if no key is specified.\n if not key_file:\n customer_key_bytes = os.urandom(32)\n else:\n with open(key_file, \"rb\") as f:\n customer_key_bytes = f.read()\n\n google_public_key = get_google_public_cert_key()\n wrapped_rsa_key = wrap_rsa_key(google_public_key, customer_key_bytes)\n\n b64_key = base64.b64encode(customer_key_bytes).decode(\"utf-8\")\n\n print(f\"Base-64 encoded private key: {b64_key}\")\n print(f\"Wrapped RSA key: {wrapped_rsa_key.decode('utf-8')}\")\n\n\n if __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter\n )\n parser.add_argument(\"--key_file\", help=\"File containing your binary private key.\")\n\n args = parser.parse_args()\n\n main(args.key_file)\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=compute)."]]