Encrypting and decrypting data with an asymmetric key Stay organized with collections Save and categorize content based on your preferences.
This topic provides information about creating and using a key for asymmetricencryption using an RSA key. If you want to use asymmetric keys for creating andvalidating signatures, seeCreating and validating digital signatures. Ifyou want to use symmetric keys for encryption and decryption, seeEncrypting and decrypting data.
Asymmetric encryption uses the public key portion of the asymmetric key anddecryption uses the private key portion of the key. Cloud Key Management Serviceprovides functionality to retrieve the public key and functionality to decryptciphertext that was encrypted with the public key. Cloud KMS doesnot allow direct access to the private key.
Before you begin
This topic provides examples that run at the command line. To simplify usingthe examples, useCloud Shell. The encryption example usesOpenSSL, which is pre-installed on Cloud Shell.
Create an asymmetric key withkey purpose of
ASYMMETRIC_DECRYPT.To see which algorithms are supported for key purposeASYMMETRIC_DECRYPT, seeAsymmetric encryption algorithms.You cannot follow this procedure witha key with purpose ofASYMMETRIC_SIGN.If you are going to use the command line, installOpenSSL if you do notalready have it. If you useCloud Shell, OpenSSL is already installed.
- macOS users: The version of OpenSSL installed on macOS does not support the flags used todecrypt data in this topic. To follow these steps on macOS,install OpenSSL fromHomebrew.
Access control to the key
For a user or service that will retrieve the public key, grant the
cloudkms.cryptoKeyVersions.viewPublicKeypermission on the asymmetric key. Thepublic key is required for encrypting data.For a user or service that will decrypt data that was encrypted with thepublic key, grant the
cloudkms.cryptoKeyVersions.useToDecryptpermission onthe asymmetric key.
Learn about permissions and roles in Cloud KMS atPermissions and Roles.
Encrypt data
To encrypt data using an asymmetric encryption key, retrieve the public key anduse the public key to encrypt the data.
Note: The plaintext data you want to encrypt is limited in size depending on the size of the key. For details on supported payload sizes,seedata too large for key size.gcloud
This sample requiresOpenSSL to beinstalled on your local system.
Download public key
Download the public key:
gcloud kms keys versions get-public-keykey-version \ --keykey \ --keyringkey-ring \ --locationlocation \ --output-filepublic-key-path
Replacekey-version with the key version that has the public key.Replacekey with the name of the key. Replacekey-ringwith the name of the key ring where the key is located. Replacelocation with the Cloud KMS location for thekey ring. Replacepublic-key-path with the location to save thepublic key on the local system.
Encrypt data
Encrypt data using the public key you just downloaded and save the output toa file:
openssl pkeyutl -incleartext-data-input-file \ -encrypt \ -pubin \ -inkeypublic-key-path \ -pkeyopt rsa_padding_mode:oaep \ -pkeyopt rsa_oaep_md:sha256 \ -pkeyopt rsa_mgf1_md:sha256 \ >encrypted-data-output-file
Replacecleartext-data-input-file with the path and file name toencrypt.
Replacepublic-key-path with the path and file name where youdownloaded the public key.
Replaceencrypted-data-output-file with the path and file nameto save the encrypted data.
C#
To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.
usingGoogle.Cloud.Kms.V1;usingSystem;usingSystem.Security.Cryptography;usingSystem.Text;publicclassEncryptAsymmetricSample{publicbyte[]EncryptAsymmetric(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",stringkeyVersionId="123",stringmessage="Sample message"){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key version name.CryptoKeyVersionNamekeyVersionName=newCryptoKeyVersionName(projectId,locationId,keyRingId,keyId,keyVersionId);// Get the public key.PublicKeypublicKey=client.GetPublicKey(keyVersionName);// Split the key into blocks and base64-decode the PEM parts.string[]blocks=publicKey.Pem.Split("-",StringSplitOptions.RemoveEmptyEntries);byte[]pem=Convert.FromBase64String(blocks[1]);// Create a new RSA key.RSArsa=RSA.Create();rsa.ImportSubjectPublicKeyInfo(pem,out_);// Convert the message into bytes. Cryptographic plaintexts and// ciphertexts are always byte arrays.byte[]plaintext=Encoding.UTF8.GetBytes(message);// Encrypt the data.byte[]ciphertext=rsa.Encrypt(plaintext,RSAEncryptionPadding.OaepSHA256);returnciphertext;}}Go
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
import("context""crypto/rand""crypto/rsa""crypto/sha256""crypto/x509""encoding/pem""fmt""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb")// encryptAsymmetric encrypts data on your local machine using an// 'RSA_DECRYPT_OAEP_2048_SHA256' public key retrieved from Cloud KMS.funcencryptAsymmetric(wio.Writer,namestring,messagestring)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"// message := "Sample message"// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Retrieve the public key from Cloud KMS. This is the only operation that// involves Cloud KMS. The remaining operations take place on your local// machine.response,err:=client.GetPublicKey(ctx,&kmspb.GetPublicKeyRequest{Name:name,})iferr!=nil{returnfmt.Errorf("failed to get public key: %w",err)}// Parse the public key. Note, this example assumes the public key is in the// RSA format.block,_:=pem.Decode([]byte(response.Pem))publicKey,err:=x509.ParsePKIXPublicKey(block.Bytes)iferr!=nil{returnfmt.Errorf("failed to parse public key: %w",err)}rsaKey,ok:=publicKey.(*rsa.PublicKey)if!ok{returnfmt.Errorf("public key is not rsa")}// Convert the message into bytes. Cryptographic plaintexts and// ciphertexts are always byte arrays.plaintext:=[]byte(message)// Encrypt data using the RSA public key.ciphertext,err:=rsa.EncryptOAEP(sha256.New(),rand.Reader,rsaKey,plaintext,nil)iferr!=nil{returnfmt.Errorf("rsa.EncryptOAEP: %w",err)}fmt.Fprintf(w,"Encrypted ciphertext: %s",ciphertext)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.CryptoKeyVersionName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.cloud.kms.v1.PublicKey;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.StringReader;importjava.nio.charset.StandardCharsets;importjava.security.GeneralSecurityException;importjava.security.KeyFactory;importjava.security.spec.MGF1ParameterSpec;importjava.security.spec.X509EncodedKeySpec;importjava.util.Base64;importjava.util.stream.Collectors;importjavax.crypto.Cipher;importjavax.crypto.spec.OAEPParameterSpec;importjavax.crypto.spec.PSource;publicclassEncryptAsymmetric{publicvoidencryptAsymmetric()throwsIOException,GeneralSecurityException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";StringkeyVersionId="123";Stringplaintext="Plaintext to encrypt";encryptAsymmetric(projectId,locationId,keyRingId,keyId,keyVersionId,plaintext);}// Encrypt data that was encrypted using the public key component of the given// key version.publicvoidencryptAsymmetric(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,StringkeyVersionId,Stringplaintext)throwsIOException,GeneralSecurityException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the key version name from the project, location, key ring, key,// and key version.CryptoKeyVersionNamekeyVersionName=CryptoKeyVersionName.of(projectId,locationId,keyRingId,keyId,keyVersionId);// Get the public key.PublicKeypublicKey=client.getPublicKey(keyVersionName);// Convert the public PEM key to a DER key (see helper below).byte[]derKey=convertPemToDer(publicKey.getPem());X509EncodedKeySpeckeySpec=newX509EncodedKeySpec(derKey);java.security.PublicKeyrsaKey=KeyFactory.getInstance("RSA").generatePublic(keySpec);// Encrypt plaintext for the 'RSA_DECRYPT_OAEP_2048_SHA256' key.// For other key algorithms:// https://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.htmlCiphercipher=Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");OAEPParameterSpecoaepParams=newOAEPParameterSpec("SHA-256","MGF1",MGF1ParameterSpec.SHA256,PSource.PSpecified.DEFAULT);cipher.init(Cipher.ENCRYPT_MODE,rsaKey,oaepParams);byte[]ciphertext=cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));System.out.printf("Ciphertext: %s%n",ciphertext);}}// Converts a base64-encoded PEM certificate like the one returned from Cloud// KMS into a DER formatted certificate for use with the Java APIs.privatebyte[]convertPemToDer(Stringpem){BufferedReaderbufferedReader=newBufferedReader(newStringReader(pem));Stringencoded=bufferedReader.lines().filter(line->!line.startsWith("-----BEGIN") &&!line.startsWith("-----END")).collect(Collectors.joining());returnBase64.getDecoder().decode(encoded);}}Node.js
To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const keyId = 'my-key';// const versionId = '123';// const plaintextBuffer = Buffer.from('...');// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key version nameconstversionName=client.cryptoKeyVersionPath(projectId,locationId,keyRingId,keyId,versionId);asyncfunctionencryptAsymmetric(){// Get public key from Cloud KMSconst[publicKey]=awaitclient.getPublicKey({name:versionName,});// Optional, but recommended: perform integrity verification on publicKey.// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:// https://cloud.google.com/kms/docs/data-integrity-guidelinesconstcrc32c=require('fast-crc32c');if(publicKey.name!==versionName){thrownewError('GetPublicKey: request corrupted in-transit');}if(crc32c.calculate(publicKey.pem)!==Number(publicKey.pemCrc32c.value)){thrownewError('GetPublicKey: response corrupted in-transit');}// Import and setup cryptoconstcrypto=require('crypto');// Encrypt plaintext locally using the public key. This example uses a key// that was configured with sha256 hash with OAEP padding. Update these// values to match the Cloud KMS key.//// NOTE: In Node < 12, this function does not properly consume the OAEP// padding and thus produces invalid ciphertext. If you are using Node to do// public key encryption, please use version 12+.constciphertextBuffer=crypto.publicEncrypt({key:publicKey.pem,oaepHash:'sha256',padding:crypto.constants.RSA_PKCS1_OAEP_PADDING,},plaintextBuffer);console.log(`Ciphertext:${ciphertextBuffer.toString('base64')}`);returnciphertextBuffer;}returnencryptAsymmetric();PHP
To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.
function encrypt_asymmetric( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $keyId = 'my-key', string $versionId = '123', string $plaintext = '...'): void { // PHP has limited support for asymmetric encryption operations. // Specifically, openssl_public_encrypt() does not allow customizing // algorithms or padding. Thus, it is not currently possible to use PHP // core for asymmetric operations on RSA keys. // // Third party libraries like phpseclib may provide the required // functionality. Google does not endorse this external library.}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
# Import base64 for printing the ciphertext.importbase64# Import cryptographic helpers from the cryptography package.fromcryptography.hazmat.backendsimportdefault_backendfromcryptography.hazmat.primitivesimporthashesfromcryptography.hazmat.primitivesimportserializationfromcryptography.hazmat.primitives.asymmetricimportpadding# Import the client library.fromgoogle.cloudimportkmsdefencrypt_asymmetric(project_id:str,location_id:str,key_ring_id:str,key_id:str,version_id:str,plaintext:str,)->bytes:""" Encrypt plaintext using the public key portion of an asymmetric key. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring'). key_id (string): ID of the key to use (e.g. 'my-key'). version_id (string): ID of the key version to use (e.g. '1'). plaintext (string): message to encrypt Returns: bytes: Encrypted ciphertext. """# Convert the plaintext to bytes.plaintext_bytes=plaintext.encode("utf-8")# Create the client.client=kms.KeyManagementServiceClient()# Build the key version name.key_version_name=client.crypto_key_version_path(project_id,location_id,key_ring_id,key_id,version_id)# Get the public key.public_key=client.get_public_key(request={"name":key_version_name})# Extract and parse the public key as a PEM-encoded RSA key.pem=public_key.pem.encode("utf-8")rsa_key=serialization.load_pem_public_key(pem,default_backend())# Construct the padding. Note that the padding differs based on key choice.sha256=hashes.SHA256()mgf=padding.MGF1(algorithm=sha256)pad=padding.OAEP(mgf=mgf,algorithm=sha256,label=None)# Encrypt the data using the public key.ciphertext=rsa_key.encrypt(plaintext_bytes,pad)print(f"Ciphertext:{base64.b64encode(ciphertext)!r}")returnciphertextRuby
To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.
# Ruby has limited support for asymmetric encryption operations. Specifically,# public_encrypt() does not allow customizing the MGF hash algorithm. Thus, it# is not currently possible to use Ruby core for asymmetric encryption# operations on RSA keys from Cloud KMS.## Third party libraries may provide the required functionality. Google does# not endorse these external libraries.Decrypt data
Use Cloud KMS to perform the decryption.
gcloud
To use Cloud KMS on the command line, firstInstall or upgrade to the latest version of Google Cloud CLI.
gcloud kms asymmetric-decrypt \ --versionkey-version \ --keykey \ --keyringkey-ring \ --locationlocation \ --ciphertext-filefile-path-with-encrypted-data \ --plaintext-filefile-path-to-store-plaintext
Replacekey-version with the key version, or omit the--versionflag to detect the version automatically. Replacekey with the nameof the key to use for decryption. Replacekey-ring with the name ofthe key ring where the key will be located. Replacelocation with theCloud KMS location for the key ring. Replacefile-path-with-encrypted-data andfile-path-to-store-plaintextwith the local file paths for reading the encrypted data and saving the decryptedoutput.
For information on all flags and possible values, run the command with the--help flag.
To display the contents of the decrypted file, open it in your editor orterminal. Here is an example that shows the file contents using thecatcommand:
cat ./my-file.txt
C#
To run this code, firstset up a C# development environment andinstall the Cloud KMS C# SDK.
usingGoogle.Cloud.Kms.V1;usingGoogle.Protobuf;usingSystem.Text;publicclassDecryptAsymmetricSample{publicstringDecryptAsymmetric(stringprojectId="my-project",stringlocationId="us-east1",stringkeyRingId="my-key-ring",stringkeyId="my-key",stringkeyVersionId="123",byte[]ciphertext=null){// Create the client.KeyManagementServiceClientclient=KeyManagementServiceClient.Create();// Build the key version name.CryptoKeyVersionNamekeyVersionName=newCryptoKeyVersionName(projectId,locationId,keyRingId,keyId,keyVersionId);// Call the API.AsymmetricDecryptResponseresult=client.AsymmetricDecrypt(keyVersionName,ByteString.CopyFrom(ciphertext));// Get the plaintext. Cryptographic plaintexts and ciphertexts are// always byte arrays.byte[]plaintext=result.Plaintext.ToByteArray();// Return the result.returnEncoding.UTF8.GetString(plaintext);}}Go
To run this code, firstset up a Go development environment andinstall the Cloud KMS Go SDK.
import("context""fmt""hash/crc32""io"kms"cloud.google.com/go/kms/apiv1""cloud.google.com/go/kms/apiv1/kmspb""google.golang.org/protobuf/types/known/wrapperspb")// decryptAsymmetric will attempt to decrypt a given ciphertext with an// 'RSA_DECRYPT_OAEP_2048_SHA256' key from Cloud KMS.funcdecryptAsymmetric(wio.Writer,namestring,ciphertext[]byte)error{// name := "projects/my-project/locations/us-east1/keyRings/my-key-ring/cryptoKeys/my-key/cryptoKeyVersions/123"// ciphertext := []byte("...") // result of an asymmetric encryption call// Create the client.ctx:=context.Background()client,err:=kms.NewKeyManagementClient(ctx)iferr!=nil{returnfmt.Errorf("failed to create kms client: %w",err)}deferclient.Close()// Optional but recommended: Compute ciphertext's CRC32C.crc32c:=func(data[]byte)uint32{t:=crc32.MakeTable(crc32.Castagnoli)returncrc32.Checksum(data,t)}ciphertextCRC32C:=crc32c(ciphertext)// Build the request.req:=&kmspb.AsymmetricDecryptRequest{Name:name,Ciphertext:ciphertext,CiphertextCrc32C:wrapperspb.Int64(int64(ciphertextCRC32C)),}// Call the API.result,err:=client.AsymmetricDecrypt(ctx,req)iferr!=nil{returnfmt.Errorf("failed to decrypt ciphertext: %w",err)}// Optional, but recommended: perform integrity verification on result.// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:// https://cloud.google.com/kms/docs/data-integrity-guidelinesifresult.VerifiedCiphertextCrc32C==false{returnfmt.Errorf("AsymmetricDecrypt: request corrupted in-transit")}ifint64(crc32c(result.Plaintext))!=result.PlaintextCrc32C.Value{returnfmt.Errorf("AsymmetricDecrypt: response corrupted in-transit")}fmt.Fprintf(w,"Decrypted plaintext: %s",result.Plaintext)returnnil}Java
To run this code, firstset up a Java development environment andinstall the Cloud KMS Java SDK.
importcom.google.cloud.kms.v1.AsymmetricDecryptResponse;importcom.google.cloud.kms.v1.CryptoKeyVersionName;importcom.google.cloud.kms.v1.KeyManagementServiceClient;importcom.google.protobuf.ByteString;importjava.io.IOException;publicclassDecryptAsymmetric{publicvoiddecryptAsymmetric()throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-project-id";StringlocationId="us-east1";StringkeyRingId="my-key-ring";StringkeyId="my-key";StringkeyVersionId="123";byte[]ciphertext=null;decryptAsymmetric(projectId,locationId,keyRingId,keyId,keyVersionId,ciphertext);}// Decrypt data that was encrypted using the public key component of the given// key version.publicvoiddecryptAsymmetric(StringprojectId,StringlocationId,StringkeyRingId,StringkeyId,StringkeyVersionId,byte[]ciphertext)throwsIOException{// Initialize client that will be used to send requests. This client only// needs to be created once, and can be reused for multiple requests. After// completing all of your requests, call the "close" method on the client to// safely clean up any remaining background resources.try(KeyManagementServiceClientclient=KeyManagementServiceClient.create()){// Build the key version name from the project, location, key ring, key,// and key version.CryptoKeyVersionNamekeyVersionName=CryptoKeyVersionName.of(projectId,locationId,keyRingId,keyId,keyVersionId);// Decrypt the ciphertext.AsymmetricDecryptResponseresponse=client.asymmetricDecrypt(keyVersionName,ByteString.copyFrom(ciphertext));System.out.printf("Plaintext: %s%n",response.getPlaintext().toStringUtf8());}}}Node.js
To run this code, firstset up a Node.js development environment andinstall the Cloud KMS Node.js SDK.
//// TODO(developer): Uncomment these variables before running the sample.//// const projectId = 'my-project';// const locationId = 'us-east1';// const keyRingId = 'my-key-ring';// const keyId = 'my-key';// const versionId = '123';// const ciphertext = Buffer.from('...');// Imports the Cloud KMS libraryconst{KeyManagementServiceClient}=require('@google-cloud/kms');// Instantiates a clientconstclient=newKeyManagementServiceClient();// Build the key version nameconstversionName=client.cryptoKeyVersionPath(projectId,locationId,keyRingId,keyId,versionId);// Optional, but recommended: compute plaintext's CRC32C.constcrc32c=require('fast-crc32c');constciphertextCrc32c=crc32c.calculate(ciphertext);asyncfunctiondecryptAsymmetric(){const[decryptResponse]=awaitclient.asymmetricDecrypt({name:versionName,ciphertext:ciphertext,ciphertextCrc32c:{value:ciphertextCrc32c,},});// Optional, but recommended: perform integrity verification on decryptResponse.// For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:// https://cloud.google.com/kms/docs/data-integrity-guidelinesif(!decryptResponse.verifiedCiphertextCrc32c){thrownewError('AsymmetricDecrypt: request corrupted in-transit');}if(crc32c.calculate(decryptResponse.plaintext)!==Number(decryptResponse.plaintextCrc32c.value)){thrownewError('AsymmetricDecrypt: response corrupted in-transit');}// NOTE: The ciphertext must be properly formatted. In Node < 12, the// crypto.publicEncrypt() function does not properly consume the OAEP// padding and thus produces invalid ciphertext. If you are using Node to do// public key encryption, please use version 12+.constplaintext=decryptResponse.plaintext.toString('utf8');console.log(`Plaintext:${plaintext}`);returnplaintext;}returndecryptAsymmetric();PHP
To run this code, first learn aboutusing PHP on Google Cloud andinstall the Cloud KMS PHP SDK.
use Google\Cloud\Kms\V1\AsymmetricDecryptRequest;use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;function decrypt_asymmetric( string $projectId = 'my-project', string $locationId = 'us-east1', string $keyRingId = 'my-key-ring', string $keyId = 'my-key', string $versionId = '123', string $ciphertext = '...') { // Create the Cloud KMS client. $client = new KeyManagementServiceClient(); // Build the key version name. $keyVersionName = $client->cryptoKeyVersionName($projectId, $locationId, $keyRingId, $keyId, $versionId); // Call the API. $asymmetricDecryptRequest = (new AsymmetricDecryptRequest()) ->setName($keyVersionName) ->setCiphertext($ciphertext); $decryptResponse = $client->asymmetricDecrypt($asymmetricDecryptRequest); printf('Plaintext: %s' . PHP_EOL, $decryptResponse->getPlaintext()); return $decryptResponse;}Python
To run this code, firstset up a Python development environment andinstall the Cloud KMS Python SDK.
fromgoogle.cloudimportkmsdefdecrypt_asymmetric(project_id:str,location_id:str,key_ring_id:str,key_id:str,version_id:str,ciphertext:bytes,)->kms.DecryptResponse:""" Decrypt the ciphertext using an asymmetric key. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring'). key_id (string): ID of the key to use (e.g. 'my-key'). version_id (string): ID of the key version to use (e.g. '1'). ciphertext (bytes): Encrypted bytes to decrypt. Returns: DecryptResponse: Response including plaintext. """# Create the client.client=kms.KeyManagementServiceClient()# Build the key version name.key_version_name=client.crypto_key_version_path(project_id,location_id,key_ring_id,key_id,version_id)# Optional, but recommended: compute ciphertext's CRC32C.# See crc32c() function defined below.ciphertext_crc32c=crc32c(ciphertext)# Call the API.decrypt_response=client.asymmetric_decrypt(request={"name":key_version_name,"ciphertext":ciphertext,"ciphertext_crc32c":ciphertext_crc32c,})# Optional, but recommended: perform integrity verification on decrypt_response.# For more details on ensuring E2E in-transit integrity to and from Cloud KMS visit:# https://cloud.google.com/kms/docs/data-integrity-guidelinesifnotdecrypt_response.verified_ciphertext_crc32c:raiseException("The request sent to the server was corrupted in-transit.")ifnotdecrypt_response.plaintext_crc32c==crc32c(decrypt_response.plaintext):raiseException("The response received from the server was corrupted in-transit.")# End integrity verificationprint(f"Plaintext:{decrypt_response.plaintext!r}")returndecrypt_responsedefcrc32c(data:bytes)->int:""" Calculates the CRC32C checksum of the provided data. Args: data: the bytes over which the checksum should be calculated. Returns: An int representing the CRC32C checksum of the provided bytes. """importcrcmod# type: ignorecrc32c_fun=crcmod.predefined.mkPredefinedCrcFun("crc-32c")returncrc32c_fun(data)Ruby
To run this code, firstset up a Ruby development environment andinstall the Cloud KMS Ruby SDK.
# TODO(developer): uncomment these values before running the sample.# project_id = "my-project"# location_id = "us-east1"# key_ring_id = "my-key-ring"# key_id = "my-key"# version_id = "123"# ciphertext = "..."# Require the library.require"google/cloud/kms"# Create the client.client=Google::Cloud::Kms.key_management_service# Build the key version name.key_version_name=client.crypto_key_version_pathproject:project_id,location:location_id,key_ring:key_ring_id,crypto_key:key_id,crypto_key_version:version_id# Call the API.response=client.asymmetric_decryptkey_version_name,ciphertextputs"Plaintext:#{response.plaintext}"API
These examples usecurl as an HTTP client to demonstrate using the API. For more information about access control, seeAccessing the Cloud KMS API.
Use theCryptoKeyVersions.asymmetricDecryptmethod.
Troubleshooting
incorrect key purpose: ASYMMETRIC_SIGN
You can only decrypt data with a key withkey purposeASYMMETRIC_DECRYPT.
invalid parameter when decrypting on macOS
The version of OpenSSL installed on macOS does not support the flags used todecrypt data in this topic. To follow these steps on macOS,install OpenSSL fromHomebrew.
data too large for key size
The maximum payload size for RSA decryption depends on the key size and paddingalgorithm. All RSA encryption formats used by Cloud KMS useOAEP, standardized inRFC 2437. As aquick reference, the following algorithms support the following maximum payloadsizes (maxMLen, in bytes):
| Algorithm | Parameters | Maximum message length |
|---|---|---|
| RSA_DECRYPT_OAEP_2048_SHA256 | k = 256; hLen = 32; | maxMLen = 190 |
| RSA_DECRYPT_OAEP_3072_SHA256 | k = 384; hLen = 32; | maxMLen = 318 |
| RSA_DECRYPT_OAEP_4096_SHA256 | k = 512; hLen = 32; | maxMLen = 446 |
| RSA_DECRYPT_OAEP_4096_SHA512 | k = 512; hLen = 64; | maxMLen = 382 |
Asymmetric encryption is not recommended for messages of varying lengths thatmay be larger than these limits. Consider using hybrid encryption instead.Tink is a cryptographic librarythat uses this approach.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-19 UTC.