public async Task EncryptEntityAsync <TEntity>(TEntity entity, string key, string iv, CancellationToken cancellationToken = new CancellationToken()) where TEntity : class, IEncryptedEntity { var encryptedProperties = entity.GetType().GetProperties() .Where(p => p.GetCustomAttributes(typeof(PropertyEncrypted), true).Any(a => p.PropertyType == typeof(string))); foreach (var property in encryptedProperties) { var value = property.GetValue(entity) as string; if (string.IsNullOrEmpty(value)) { continue; } if (string.IsNullOrEmpty(key)) { key = _cryptoProvider.GetByteToken(32); } var encryptedValue = await _cryptoProvider.EncryptStringAsync(value, key, iv, cancellationToken).ConfigureAwait(false); property.SetValue(entity, encryptedValue); entity.DecryptionPrivateKey = key; } }