예제 #1
0
        private static CryptoKeyName UnpackKeyName(IFileInfo keynameFileInfo)
        {
            if (keynameFileInfo == null || !keynameFileInfo.Exists || keynameFileInfo.IsDirectory)
            {
                throw new FileNotFoundException("Encrypted file found, but "
                                                + "failed to find corresponding keyname file.",
                                                keynameFileInfo.Name);
            }

            using (var reader = new StreamReader(keynameFileInfo.CreateReadStream()))
            {
                string line = "";
                while (!reader.EndOfStream)
                {
                    line = reader.ReadLine().Trim();
                    if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#'))
                    {
                        continue; // blank or comment;
                    }
                    var keyName = CryptoKeyName.Parse(line);
                    if (keyName != null)
                    {
                        return(keyName);
                    }
                    break;
                }
                throw new Exception(
                          $"Incorrectly formatted keyname file {keynameFileInfo.Name}.\n" +
                          "Expected projects/<projectId>/locations/<locationId>/keyRings/<keyringId>/cryptoKeys/<keyId>\n" +
                          $"Instead, found {line}.");
            }
        }
    public Policy IamGetPolicy(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the resource name.
        CryptoKeyName resourceName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // The resource name could also be a key ring.
        // var resourceName = new KeyRingName(projectId, locationId, keyRingId);

        // Get the current IAM policy.
        Policy policy = client.GetIamPolicy(resourceName);

        // Print the policy.
        foreach (Binding b in policy.Bindings)
        {
            String role = b.Role;

            foreach (String member in b.Members)
            {
                // ...
            }
        }

        // Return the policy.
        return(policy);
    }
