Encrypt and decrypt a Datatable in C# without iterating - c#

I need to encrypt and store a datatable in a database (like MS Access or SQL Server). Then read this database and decrypt the data in memory for query on that. How can I do that without iterating over every cell with for or loop?
I read here that (you can convert datasource to List<TmpClass>), but I don't know how?

This largely depends on the technology stack.
For example, take a look at the always on option of the SQL server: https://learn.microsoft.com/en-us/sql/relational-databases/security/encryption/develop-using-always-encrypted-with-net-framework-data-provider?view=sql-server-ver15
Always Encrypted allows client applications to encrypt sensitive data and never reveal the data or the encryption keys to SQL Server or Azure SQL Database. An Always Encrypted enabled driver, such as the .NET Framework Data Provider for SQL Server, achieves this by transparently encrypting and decrypting sensitive data in the client application
So, this achieves what you want to do without you needing to do anything in your code.
The solution you posted, says that you need to iterate the data source, get the data and have a member that does the description like this:
public class EncDataRows {
public SomeType SomeProperty {get; set;}
public void DecryptObject() {
// ENCRYPT LOGIC HERE
}
}

Related

ASP.NET MVC 5 - submitted model SecureString

I have a C# ASP.net MVC application where hundreds of users input very confidential data everyday. The client browser connects to my back-end with an end-to-end TLS encrypted connection so I'm not worries about the data not being encrypted by the HTML form.
Once the confidential data arrives to my back-end, it is used over another TLS connection and is not stored on any disks nor a database, except in string variables in memory. Now that's an issue because I need to dispose of the confidential data as soon as possible so in case an attacker gets access to the disk I'm using, they could not retrieve the confidential info from a memory dump. (the disk is running on an instance in the cloud so accessing a disk in a compromised account is not as difficult as it used to be)
I know I could use SecureString to be able to call Dispose() on the variable after I used it to make sure it is removed from the memory which is good. However, I am not sure how I can use this with a Model. Below is code snippet.
public class InputModel
{
Private String confidential;
// Getters and Setters
}
public ActionResult Index(InputModel inputModel)
{
//Create a SecureString "secureString" and store inputModel.confidential in
}
Now I could dispose secureString at any time, but inputModel.confidential is going to stay in memory which makes the whole use of SecureString irrelevant.
How can I deal with this?
Points to keep in mind:
My server is pretty secure. I am not expecting SecureString to help me encrypt the variable against a virus that might run on the server. I just want to make sure no one could retrieve the credentials from a memory dump (or at least, significantly reduce the amount of credential that can be retrieved) if the disk is accessed.
I am using TLS in all client-server communication. I do not need anything to be encrypted by the application.

Using WCF Data Services to copy one database table to another

