Exemple #1
0
        private IKeyManagement GetGoogleCloudKeyManagment()
        {
            var location        = Configuration.GetValue <string>("KeyManagement:GoogleKms:Location");
            var keyRingName     = Configuration.GetValue <string>("KeyManagement:GoogleKms:KeyRingName");
            var protectionLevel = Configuration.GetValue <string>("KeyManagement:GoogleKms:ProtectionLevel");
            var credentialsPath = Configuration.GetValue <string>("KeyManagement:GoogleKms:CredentialsPath");

            var serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(File.OpenRead(credentialsPath));
            var credentials = GoogleCredential.FromServiceAccountCredential(serviceAccountCredential);

            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(new[]
                {
                    CloudKMSService.Scope.CloudPlatform
                });
            }

            var kmsService = new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                GZipEnabled           = true
            });


            return(new GoogleCloudKeyManagment(
                       kmsService,
                       serviceAccountCredential.ProjectId,
                       keyRingName,
                       location,
                       protectionLevel));
        }
Exemple #2
0
 internal KmsDataProtector(CloudKMSService kms, string keyName,
                           Func <string, IDataProtector> dataProtectorFactory)
 {
     _kms     = kms;
     _keyName = keyName;
     _dataProtectorFactory = dataProtectorFactory;
 }
Exemple #3
0
 public GoogleCloudKeyManagment(
     CloudKMSService kmsService,
     string projectName,
     string keyringName,
     string keyringLocation,
     string protectionLevel)
 {
     mKmsService      = kmsService;
     mProjectName     = projectName;
     mKeyringName     = keyringName;
     mKeyringLocation = keyringLocation;
     mProtectionLevel = protectionLevel;
 }
Exemple #4
0
        public static string Decrypt(CloudKMSService cloudKms, string projectId, string locationId, string keyRingId, string cryptoKeyId, string ciphertext)
        {
            //var cloudKms = CreateAuthorizedClient();
            // Generate the full path of the crypto key to use for encryption.
            var            cryptoKey      = $"projects/{projectId}/locations/{locationId}/keyRings/{keyRingId}/cryptoKeys/{cryptoKeyId}";
            DecryptRequest decryptRequest = new DecryptRequest();

            decryptRequest.Ciphertext = ciphertext;
            Console.WriteLine($"dataToDecrypt.Ciphertext: {decryptRequest.Ciphertext}");
            var result = cloudKms.Projects.Locations.KeyRings.CryptoKeys.Decrypt(name: cryptoKey, body: decryptRequest).Execute();
            // Output decrypted data to a file.
            var plaintext = result.Plaintext;

            Console.WriteLine($"Decrypted file created: {plaintext}");
            return(plaintext);
        }
        public static void Main(string[] args)
        {
            // Your Google Cloud Platform project ID.
            string projectId = "YOUR-PROJECT-ID";

            // Lists keys in the "global" location.
            string location = "global";

            // The resource name of the location associated with the key rings.
            string parent = $"projects/{projectId}/locations/{location}";

            // Authorize the client using Application Default Credentials.
            // See: https://developers.google.com/identity/protocols/application-default-credentials
            GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;

            // Specify the Cloud Key Management Service scope.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    Google.Apis.CloudKMS.v1.CloudKMSService.Scope.CloudPlatform
                });
            }
            // Instantiate the Cloud Key Management Service API.
            CloudKMSService cloudKms = new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled           = false
            });

            // List key rings.
            ListKeyRingsResponse result = cloudKms.Projects.Locations.KeyRings.List(parent).Execute();

            if (result.KeyRings != null)
            {
                Console.WriteLine("Key Rings: ");
                result.KeyRings.ToList().ForEach(response => Console.WriteLine(response.Name));
            }
            else
            {
                Console.WriteLine("No Key Rings found.");
            }
        }
