Ejemplo n.º 1
0
    public CryptoKey CreateKeyLabels(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
        string id        = "my-asymmetric-encrypt-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose         = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            }
        };

        key.Labels["team"]        = "alpha";
        key.Labels["cost_center"] = "cc1234";

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return(result);
    }
    public CryptoKey CreateKeyAsymmetricSign(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
        string id        = "my-asymmetric-signing-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose         = CryptoKey.Types.CryptoKeyPurpose.AsymmetricSign,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaSignPkcs12048Sha256,
            },

            // Optional: customize how long key versions should be kept before destroying.
            DestroyScheduledDuration = new Duration
            {
                Seconds = 24 * 60 * 60,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return(result);
    }
Ejemplo n.º 3
0
        // [END kms_get_keyring_policy]

        // [START kms_add_member_to_keyring_policy]
        public static void AddMemberToKeyRingPolicy(string projectId, string locationId,
                                                    string keyRingId, string role, string member)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            KeyRingName keyRingName           = new KeyRingName(projectId, locationId, keyRingId);

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

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

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

            foreach (Binding bindingResult in updateResult.Bindings)
            {
                Console.WriteLine($"Role: {bindingResult.Role}");
                foreach (string memberResult in bindingResult.Members)
                {
                    Console.WriteLine($"  Member: {memberResult}");
                }
            }
        }
    public CryptoKey CreateKeyHsm(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
        string id        = "my-hsm-encryption-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose         = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                ProtectionLevel = ProtectionLevel.Hsm,
                Algorithm       = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            },

            // Optional: customize how long key versions should be kept before destroying.
            DestroyScheduledDuration = new Duration
            {
                Seconds = 24 * 60 * 60,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return(result);
    }
Ejemplo n.º 5
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 KmsDataProtectionProvider(
     string googleProjectId,
     string keyRingLocation,
     string keyRingId)
 {
     _googleProjectId = googleProjectId ??
                        throw new ArgumentNullException(nameof(googleProjectId));
     _keyRingLocation = keyRingLocation ??
                        throw new ArgumentNullException(nameof(keyRingLocation));
     _keyRingId = keyRingId ??
                  throw new ArgumentNullException(nameof(keyRingId));
     _kms         = KeyManagementServiceClient.Create();
     _keyRingName = new KeyRingName(_googleProjectId,
                                    _keyRingLocation, _keyRingId);
     try
     {
         // Create the key ring.
         _kms.CreateKeyRing(
             new LocationName(_googleProjectId, _keyRingLocation),
             _keyRingId, new KeyRing());
     }
     catch (Grpc.Core.RpcException e)
         when(e.StatusCode == StatusCode.AlreadyExists)
         {
             // Already exists.  Ok.
         }
 }
Ejemplo n.º 7
0
    public CryptoKey CreateKeyHsm(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
        string id        = "my-hsm-encryption-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose         = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                ProtectionLevel = ProtectionLevel.Hsm,
                Algorithm       = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return(result);
    }
    public CryptoKey CreateKeyAsymmetricDecrypt(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
        string id        = "my-asymmetric-encrypt-key")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose         = CryptoKey.Types.CryptoKeyPurpose.AsymmetricDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaDecryptOaep2048Sha256,
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return(result);
    }
Ejemplo n.º 9
0
        // [END kms_create_keyring]

        // [START kms_get_keyring]
        public static void GetKeyRing(string projectId, string locationId, string keyRingId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            KeyRingName keyRingName           = new KeyRingName(projectId, locationId, keyRingId);

            KeyRing result = client.GetKeyRing(keyRingName);

            Console.WriteLine($"Found KeyRing: {result.Name}");
            Console.WriteLine($"  Created on: {result.CreateTime}");
        }
Ejemplo n.º 10
0
        // [END kms_get_cryptokey]

        // [START kms_create_cryptokey]
        public static void CreateCryptoKey(string projectId, string locationId, string keyRingId, string cryptoKeyId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            // The KeyRing in which to create the CryptoKey.
            KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

            CryptoKey cryptoKeyToCreate = new CryptoKey();

            cryptoKeyToCreate.Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt;

            CryptoKey result = client.CreateCryptoKey(keyRingName, cryptoKeyId, cryptoKeyToCreate);

            Console.Write($"Created Crypto Key: {result.Name}");
        }
Ejemplo n.º 11
0
        // [END kms_remove_member_from_cryptokey_policy]

        // [START kms_get_keyring_policy]
        public static void GetKeyRingIamPolicy(string projectId, string locationId, string keyRingId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();
            KeyRingName keyRingName           = new KeyRingName(projectId, locationId, keyRingId);

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

            foreach (Binding binding in result.Bindings)
            {
                Console.WriteLine($"Role: {binding.Role}");
                foreach (String member in binding.Members)
                {
                    Console.WriteLine($"  Member: {member}");
                }
            }
        }