예제 #3
0
 public override DecryptResponse Decrypt(CryptoKeyName name, ByteString ciphertext, CallSettings callSettings = null)
 {
     DecryptCalls++;
     return(new DecryptResponse {
         Plaintext = ciphertext
     });
 }
        IDataProtector IDataProtectionProvider.CreateProtector(string purpose)
        {
            IDataProtector cached;

            if (_dataProtectorCache.TryGetValue(purpose, out cached))
            {
                return(cached);
            }
            // Create the crypto key:
            CryptoKey cryptoKeyToCreate = new CryptoKey()
            {
                Purpose          = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
                NextRotationTime = Timestamp.FromDateTime(DateTime.UtcNow.AddDays(7)),
                RotationPeriod   = Duration.FromTimeSpan(TimeSpan.FromDays(7))
            };
            CryptoKeyName keyName = new CryptoKeyName(_googleProjectId,
                                                      _keyRingLocation, _keyRingId, EscapeKeyId(purpose));

            try
            {
                _kms.CreateCryptoKey(_keyRingName, keyName.CryptoKeyId,
                                     cryptoKeyToCreate);
            }
            catch (Grpc.Core.RpcException e)
                when(e.StatusCode == StatusCode.AlreadyExists)
                {
                    // Already exists.  Ok.
                }
            var newProtector = new KmsDataProtector(_kms, keyName,
                                                    (string innerPurpose) =>
                                                    this.CreateProtector($"{purpose}.{innerPurpose}"));

            _dataProtectorCache.TryAdd(purpose, newProtector);
            return(newProtector);
        }
        /// <inheritdoc />
        public XElement Decrypt(XElement encryptedElement)
        {
            GaxPreconditions.CheckNotNull(encryptedElement, nameof(encryptedElement));
            XElement   payloadElement        = encryptedElement.Element(PayloadElement);
            XAttribute kmsKeyName            = encryptedElement.Attribute(KmsKeyNameAttribute);
            XAttribute localKeyDataAttribute = encryptedElement.Attribute(LocalKeyDataAttribute);

            GaxPreconditions.CheckArgument(payloadElement != null, nameof(encryptedElement), "Expected '{0}' element", PayloadElement);
            GaxPreconditions.CheckArgument(kmsKeyName != null, nameof(encryptedElement), "Expected '{0}' attribute", KmsKeyNameAttribute);
            GaxPreconditions.CheckArgument(localKeyDataAttribute != null, nameof(encryptedElement), "Expected '{0}' attribute", LocalKeyDataAttribute);

            CryptoKeyName cryptoKeyName         = CryptoKeyName.Parse(kmsKeyName.Value);
            ByteString    encryptedLocalKeyData = ByteString.FromBase64(localKeyDataAttribute.Value);
            ByteString    plaintextLocalKeyData = _kmsClient.Decrypt(cryptoKeyName, encryptedLocalKeyData).Plaintext;

            SymmetricKey key = SymmetricKey.Parser.ParseFrom(plaintextLocalKeyData);

            using (var algorithm = CreateLocalKey(key))
            {
                byte[] encryptedPayload = Convert.FromBase64String(payloadElement.Value);
                using (var decryptor = algorithm.CreateDecryptor())
                {
                    byte[] plaintextPayload = decryptor.TransformFinalBlock(encryptedPayload, 0, encryptedPayload.Length);
                    using (var stream = new MemoryStream(plaintextPayload))
                    {
                        return(XElement.Load(stream));
                    }
                }
            }
        }
        // [END kms_get_cryptokey_policy]

        // [START kms_add_member_to_cryptokey_policy]
        public static void AddMemberToCryptoKeyPolicy(string projectId, string locationId,
                                                      string keyRingId, string cryptoKeyId, string role, string member)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName       =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            Policy policy = client.GetIamPolicy(KeyNameOneof.From(cryptoKeyName));

            policy.Bindings.Add(new Binding
            {
                Role    = role,
                Members = { member }
            });

            Policy updateResult = client.SetIamPolicy(KeyNameOneof.From(cryptoKeyName), policy);

            foreach (Binding bindingResult in updateResult.Bindings)
            {
                Console.WriteLine($"Role: {bindingResult.Role}");
                foreach (string memberResult in bindingResult.Members)
                {
                    Console.WriteLine($"  Member: {memberResult}");
                }
            }
        }
        // [END kms_add_member_to_cryptokey_policy]

        // [START kms_remove_member_from_cryptokey_policy]
        public static void RemoveMemberFromCryptoKeyPolicy(string projectId, string locationId,
                                                           string keyRingId, string cryptoKeyId, string role, string member)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName       =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            Policy policy = client.GetIamPolicy(KeyNameOneof.From(cryptoKeyName));

            foreach (Binding binding in policy.Bindings.Where(b => b.Role == role))
            {
                binding.Members.Remove(member);
            }

            Policy updateResult = client.SetIamPolicy(KeyNameOneof.From(cryptoKeyName), policy);

            foreach (Binding bindingResult in updateResult.Bindings)
            {
                Console.WriteLine($"Role: {bindingResult.Role}");
                foreach (string memberResult in bindingResult.Members)
                {
                    Console.WriteLine($"  Member: {memberResult}");
                }
            }
        }
    public Policy IamRemoveMember(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key",
        string member    = "user:[email protected]")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the resource name.
        CryptoKeyName resourceName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // The resource name could also be a key ring.
        // var resourceName = new KeyRingName(projectId, locationId, keyRingId);

        // Get the current IAM policy.
        Policy policy = client.GetIamPolicy(resourceName);

        // Add the member to the policy.
        policy.RemoveRoleMember("roles/cloudkms.cryptoKeyEncrypterDecrypter", member);

        // Save the updated IAM policy.
        Policy result = client.SetIamPolicy(resourceName, policy);

        // Return the resulting policy.
        return(result);
    }
예제 #9
0
    public CryptoKey UpdateKeyUpdateLabels(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        //
        // Step 1 - get the current set of labels on the key
        //

        // Get the current key.
        CryptoKey key = client.GetCryptoKey(keyName);


        //
        // Step 2 - add a label to the list of labels
        //

        // Add a new label
        key.Labels["new_label"] = "new_value";

        // Build the update mask.
        FieldMask fieldMask = new FieldMask
        {
            Paths = { "labels" }
        };

        // Call the API.
        CryptoKey result = client.UpdateCryptoKey(key, fieldMask);

        // Return the updated key.
        return(result);
    }