Exemple #6
0
        public KmsDataProtectionProvider(
            IOptions <KmsDataProtectionProviderOptions> options)
        {
            _options = options;
            // Create a KMS service client with credentials.
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefaultAsync().Result;

            // Inject the Cloud Key Management Service scope
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    CloudKMSService.Scope.CloudPlatform
                });
            }
            _kms = new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled           = false
            });
            // Create the key ring.
            var parent = string.Format("projects/{0}/locations/{1}",
                                       options.Value.ProjectId, options.Value.Location);
            KeyRing keyRingToCreate = new KeyRing();
            var     request         = new ProjectsResource.LocationsResource
                                      .KeyRingsResource.CreateRequest(_kms, keyRingToCreate, parent);

            request.KeyRingId = options.Value.KeyRing;
            try
            {
                request.Execute();
            }
            catch (Google.GoogleApiException e)
                when(e.HttpStatusCode == System.Net.HttpStatusCode.Conflict)
                {
                    // Already exists.  Ok.
                }
        }
        public GoogleCloudKeyManagmentTests()
        {
            mConfiguration = new ConfigurationBuilder()
                             .AddJsonFile("settings.json")
                             .AddEnvironmentVariables().Build();

            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write(mConfiguration.GetValue <string>("KeyManagment:GoogleKms:Credentials"));
            writer.Flush();
            stream.Position = 0;
            var serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(stream);
            var credentials = GoogleCredential.FromServiceAccountCredential(serviceAccountCredential);

            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(new[]
                {
                    CloudKMSService.Scope.CloudPlatform
                });
            }

            mCloudKmsService = new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credentials,
                GZipEnabled           = true
            });
            var location        = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:Location");
            var keyRingName     = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:KeyRingName");
            var protectionLevel = mConfiguration.GetValue <string>("KeyManagment:GoogleKms:ProtectionLevel");

            mGoogleCloudKeyManagement = new GoogleCloudKeyManagment(
                mCloudKmsService,
                serviceAccountCredential.ProjectId,
                keyRingName,
                location,
                protectionLevel);
        }
Exemple #8
0
        public KmsDataProtectionProvider(IOptions <KmsDataProtectionProviderOptions> options)
        {
            _options = options;

            GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;

            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[] { CloudKMSService.Scope.CloudPlatform });
            }

            _kms = new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled           = false
            });

            var parent = string.Format("projects/{0}/locations/{1}", options.Value.ProjectId, options.Value.Location);

            KeyRing keyRingToCreate = new KeyRing();

            var request = new ProjectsResource.LocationsResource.KeyRingsResource.CreateRequest(_kms, keyRingToCreate, parent);

            request.KeyRingId = options.Value.KeyRing;

            try
            {
                request.Execute();
            }
            catch (Google.GoogleApiException e)
                when(e.HttpStatusCode == System.Net.HttpStatusCode.Conflict) /* Already exists.  Ok.*/ }
            {

        }

        IDataProtector IDataProtectionProvider.CreateProtector(string purpose)
        {
            IDataProtector cached;

            if (_dataProtectorCache.TryGetValue(purpose, out cached))
            {
                return(cached);
            }

            var keyRingName = string.Format(
                "projects/{0}/locations/{1}/keyRings/{2}",
                _options.Value.ProjectId, _options.Value.Location,
                _options.Value.KeyRing);

            string rotationPeriod = string.Format("{0}s", TimeSpan.FromDays(7).TotalSeconds);

            CryptoKey cryptoKeyToCreate = new CryptoKey()
            {
                Purpose          = "ENCRYPT_DECRYPT",
                NextRotationTime = DateTime.UtcNow.AddDays(7),
                RotationPeriod   = rotationPeriod
            };

            var request = new ProjectsResource.LocationsResource.KeyRingsResource.CryptoKeysResource.CreateRequest(_kms, cryptoKeyToCreate, keyRingName);

            string keyId = EscapeKeyId(purpose);

            request.CryptoKeyId = keyId;

            string keyName;

            try
            {
                keyName = request.Execute().Name;
            }
            catch (Google.GoogleApiException e)
                when(e.HttpStatusCode == System.Net.HttpStatusCode.Conflict)
                {
                    // Already exists.  Ok.
                    keyName = string.Format("{0}/cryptoKeys/{1}", keyRingName, keyId);
                }

            var newProtector = new KmsDataProtector(_kms, keyName, (string innerPurpose) => this.CreateProtector($"{purpose}.{innerPurpose}"));

            _dataProtectorCache.TryAdd(purpose, newProtector);

            return(newProtector);
        }
