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}."); } }
/// <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)); } } } }
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)); }
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)); }
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)); } }
/// <summary> /// Configures the data protection system to protect keys with specified key in Google Cloud KMS. /// </summary> /// <param name="builder">The data protection builder to configure. Must not be null.</param> /// <param name="keyName">The name of the KMS key to use. Must not be null.</param> /// <returns>The same builder, for chaining purposes.</returns> public static IDataProtectionBuilder ProtectKeysWithGoogleKms( this IDataProtectionBuilder builder, string keyName) => ProtectKeysWithGoogleKms(builder, CryptoKeyName.Parse(GaxPreconditions.CheckNotNull(keyName, nameof(keyName))), null);