예제 #10
0
        public async Task <string> Encrypt(string data, string serviceAccountId, bool createKeyIfMissing = true)
        {
            var safeId        = KeyIdCreator.Create(serviceAccountId);
            var keyring       = new KeyRingName(mProjectName, mKeyringLocation, mKeyringName);
            var cryptoKeyName =
                new CryptoKeyName(mProjectName, mKeyringLocation, mKeyringName, safeId);

            try
            {
                await mKmsService.GetCryptoKeyAsync(cryptoKeyName);
            } catch (RpcException e) when(e.StatusCode == StatusCode.NotFound && createKeyIfMissing)
            {
                var key = new CryptoKey
                {
                    Purpose         = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
                    VersionTemplate = new CryptoKeyVersionTemplate
                    {
                        ProtectionLevel = ProtectionLevel.Software
                    }
                };

                if (mRotationPeriod.HasValue)
                {
                    key.NextRotationTime = (DateTime.UtcNow + mRotationPeriod.Value).ToTimestamp();
                    key.RotationPeriod   = Duration.FromTimeSpan(mRotationPeriod.Value);
                }

                var request = await mKmsService.CreateCryptoKeyAsync(keyring, safeId, key);
            }

            var cryptoKeyPathName = new CryptoKeyPathName(mProjectName, mKeyringLocation, mKeyringName, safeId);
            var encryted          = await mKmsService.EncryptAsync(cryptoKeyPathName, ByteString.FromBase64(data));

            return(encryted.Ciphertext.ToBase64());
        }
    public async Task TestRestoreDatabaseWithEncryptionKeyAsync()
    {
        Skip.If(!_fixture.RunCmekBackupSampleTests, SpannerFixture.SkipCmekBackupSamplesMessage);
        var sample   = new RestoreDatabaseWithEncryptionAsyncSample();
        var database = await sample.RestoreDatabaseWithEncryptionAsync(_fixture.ProjectId, _fixture.InstanceId, _fixture.EncryptedRestoreDatabaseId, _fixture.FixedEncryptedBackupId, _fixture.KmsKeyName);

        Assert.Equal(_fixture.KmsKeyName, CryptoKeyName.Parse(database.EncryptionConfig.KmsKeyName));
    }
예제 #12
0
    public async Task TestCreateDatabaseWithEncryptionKeyAsync()
    {
        // Create a database with a custom encryption key.
        var sample   = new CreateDatabaseWithEncryptionKeyAsyncSample();
        var database = await sample.CreateDatabaseWithEncryptionKeyAsync(_fixture.ProjectId, _fixture.InstanceId, _fixture.EncryptedDatabaseId, _fixture.KmsKeyName);

        Assert.Equal(_fixture.KmsKeyName, CryptoKeyName.Parse(database.EncryptionConfig.KmsKeyName));
    }
예제 #13
0
        public static string Decrypt(string cipher)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName kn        = CryptoKeyName.FromUnparsed(new Google.Api.Gax.UnparsedResourceName("projects/programmingforthecloudbf/locations/global/keyRings/BFKeyring/cryptoKeys/BFkey"));
            string        realvalue = client.Decrypt(kn, ByteString.FromBase64(cipher)).Plaintext.ToStringUtf8();

            return(realvalue);
        }
예제 #14
0
        public static string Encrypt(string plaintext)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            //projects/progforthecloudt2020/locations/global/keyRings/pfckeyring001/cryptoKeys/pfckeys
            CryptoKeyName kn     = CryptoKeyName.FromUnparsed(new Google.Api.Gax.UnparsedResourceName("projects/programmingforthecloudbf/locations/global/keyRings/BFKeyring/cryptoKeys/BFkey"));
            string        cipher = client.Encrypt(kn, ByteString.CopyFromUtf8(plaintext)).Ciphertext.ToBase64();

            return(cipher);
        }
 internal KmsDataProtector(KeyManagementServiceClient kms,
                           CryptoKeyName keyName,
                           Func <string, IDataProtector> dataProtectorFactory)
 {
     _kms         = kms;
     _keyName     = keyName;
     _keyPathName = new CryptoKeyPathName(keyName.ProjectId,
                                          keyName.LocationId, keyName.KeyRingId, keyName.CryptoKeyId);
     _dataProtectorFactory = dataProtectorFactory;
 }
예제 #16
0
        public static string Encrypt(string plaintext)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            CryptoKeyName kn = CryptoKeyName.FromUnparsed(
                new Google.Api.Gax.UnparsedResourceName("projects/jurgen-cloud-project/locations/global/keyRings/pftckeyring/cryptoKeys/pftckeys"));
            string cipher = client.Encrypt(kn, ByteString.CopyFromUtf8(plaintext)).Ciphertext.ToBase64();

            return(cipher);
        }