Ejemplo n.º 12
0
        // [END kms_list_keyrings]

        // [START kms_list_cryptokeys]
        public static void ListCryptoKeys(string projectId, string locationId, string keyRingId)
        {
            KeyManagementServiceClient client = KeyManagementServiceClient.Create();

            // Generate the full path of the parent to use for listing crypto keys.
            KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

            foreach (CryptoKey result in client.ListCryptoKeys(keyRingName))
            {
                Console.WriteLine(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}");
            }
        }
Ejemplo n.º 13
0
    public KmsFixture()
    {
        ProjectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
        if (string.IsNullOrEmpty(ProjectId))
        {
            throw new Exception("missing GOOGLE_PROJECT_ID");
        }
        ProjectName = new ProjectName(ProjectId);

        LocationId   = "us-east1";
        LocationName = new LocationName(ProjectId, LocationId);

        KeyRingId   = RandomId();
        KeyRingName = new KeyRingName(ProjectId, LocationId, KeyRingId);
        CreateKeyRing(KeyRingId);

        AsymmetricDecryptKeyId   = RandomId();
        AsymmetricDecryptKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, AsymmetricDecryptKeyId);
        CreateAsymmetricDecryptKey(AsymmetricDecryptKeyId);

        AsymmetricSignEcKeyId   = RandomId();
        AsymmetricSignEcKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, AsymmetricSignEcKeyId);
        CreateAsymmetricSignEcKey(AsymmetricSignEcKeyId);

        AsymmetricSignRsaKeyId   = RandomId();
        AsymmetricSignRsaKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, AsymmetricSignRsaKeyId);
        CreateAsymmetricSignRsaKey(AsymmetricSignRsaKeyId);

        HsmKeyId   = RandomId();
        HsmKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, HsmKeyId);
        CreateHsmKey(HsmKeyId);

        MacKeyId   = RandomId();
        MacKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, MacKeyId);
        CreateMacKey(MacKeyId);

        SymmetricKeyId   = RandomId();
        SymmetricKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, SymmetricKeyId);
        CreateSymmetricKey(SymmetricKeyId);
    }
Ejemplo n.º 14
0
    private async Task InitializeEncryptionKeys()
    {
        var client = await KeyManagementServiceClient.CreateAsync();

        var keyRingName = KeyRingName.FromProjectLocationKeyRing(KmsKeyName.ProjectId, KmsKeyName.LocationId, KmsKeyName.KeyRingId);

        try
        {
            await client.GetKeyRingAsync(keyRingName);
        }
        catch (RpcException e) when(e.StatusCode == StatusCode.NotFound)
        {
            await client.CreateKeyRingAsync(new CreateKeyRingRequest
            {
                ParentAsLocationName = LocationName.FromProjectLocation(keyRingName.ProjectId, keyRingName.LocationId),
                KeyRingId            = KmsKeyName.KeyRingId,
                KeyRing = new KeyRing(),
            });
        }

        var keyName = Google.Cloud.Kms.V1.CryptoKeyName.FromProjectLocationKeyRingCryptoKey(KmsKeyName.ProjectId, KmsKeyName.LocationId, KmsKeyName.KeyRingId, KmsKeyName.CryptoKeyId);

        try
        {
            await client.GetCryptoKeyAsync(keyName);
        }
        catch (RpcException e) when(e.StatusCode == StatusCode.NotFound)
        {
            await client.CreateCryptoKeyAsync(new CreateCryptoKeyRequest
            {
                ParentAsKeyRingName = keyRingName,
                CryptoKeyId         = keyName.CryptoKeyId,
                CryptoKey           = new CryptoKey
                {
                    Purpose = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
                },
            });
        }
    }
    public CryptoKey CreateKeyRotationSchedule(
        string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
        string id        = "my-key-with-rotation-schedule")
    {
        // Create the client.
        KeyManagementServiceClient client = KeyManagementServiceClient.Create();

        // Build the parent key ring name.
        KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);

        // Build the key.
        CryptoKey key = new CryptoKey
        {
            Purpose         = CryptoKey.Types.CryptoKeyPurpose.EncryptDecrypt,
            VersionTemplate = new CryptoKeyVersionTemplate
            {
                Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.GoogleSymmetricEncryption,
            },

            // Rotate the key every 30 days.
            RotationPeriod = new Duration
            {
                Seconds = 60 * 60 * 24 * 30, // 30 days
            },

            // Start the first rotation in 24 hours.
            NextRotationTime = new Timestamp
            {
                Seconds = new DateTimeOffset(DateTime.UtcNow.AddHours(24)).ToUnixTimeSeconds(),
            }
        };

        // Call the API.
        CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);

        // Return the result.
        return(result);
    }