使用 Cloud KMS 建立加密金鑰
本快速入門導覽課程說明如何在您擁有的專案中,使用 Cloud Key Management Service 建立及使用加密金鑰。這些操作說明會使用Google Cloud 控制台,在 Cloud KMS 中建立金鑰環、金鑰和金鑰版本。如需其他方法的操作說明,請參閱使用指南。
本快速入門導覽課程使用指令列將要求傳送至 Cloud KMS API。如需使用用戶端程式庫將要求傳送至 Cloud KMS API 的程式設計範例,請參閱加密與解密一文。
事前準備
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud KMS API.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Cloud KMS API.
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
金鑰環與金鑰
如要加密及解密內容,您需要 Cloud KMS 金鑰,而該金鑰為金鑰環的一部分。
請建立名為 test
的金鑰環,以及名為 quickstart
的金鑰。如要進一步瞭解這些物件,以及這些物件彼此之間的關係,請參閱物件階層總覽。
gcloud kms keyrings create "test" \
--location "global"
gcloud kms keys create "quickstart" \
--location "global" \
--keyring "test" \
--purpose "encryption"
您可以使用 list
選項,查看您剛建立的金鑰的名稱和中繼資料。
gcloud kms keys list \
--location "global" \
--keyring "test"
您應該會看到:
NAME PURPOSE PRIMARY_STATE projects/project-id/locations/global/keyRings/test/cryptoKeys/quickstart ENCRYPT_DECRYPT ENABLED
加密資料
您現在有了金鑰,就可以使用該金鑰來加密文字或二進位檔內容。
請將要加密的部分文字儲存在名為「mysecret.txt」的檔案中。
echo -n "Some text to be encrypted" > mysecret.txt
如要利用 gcloud kms encrypt
加密資料,請提供您的金鑰資訊、指定要加密的明文檔案名稱,然後指定將包含已加密內容的檔案名稱:
gcloud kms encrypt \
--location "global" \
--keyring "test" \
--key "quickstart" \
--plaintext-file ./mysecret.txt \
--ciphertext-file ./mysecret.txt.encrypted
encrypt
方法會把已加密內容儲存在 --ciphertext-file
標記所指定的檔案中。
解密密文
如要利用 gcloud kms decrypt
解密資料,請提供您的金鑰資訊、指定要解密的已加密檔案 (密文檔案) 名稱,然後指定將包含已解密內容的檔案名稱:
gcloud kms decrypt \
--location "global" \
--keyring "test" \
--key "quickstart" \
--ciphertext-file ./mysecret.txt.encrypted \
--plaintext-file ./mysecret.txt.decrypted
decrypt
方法會把已解密內容儲存在 --plaintext-file
標記所指定的檔案中。
如要為已加密內容解密,您必須使用之前用來為該內容加密的金鑰。
清除所用資源
如要避免系統向您的 Google Cloud 帳戶收取本頁所用資源的費用,請按照下列步驟操作。
列出適用於金鑰的版本:
gcloud kms keys versions list \
--location "global" \
--keyring "test" \
--key "quickstart"
如要刪除版本,請執行下列指令,將 key-version 取代為要刪除的金鑰版本編號:
gcloud kms keys versions destroy key-version \ --location "global" \ --keyring "test" \ --key "quickstart"