예제 #17
0
        public async Task <string> Decrypt(string encryptedData, string serviceAccountId)
        {
            var safeId        = KeyIdCreator.Create(serviceAccountId);
            var cryptoKeyName =
                new CryptoKeyName(mProjectName, mKeyringLocation, mKeyringName, safeId);
            var result =
                await mKmsService.DecryptAsync(
                    cryptoKeyName,
                    ByteString.FromBase64(encryptedData));

            return(result.Plaintext.ToBase64());
        }
예제 #18
0
        // [END kms_encrypt]

        // [START kms_decrypt]
        public static void Decrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId,
                                   string ciphertextFile, string plaintextFile)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName       =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            byte[]          ciphertext = File.ReadAllBytes(ciphertextFile);
            DecryptResponse result     = client.Decrypt(cryptoKeyName, ByteString.CopyFrom(ciphertext));

            // Output decrypted data to a file.
            File.WriteAllBytes(plaintextFile, result.Plaintext.ToByteArray());
            Console.Write($"Decrypted file created: {plaintextFile}");
        }
        public void Roundtrip(int dataSize)
        {
            var key       = new CryptoKeyName("projectId", "locationId", "keyRingId", Guid.NewGuid().ToString());
            var client    = new FakeKmsClient();
            var encryptor = new KmsXmlEncryptor(client, key);
            var decryptor = new KmsXmlDecryptor(client);
            var plain     = new XElement("Original", new string ('x', dataSize));
            var encrypted = encryptor.Encrypt(plain);

            Assert.DoesNotContain("Plaintext value", encrypted.EncryptedElement.ToString());
            var decrypted = decryptor.Decrypt(encrypted.EncryptedElement);

            Assert.Equal(plain.ToString(), decrypted.ToString());
        }
예제 #20
0
        public string Encrypt(string plaintext)
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            // Build the key name.
            CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

            //Encrypt data
            string cipher = client.Encrypt(keyName, ByteString.CopyFromUtf8(plaintext)).Ciphertext.ToBase64();


            return(cipher);
        }
예제 #21
0
        // [END kms_get_keyring]

        // [START kms_get_cryptokey]
        public static void GetCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName       =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            CryptoKey result = client.GetCryptoKey(cryptoKeyName);

            Console.WriteLine($"Name: {result.Name}");
            Console.WriteLine($"Created: {result.CreateTime}");
            Console.WriteLine($"Purpose: {result.Purpose}");
            Console.WriteLine($"Primary: {result.Primary}");
            Console.WriteLine($"  State: {result.Primary.State}");
            Console.WriteLine($"  Created: {result.Primary.CreateTime}");
        }
예제 #22
0
    public void DecryptsData()
    {
        var plaintext = "testing1234";

        // Create some ciphertext.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();
        CryptoKeyName keyName             = new CryptoKeyName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.SymmetricKeyId);
        var           result = client.Encrypt(keyName, ByteString.CopyFromUtf8(plaintext));

        // Run the sample code.
        var response = _sample.DecryptSymmetric(
            projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.SymmetricKeyId,
            ciphertext: result.Ciphertext.ToByteArray());

        Assert.Equal(plaintext, response);
    }
예제 #23
0
        public string Decrypt(string cipher)
        {
            // Create the client.
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            // Build the key name.
            CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);


            DecryptResponse result = client.Decrypt(keyName, ByteString.FromBase64(cipher));

            //convert the result to byteArray
            byte[] plaintext = result.Plaintext.ToByteArray();

            return(Encoding.UTF8.GetString(plaintext));
        }
예제 #24
0
        public static string Decrypt(string cipher)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            CryptoKeyName kn = CryptoKeyName.FromUnparsed(
                new Google.Api.Gax.UnparsedResourceName("projects/jurgen-cloud-project/locations/global/keyRings/pftckeyring/cryptoKeys/pftckeys"));

            byte[] cipherText = Convert.FromBase64String(cipher);

            DecryptResponse result = client.Decrypt(kn, ByteString.CopyFrom(cipherText));

            byte[] bytes       = result.Plaintext.ToByteArray();
            string finalResult = Encoding.Default.GetString(bytes);

            return(finalResult);
        }