Exemple #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath  = "/login";
                options.LogoutPath = "/signout";
            })
            .AddStrava(options =>
            {
                // ClientId and CleintSecret can be configured in your appsettings.json file
                // ....
                //  "Strava": {
                //    "ClientId": "5275",
                //    "ClientSecret": "5930e45f6727e4656eb830e7a3893efbcef2a37b"
                //  },
                // ....
                // Your Google Cloud Platform project ID.
                string projectId = "jenkins-x-002";

                // Lists keys in the "global" location.
                string location = "global";

                // The resource name of the location associated with the key rings.
                string parent = $"projects/{projectId}/locations/{location}";

                // Authorize the client using Application Default Credentials.
                // See: https://developers.google.com/identity/protocols/application-default-credentials
                GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;
                // Specify the Cloud Key Management Service scope.
                if (credential.IsCreateScopedRequired)
                {
                    credential = credential.CreateScoped(new[]
                    {
                        Google.Apis.CloudKMS.v1.CloudKMSService.Scope.CloudPlatform
                    });
                }
                // Instantiate the Cloud Key Management Service API.
                CloudKMSService cloudKms = new CloudKMSService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    GZipEnabled           = false
                });
                string keyRingId   = "oauth_keystore";
                string cryptoKeyId = "strava_client_secret";

                var ClientIdEnc  = Configuration["Strava:ClientId"];
                options.ClientId = Decrypt(cloudKms, projectId, location, keyRingId, cryptoKeyId, ClientIdEnc);

                var ClientSecretEnc  = Configuration["Strava:ClientSecret"];
                options.ClientSecret = Decrypt(cloudKms, projectId, location, keyRingId, cryptoKeyId, ClientSecretEnc);
            });
        }
        public static int Main(string[] args)
        {
            // Your Google Cloud Platform project ID.
            string projectId = "YOUR-PROJECT-ID";

            if (projectId == "YOUR-" + "PROJECT-ID")
            {
                Console.Error.WriteLine("Modify Program.cs and replace YOUR-"
                                        + "PROJECT-ID with your google project id.");
                return(-1);
            }

            // Authorize the client using Application Default Credentials.
            // See: https://developers.google.com/identity/protocols/application-default-credentials
            GoogleCredential credential =
                GoogleCredential.GetApplicationDefaultAsync().Result;

            // Specify the Cloud Key Management Service scope.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    CloudKMSService.Scope.CloudPlatform
                });
            }
            var cloudKms =
                new CloudKMSService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled           = false
            });

            // Create the key ring.
            string location = "global";
            // The resource name of the location associated with the key rings.
            string  parent          = $"projects/{projectId}/locations/{location}";
            KeyRing keyRingToCreate = new KeyRing();
            var     request         = new ProjectsResource.LocationsResource
                                      .KeyRingsResource.CreateRequest(cloudKms, keyRingToCreate, parent);
            string keyRingId = request.KeyRingId = "QuickStartCore";

            try
            {
                request.Execute();
            }
            catch (Google.GoogleApiException e)
                when(e.HttpStatusCode == System.Net.HttpStatusCode.Conflict)
                {
                    // Already exists.  Ok.
                }

            // Create the crypto key:
            var keyRingName = string.Format(
                "projects/{0}/locations/{1}/keyRings/{2}",
                projectId, location, keyRingId);
            string rotationPeriod = string.Format("{0}s",
                                                  TimeSpan.FromDays(7).TotalSeconds);
            CryptoKey cryptoKeyToCreate = new CryptoKey()
            {
                Purpose          = "ENCRYPT_DECRYPT",
                NextRotationTime = DateTime.UtcNow.AddDays(7),
                RotationPeriod   = rotationPeriod
            };
            string keyId = "Key1";
            string keyName;

            try
            {
                keyName = new ProjectsResource.LocationsResource
                          .KeyRingsResource.CryptoKeysResource.CreateRequest(
                    cloudKms, cryptoKeyToCreate, keyRingName)
                {
                    CryptoKeyId = keyId
                }.Execute().Name;
            }
            catch (Google.GoogleApiException e)
                when(e.HttpStatusCode == System.Net.HttpStatusCode.Conflict)
                {
                    // Already exists.  Ok.
                    keyName = string.Format("{0}/cryptoKeys/{1}",
                                            keyRingName, keyId);
                }

            // Encrypt a string.
            var encryptResult = cloudKms.Projects.Locations.KeyRings.CryptoKeys
                                .Encrypt(new EncryptRequest()
            {
                Plaintext = Convert.ToBase64String(Encoding.UTF8.GetBytes("Hello World."))
            }, keyName).Execute();
            var cipherText =
                Convert.FromBase64String(encryptResult.Ciphertext);

            // Decrypt the string.
            var result = cloudKms.Projects.Locations.KeyRings.CryptoKeys
                         .Decrypt(new DecryptRequest()
            {
                Ciphertext = Convert.ToBase64String(cipherText)
            }, keyName).Execute();

            Console.WriteLine(Encoding.UTF8.GetString(Convert.FromBase64String(result.Plaintext)));
            return(0);
        }