I am little stuck in using LINQ to insert one database table to another database table located on another server as a WCF Data Service.
Suppose I have an Item class on the local database and the same Item class on the the remote server, and I want to copy all the records across.
Is there a possibility to do this from: -
private Uri svcUri = new Uri("someurl/WcfDataService.svc");
Entities = new Entities(svcUri);
.....
I know that LINQ to SQL is mostly a 1-1 mapping between classes and the database, but I heard it is possible.
You just need to construct a connectionstring pointing at the right database. That database has to have the tables the EF expects to have though. (The code would look like yours, but I've never used a Uri for a connection string.)
However, it would be more efficient to do via a stored procedure on your source database, via a Linked Database to y=the Target. This because if you do it via WCF the data has to travel twice: SourceDB -> WCF service -> TargetDB, whereas with a SP it only has one hop: SourceDB -> TargetDB. Also in the SP it will operate pretty much as a set operation whereas the WCF service will have to process one row at a time.
EDIT - Apologies: I didn't notibe the MySQL tag. I don't know whether MySQL supports Linked Databases, so feel free to ignore this if it doesn't.

How to add password protection to already created LINQ to SQL Database

I'm using LINQ to SQL Database in Windows Phone 8.1 developmentand using below connection string:
public class MyAppDBContext : DataContext
{
public static string ConnectionString = "Data Source=isostore:/MyAppDB.sdf";
public MyAppDBContext() : base(ConnectionString) { }
//Standart DBContext Code
...
}
As you can see there is no password protection. I'm looking for a solution to add password to current database. After a long research i saw this on MSDN
You cannot encrypt a database after it has been created.
This is a live app on the store and there are thousands of users already downloaded. Planning to add OneDrive backup option and don't want to upload the DB to user's OneDrive without encrpyting the database. This is very important feature and i'm unable to add this feature without protecting the DB. Any idea mighty StackOVerFlow masters?
If you are only worried about the backup, you could use some kind of encrypted container like a .zip file and password protect that instead of the database.

Connecting to remote mysql database with API

I am designing a desktop application in C#, which needs to be connected to my online mysql database. I tried to give access in control panel a "%" which means from any IP, but it is not working. May be the hosting provider (bigrock) not allowing that.
Alternatively, I am trying to write some code in online on PHP which will get the "sql" as parameter and returns the output as JSON format using json_encode.
Is there any alternate methods which is better approach.
What error do you get when you try to connect? Timeout = firewalled; Permission denied = permissions not right etc.
One solution is to create a proxy with pre-coded queries (let's call then "stored procedures") - you can then say "Run query 5, parameters A, B and C". As this would be server-server (not public) you just need to add some basic authentication system (e.g. shared rotating key, checksum using parameters etc), but also ensure the queries are not dangerous if any parameters are thrown at it.
Disclaimer: It's a solution, but I'm not actually recommending that I'd do it unless you're very sure it's safe!
Do you have Cpanel ? If yes, then try adding your host in remote MySQL.
Here the link http://www.liquidweb.com/kb/enable-remote-mysql-connections-in-cpanel/ if you are unsure on how to do that.
I'd advise that you do not create a wildcard user that can connect to the database from anywhere using embedded MySQL credentials in your application. This is a bad idea.
It would be extremely easy to determine the credentials used by your application and then a malicious user could directly connect to your DB server and begin issuing queries to your database.
They will be able to issue SELECT statements for any information in your tables, even info they shouldn't see. It then becomes much easier to exploit any known or unknown vulnerabilities in MySQL much easier since now they have console access and can send data directly to the server. If the account has the DELETE privilege, they can erase all the data in your table(s).
Also, having a PHP script that issues queries provided by the application/end-user is not ideal because one can still freely issue queries. While that option is better than giving blanket access to a remote user, it is still a bad idea.
The way to go would be to identify all of the information that the C# application needs to access, and how, and write a simple web service/API that will receive parameters and issue its own queries and return the results using XML, JSON, or even SOAP. Try to abstract the database access as much as possible from the outside world for the best security.
Hope that helps.
I would do the following:
Create a user with the host of your public ip (www.whatismyip.com).
If that doesn't work, create a user with your host as your public ARPA/PTR record:
>nslookup
> set q=ptr
> 8.8.8.8
Non-authoritative answer:
8.8.8.8.in-addr.arpa name = google-public-dns-a.google.com
8.in-addr.arpa nameserver = ns1.Level3.net
8.in-addr.arpa nameserver = ns2.Level3.net
The host would then be set to google-public-dns-a.google.com.
The second worked, and I am not sure why for me on a project I worked on in the past, where you would have thought the IP address to be sufficient.
I am not sure if you have root access or access to my.cfg. If you can edit it, make sure the line "skip-networking" is commented or removed and it contains line "bind-address = *". Restart mysql after editing config.
For security reasons you shouldn't access the database directly over the (public) network.
One way is to write a php script on the database server and access it via HTTP/POST.
You should authenticate the client via username and a hashed password. The data you are sending should be encrypted (eg with the users clear text password). Don't send complete queries, only what you want to do and the parameters. As example, you want the orders for the customer, you can send a post request with the following parameters
user=abc,password=9151440965cf9c5e07f81eee6241c042a7b78e9bb2dd4f928a8f6da5e369cdffdd2b70c70663ee30d02115731d35f1ece5aad9b362aaa9850efa99e3d197212a,data=EncryptedData
You can notice, that the password is an SHA512 Hash.
The data can be json or anything else:
{
"Command": "GetOrder",
"Limit": "10"
}
In your php code you do the following steps:
1. Authenticate the user, if the password is not correct, respond with error code etc
2. Decrypt the data
3. Execute a query
4. Return the result as encrypted data
If you don't want to store the clear text password in your database, you could store in your database the hashed value and use a double hashed value for authentication and single hashed value for encryption.
If you wan't to execute the queries with parameters from the request you should use prepared statements to prevent sql injection.
More information about en/decrypting in php see: http://php.net/manual/de/ref.mcrypt.php
Like some answers suggested, I think you are firewalled by bigrock.
Now if you want to use AJAX/PHP, you need three things:
- your C# class to send requests and receive the result
- your HTML/JS (or jQuery) file to receive the request and hand it over to your PHP. Then send you the result.
- your PHP file to query your DB.
The AJAX seems superfluous to me, you could just send your query passing it through POST or a GET parameter (i.e. example.com/query.php?req='SELECT * FROM clients')
The code would be as follow:
C# using this class made by Ali Ahsan Rana:
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest("http://www.example.com/query.php","POST","req=");
//use System.Web.Script.Serialization and myRequest.GetResponse();
Some tutorial on System.Web.Script.Serialization.
On the PHP side:
<?php
$request=$_POST['req'];
$dsn = 'mysql:dbname=mydb;host=example.com';
$user = 'ajay';
$password = '0000';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$response = $dbh->query($request);
while ($rep = $response->fetch())
{
$response_array[] = $rep;
}
$response->closeCursor();
$return = json_encode($rep);
return($return);
?>
That's a quick draft but should work AFAIK.

Migrating from SQL Server CE to SQL Server database

Currently I am using SQL Server CE for persisting my data for which I am providing with a .sdf and connection string mentioned in app.config pointing to this .sdf file.
Now I want to provide user with the flexibility to have the data stored in their own SQL Server database if present at there disposal.
Now I am facing the problem of how to change the connection string at runtime if user chooses to uses its own database ?
Or if restrict them to use my predefined .mdf file how to attach that in their SQL Server ?
My recommendation would be to have 2 connection strings in the configuration file (app or web). There is a special section for them intuitively called ConnectionStrings. You can then switch between them based on other settings.
Changing connection strings dynamically is actually pretty easy to do as long as you have a place to store the new settings (ie. web or app config files). If you provide a way for them to enter the server information you can use the ConfigurationManager class to update your app/web.config.
Ado.net typically has parameters on almost any db connection object that allows you to specify the connection string as an arguement. Additionally, there are helper classes that can be used to construct the connection string on the fly like the SqlConnectionStringBuilder or EntityConnectionStringBuilder. I personally love the Entity Framework as it allows you to create the database from the model itself if it does not already exist, provided you already have the connection string.

Categories

Resources