예제 #25
0
    public CryptoKey UpdateKeySetPrimary(
        string projectId    = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key",
        string keyVersionId = "123")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Call the API.
        CryptoKey result = client.UpdateCryptoKeyPrimaryVersion(keyName, keyVersionId);

        // Return the updated key.
        return(result);
    }
        public void EncryptFormat()
        {
            var key       = new CryptoKeyName("projectId", "locationId", "keyRingId", Guid.NewGuid().ToString());
            var encryptor = new KmsXmlEncryptor(new FakeKmsClient(), key);
            var plain     = new XElement("Original", "Plaintext value");
            var encrypted = encryptor.Encrypt(plain);

            Assert.Equal(typeof(KmsXmlDecryptor), encrypted.DecryptorType);
            var element = encrypted.EncryptedElement;

            Assert.Equal(KmsXmlConstants.EncryptedElement, element.Name);
            Assert.Equal(key.ToString(), element.Attribute(KmsXmlConstants.KmsKeyNameAttribute).Value);
            // Validate that the key data contains valid base64 data
            Convert.FromBase64String(element.Attribute(KmsXmlConstants.LocalKeyDataAttribute).Value);
            // Validate that the payload contains valid base64 data.
            Convert.FromBase64String(element.Element(KmsXmlConstants.PayloadElement).Value);
        }
예제 #27
0
    public CryptoKeyVersion CreateKeyVersion(string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Build the key version.
        CryptoKeyVersion keyVersion = new CryptoKeyVersion {
        };

        // Call the API.
        CryptoKeyVersion result = client.CreateCryptoKeyVersion(keyName, keyVersion);

        // Return the result.
        return(result);
    }
예제 #28
0
        // [END kms_restore_cryptokey_version]

        // [START kms_get_cryptokey_policy]
        public static void GetCryptoKeyIamPolicy(string projectId, string locationId,
                                                 string keyRingId, string cryptoKeyId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            CryptoKeyName cryptoKeyName       =
                new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId);

            Policy result = client.GetIamPolicy(KeyNameOneof.From(cryptoKeyName));

            foreach (Binding binding in result.Bindings)
            {
                Console.WriteLine($"Role: {binding.Role}");
                foreach (String member in binding.Members)
                {
                    Console.WriteLine($"  Member: {member}");
                }
            }
        }
예제 #29
0
        public void RoundtripViaDataProtector(int dataSize)
        {
            var keyName     = Environment.GetEnvironmentVariable("TEST_PROJECT_KMS_KEY");
            var key         = CryptoKeyName.Parse(keyName);
            var xmlDocument = new XDocument(new XElement("root"));
            var random      = new Random();
            var plaintext   = new byte[dataSize];

            random.NextBytes(plaintext);

            Assert.Empty(xmlDocument.Root.Elements());
            var encrypted = Encrypt(xmlDocument, key, plaintext);

            Assert.Single(xmlDocument.Root.Elements());
            var roundtrip = Decrypt(xmlDocument, key, encrypted);

            Assert.Equal(plaintext, roundtrip);

            byte[] Encrypt(XDocument document, CryptoKeyName cryptoKeyName, byte[] bytes)
            {
                var serviceCollection = new ServiceCollection();

                serviceCollection.AddDataProtection()
                .ProtectKeysWithGoogleKms(cryptoKeyName)
                .PersistKeysToMemory(document);
                var serviceProvider = serviceCollection.BuildServiceProvider();
                var protector       = serviceProvider.GetDataProtector(new[] { "test" });

                return(protector.Protect(bytes));
            }

            byte[] Decrypt(XDocument document, CryptoKeyName cryptoKeyName, byte[] bytes)
            {
                var serviceCollection = new ServiceCollection();

                serviceCollection.AddDataProtection()
                .ProtectKeysWithGoogleKms(cryptoKeyName)
                .PersistKeysToMemory(document);
                var serviceProvider = serviceCollection.BuildServiceProvider();
                var protector       = serviceProvider.GetDataProtector(new[] { "test" });

                return(protector.Unprotect(bytes));
            }
        }
    public byte[] EncryptSymmetric(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key",
        string message   = "Sample message")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the key name.
        CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId);

        // Convert the message into bytes. Cryptographic plaintexts and
        // ciphertexts are always byte arrays.
        byte[] plaintext = Encoding.UTF8.GetBytes(message);

        // Call the API.
        EncryptResponse result = client.Encrypt(keyName, ByteString.CopyFrom(plaintext));

        // Return the ciphertext.
        return(result.Ciphertext.ToByteArray());
    }