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 void EncryptsData() { var message = "testing1234"; // Run the sample code. var signature = _sample.SignAsymmetric( projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.AsymmetricSignRsaKeyId, keyVersionId: "1", message: message); // Calculate the hash of the message. var sha256 = SHA256.Create(); var digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(message)); // Get the public key. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.AsymmetricSignRsaKeyId, "1"); var publicKey = client.GetPublicKey(keyVersionName); // Split the key into blocks and base64-decode the PEM parts. var blocks = publicKey.Pem.Split("-", StringSplitOptions.RemoveEmptyEntries); var pem = Convert.FromBase64String(blocks[1]); // Create a new RSA key. var rsa = RSA.Create(); rsa.ImportSubjectPublicKeyInfo(pem, out _); var verified = rsa.VerifyHash(digest, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss); Assert.True(verified); }
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); }
public CryptoKeyVersion CreateKeyVersion(string keyId) { KeyManagementServiceClient client = KeyManagementServiceClient.Create(); var result = client.CreateCryptoKeyVersion(new CreateCryptoKeyVersionRequest { ParentAsCryptoKeyName = new CryptoKeyName(ProjectId, LocationId, KeyRingId, keyId), }); for (var i = 1; i <= 5; i++) { var version = client.GetCryptoKeyVersion(new GetCryptoKeyVersionRequest { CryptoKeyVersionName = result.CryptoKeyVersionName, }); if (version.State == CryptoKeyVersion.Types.CryptoKeyVersionState.Enabled) { return(version); } Thread.Sleep(500 * i); } throw new TimeoutException($"{result.Name} not enabled within time"); }
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); }
// [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 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); }
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); }
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 UpdateKeyRemoveRotation(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. CryptoKey key = new CryptoKey { CryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId), RotationPeriod = null, NextRotationTime = null, }; // Build the update mask. FieldMask fieldMask = new FieldMask { Paths = { "rotation_period", "next_rotation_time" }, }; // Call the API. CryptoKey result = client.UpdateCryptoKey(key, fieldMask); // Return the updated key. return(result); }
/// <summary> /// Creates a new instance of <see cref="AuthenticodeKeyVaultSigner" />. /// </summary> /// <param name="signingAlgorithm"> /// An instance of an asymmetric algorithm that will be used to sign. It must support signing with /// a private key. /// </param> /// <param name="signingCertificate">The X509 public certificate for the <paramref name="signingAlgorithm"/>.</param> /// <param name="timeStampConfiguration">The timestamp configuration for timestamping the file. To omit timestamping, /// use <see cref="TimeStampConfiguration.None"/>.</param> /// <param name="additionalCertificates">Any additional certificates to assist in building a certificate chain.</param> public AuthenticodeKeyVaultSigner(KeyManagementServiceClient client, CryptoKeyVersionName ckvn, TimeStampConfiguration timeStampConfiguration, X509Certificate2Collection additionalCertificates = null) { _client = client; _ckvn = ckvn; _signingCertificate = additionalCertificates[0]; _timeStampConfiguration = timeStampConfiguration ?? throw new ArgumentNullException(nameof(timeStampConfiguration)); _signingAlgorithm = _signingCertificate.SignatureAlgorithm.FriendlyName.Substring(0, 6).ToUpper(); _certificateStore = MemoryCertificateStore.Create(); _chain = new X509Chain(); if (additionalCertificates != null) { _chain.ChainPolicy.ExtraStore.AddRange(additionalCertificates); } //We don't care about the trustworthiness of the cert. We just want a chain to sign with. _chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllFlags; if (!_chain.Build(_signingCertificate)) { throw new InvalidOperationException("Failed to build chain for certificate."); } for (var i = 0; i < _chain.ChainElements.Count; i++) { if (!_chain.ChainElements[i].Certificate.SubjectName.Equals(_chain.ChainElements[i].Certificate.IssuerName)) { _certificateStore.Add(_chain.ChainElements[i].Certificate); } } _signCallback = SignCallback; }
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); }
public EncryptedDirectoryContents( KeyManagementServiceClient kms, IDirectoryContents innerDirectoryContents) { _kms = kms; _innerDirectoryContents = innerDirectoryContents; }
public byte[] SignMac( string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123", string data = "Sample data") { // Create the client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the key version name. CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId); // Convert the data into a ByteString. ByteString dataByteString = ByteString.CopyFromUtf8(data); // Call the API. MacSignResponse result = client.MacSign(keyVersionName, dataByteString); // The data comes back as raw bytes, which may include non-printable // characters. To print the result, you could encode it as base64. // string encodedSignature = result.Mac.ToBase64(); // Get the signature. byte[] signature = result.Mac.ToByteArray(); // Return the result. return(signature); }
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); }
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. } }
public byte[] EncryptAsymmetric( string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123", string message = "Sample message") { // Create the client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the key version name. CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId); // Get the public key. PublicKey publicKey = 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. RSA rsa = 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); return(ciphertext); }
public bool VerifyAsymmetricSignatureRsa( string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", string keyVersionId = "123", string message = "my message", byte[] signature = null) { // Build the key version name. CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, keyId, keyVersionId); // Calculate the digest of the message. SHA256 sha256 = SHA256.Create(); byte[] digest = sha256.ComputeHash(Encoding.UTF8.GetBytes(message)); // Get the public key. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); PublicKey publicKey = 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. RSA rsa = RSA.Create(); rsa.ImportSubjectPublicKeyInfo(pem, out _); // Verify the signature. bool verified = rsa.VerifyHash(digest, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pss); // Return the result. return(verified); }
// [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 void DecryptsDataa() { var plaintext = "testing1234"; // Get the public key. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); CryptoKeyVersionName keyVersionName = new CryptoKeyVersionName(_fixture.ProjectId, _fixture.LocationId, _fixture.KeyRingId, _fixture.AsymmetricDecryptKeyId, "1"); var publicKey = client.GetPublicKey(keyVersionName); // Split the key into blocks and base64-decode the PEM parts. var blocks = publicKey.Pem.Split("-", StringSplitOptions.RemoveEmptyEntries); var pem = Convert.FromBase64String(blocks[1]); // Create a new RSA key. var rsa = RSA.Create(); rsa.ImportSubjectPublicKeyInfo(pem, out _); // Encrypt the data. var ciphertext = rsa.Encrypt(Encoding.UTF8.GetBytes(plaintext), RSAEncryptionPadding.OaepSHA256); // Run the sample code. var result = _sample.DecryptAsymmetric( projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.AsymmetricDecryptKeyId, keyVersionId: "1", ciphertext: ciphertext); Assert.Equal(plaintext, result); }
public EncryptedFileProvider( string fullPath, KeyManagementServiceClient kms = null, IFileProvider innerProvider = null) { _kms = kms ?? KeyManagementServiceClient.Create(); _innerProvider = innerProvider ?? new PhysicalFileProvider(fullPath); }
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); }
private EncryptedFileInfo(KeyManagementServiceClient kms, IFileInfo innerFileInfo, IFileInfo keynameFileInfo) { this.kms = kms; this.keynameFileInfo = keynameFileInfo; this.innerFileInfo = innerFileInfo; this.cryptoKeyName = new Lazy <CryptoKeyName>(() => UnpackKeyName(keynameFileInfo)); }
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); }
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); }
public KeyRing CreateKeyRing(string keyRingId) { KeyManagementServiceClient client = KeyManagementServiceClient.Create(); return(client.CreateKeyRing(new CreateKeyRingRequest { ParentAsLocationName = LocationName, KeyRingId = keyRingId, })); }
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; }
// [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}"); }
public void CreatesKeyVersion() { // Run the sample code. var result = _sample.CreateKeyVersion( projectId: _fixture.ProjectId, locationId: _fixture.LocationId, keyRingId: _fixture.KeyRingId, keyId: _fixture.SymmetricKeyId); // Get the key version. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); var response = client.GetCryptoKeyVersion(result.CryptoKeyVersionName); Assert.NotNull(response.CryptoKeyVersionName.CryptoKeyVersionId); }
// [END kms_destroy_cryptokey_version] // [START kms_restore_cryptokey_version] public static void RestoreCryptoKeyVersion(string projectId, string locationId, string keyRingId, string cryptoKeyId, string versionId) { KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // The CryptoKeyVersion to restore. CryptoKeyVersionName versionName = new CryptoKeyVersionName(projectId, locationId, keyRingId, cryptoKeyId, versionId); CryptoKeyVersion result = client.RestoreCryptoKeyVersion(versionName); Console.Write($"Restored Crypto Key Version: {result.Name}"); }