Best practices for encrypting and decrypting passwords? (C#/.NET) - c#

I need to store and encrypt a password in a (preferably text) file, that I later need to be able to decrypt. The password is for another service that I use, and needs to be sent there in clear text (over SSL). This is not something I can change. What are best practices in this area? How can achieve some degree of protection of the password from malicious users?
My platform is WinForms with C#/.NET 3.5.
Thanks.

I am assuming that you want to encrypt the password as it will be on the users machine and they will (possibly) be able to find it and use it? If so you are basically screwed - no matter what you do, since it is in the users domain they will be able to get it and figure out the encryption and get the password for the encryption (remember that using Reflector - and it's clones - isn't out of the reach of most) and decrypt it and they have it. In short all you are doing is obfuscating the password, not securing it.
What I would recommend is actually move it out of the users control. For example put up a web service which communicates with the client and returns the password securely when requested. This also allows you to change the password, if needed in future as well as provides you with a way to validate legitimate users.

Why you need to decrypt the password? Usually a salted hash of the password is stored and compared. If you encrypt/decrypt the password you have the password as plain text again and this is dangerous. The hash should be salted to avoid duplicated hash if the some users have the same passwords. For the salt you can take the user name.
HashAlgorithm hash = new SHA256Managed();
string password = "12345";
string salt = "UserName";
// compute hash of the password prefixing password with the salt
byte[] plainTextBytes = Encoding.UTF8.GetBytes(salt + password);
byte[] hashBytes = hash.ComputeHash(plainTextBytes);
string hashValue = Convert.ToBase64String(hashBytes);
You can calculate the salted hash of the password and store that within your file. During the authentication you calculate the hash from the user entries again and compare this hash with the stored password hash.
Since it should be very difficult (its never impossible, always a matter of time) to get the plain text from a hash the password is protected from reading as plain text again.
Tip: Never store or send a password unencrypted. If you get a new password, encrypt is as soon as possible!

System.Security.Cryptography.ProtectedData in the System.Security assembly uses some Windows APIs to encrypt data with a password only it knows.
One possibly use of this would be to have a Windows service that actually does the operation requiring the password. The application that the user interacts with calls into the service via remoting or WCF. As long as the service used DataProtectionScope.CurrentUser and the service user is different from the logged on user, the password should be pretty safe.
This of course assumes that the users are running as limited users who cannot modify the service or run program as the service's user.

Because you are using WinForms and .Net, your code is going to be visible in MSIL - even if obfuscated, and therefore your decryption code is visible.
Who are you trying to hide the password from? Is the user of the app not supposed to know the password?
I think you are going to need to do some user validation, and I would be tempted to put keys to the decryption in a separate database and provide some other mechanism to get that out which should require authentication. That way you can get the decryption code out of the winforms app.
I would also suggest a separate service which runs to regularly change the encryption decryption keys and updates all passwords in the database.

Encrypted in AES if you must store it in a text file.
AES is better known as Rijndael in c#
http://www.obviex.com/samples/Encryption.aspx
Better place would be the registry, since it would protect other users of the machine getting to it.
Still not the best storing it anywhere that a user might be able to get to is dangerous a 1/2 way decent developer can load up your app in reflector and find your key.
Or there is System.Security.Cryptography.ProtectedData that someone else suggested.
The best you could do on a machine is create a certificate and encrypt/decrypt with it loaded and locked down in the machine's keystore. (Still have to deal with the certificate password being in your code)

I just implemented something like this for storing a user supplied password. I converted the encrypted result to a base 64 encoded string, so that I could easily store it in my application's user settings.
From your question, it seems that your malicious user is actually using your application, so this will only provide obfuscation. Though no key would be revealed through the use of Reflector, the plain text would be visible in a debugger.
static byte[] entropy = { 65, 34, 87, 33 };
public string Password
{
get
{
if (this.EncryptedPassword == string.Empty)
{
return string.Empty;
}
var encrypted = Convert.FromBase64String(this.EncryptedPassword);
var data = ProtectedData.Unprotect(encrypted, entropy, DataProtectionScope.CurrentUser);
var password = Encoding.UTF8.GetString(data);
return password;
}
set
{
if (value == string.Empty)
{
this.EncryptedPassword = string.Empty;
return;
}
var data = Encoding.UTF8.GetBytes(value);
var encrypted = ProtectedData.Protect(data, entropy, DataProtectionScope.CurrentUser);
var stored = Convert.ToBase64String(encrypted);
this.EncryptedPassword = stored;
}
}

Do not store the password as part of the code. Aside from the issues of decompilation and relying on security through obscurity, if you change the password you need to recompile and redistribution your application.
Store the password as a webservice or in a database that the application has access to. You're communicating with a service over the web, so you will be connected, after all.

One of the most important thing is the permissions on the file. Even if the content is encrypted you need to make sure that only the processes that need access to the file can read it.

Since you must send the password in unencrypted form over the network, there is nothing you can do to protect it 100%.
AES is good enough if you need to store locally, and talking about disasms, network sniffers etc is not particulary good contra-argument becuase the same thing can be done with any program (sure, ASM is harder then CIL but its a minior point).
Such password protecting is good enough to prevent casual pick up, not to prevent decoding by proffesionals.

Related

Encrypt a string in C# Settings.settings

I have a password which I save on the Settings.settings file
and since it is a password, I need to encrypt it.
What are my possibilities, and how can I accomplish such a task?
Is it possible to encrypt a string, and how do you decrypt it?
You could encrypt the password, but your code will need to have the decryption key built in. So it's not very secure. Anyone disassembling your code would have one extra step to take before they'd have the password.
You're likely better off using an AD service account, or some other security mechanism designed for this purpose. Security is hard; don't roll your own unless you absolutely have to!
Option 1: You can protect use SectionInformation.ProtectSection to encrypt it, or if it's an ASP.NET app you can use aspnet_regiis to encrypt it, iirc aspnet_regiis uses ProtectSection under the covers so in theory you could use this in command line if you wanted on a regular app. Can be done like below, to clear up all the cluttter from msdn article
// you will need to add ref to System.Configuration
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Get the section.
UrlsSection section = (UrlsSection)config.GetSection("MyUrls");
// Protect (encrypt)the section.
section.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider");
config.Save(ConfigurationSaveMode.Full);
Option 2: Write up your own encryption decryption mechanism, check out System.Security.Cryptography to learn how to do this
Option 3: Use ProtectData (from System.Security.Cryptography) class to encrypt using user specific or machine specific encryption. This is simple, something like this will do.
byte[] aditionalEntropy = {9, 8, 7, 6, 5};
byte[] secret = {0, 1, 2, 3, 4, 1, 2, 3, 4};
byte[] protectedBytes = ProtectedData.Protect(secret, aditionalEntropy, DataProtectionScope.CurrentUser);
byte[] originalSecret = ProtectedData.Unprotect(protectedBytes, aditionalEntropy, DataProtectionScope.CurrentUser);
Note that method #1 encrypts using the machine key, and therefore can only be read back on the machine it was encrypted thus can be read back by any user running your app on the same machine. Method #3 is based on the user key (and specific to the machine iirc) so is the most restrictive. If you want to encrypt in one machine and make it readable across different machines, you'll need to go with option 2
First thing I'd ask ask - do you need to have an admin password in your application? If the answer is yes then it depends what you want to do. If you need to use the password for something then you can use aspnet_regiis to encrypt sections of your config file and be able to recover them again.
http://msdn.microsoft.com/en-us/library/k6h9cz8h(v=vs.80).aspx
If the password is never going to be used, i.e. you are just expecting someone to login as the administrator and you want to check the password is correct then the best method to use is salting, which is basically a one-way encryption meaning that no one can recover your password. When you come to authenticate you simply repeat the process and validate the results against your salted password
http://en.wikipedia.org/wiki/Salt_(cryptography)
http://www.symantec.com/connect/blogs/would-you-care-some-salt-your-password
Hash and salt passwords in C#

How do I safely store database login and password in a C# application?

I have a C# application that needs to connect to an SQL database to send some data from time to time. How can I safely store the username and password used for this job?
There is a nice MSDN article about how to secure connection strings in .Net.
You might want to use protected configuration.
Use integrated Windows authentication whenever possible. It takes the onus off of your application and lets Windows handle it. Using Windows authentication instead of SQL authentication is considered a best practice.
Read this accepted answer: the best way to connect sql server (Windows authentication vs SQL Server authentication) for asp.net app
See also: http://www.mssqltips.com/sqlservertip/1831/using-windows-groups-for-sql-server-logins-as-a-best-practice/
And: http://www.greensql.com/content/sql-server-security-best-practices
Incidentally, if this is a "job" as implied by the question, it may be a great candidate for a simple Windows service or scheduled task, both of which can run in a specific security context (i.e. as a specific Windows user).
in your app.config or web.config and then you encrypt them using the .net encryption provider
for more info check here
http://msdn.microsoft.com/en-us/library/dx0f3cf2%28v=vs.80%29.aspx
Encrypting Configuration Information Using Protected Configuration
http://msdn.microsoft.com/en-us/library/53tyfkaw%28v=vs.80%29.aspx
You may want to look at the RijndaelManaged key, which is quite a secure symmetric encryption key. A good article on this information (and tutorial) can be found here;
http://www.obviex.com/samples/Encryption.aspx
Not sure about your exact requirements, but first and foremost, you have to encrypt the password.
Also, when transmitting such sensitive information, consider using a secured connection.
Store an encrypted version in your connection string and form the connection string programmatically after decrypting the password.
You could use any encryption mechanism of your choice - from trivial to complex.
you can use encryption and dyscryption algorithm for passwords and log your user information by who created user and what datetime it created and save this in database.
and even if someone update or edit log that information in database.
Code to Convert stirng into md5
using System.Text;
using System.Security.Cryptography;
public static string ConvertStringtoMD5(string strword)
{
MD5 md5 = MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(strword);
byte[] hash = md5.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("x2"));
}
return sb.ToString();
}

hide password in string

I am making a custom ftp client that logs onto a single ftp site and goes to a specific folder to avoid users' putting files in the wrong place.
I'm not super concerned about it, but the password is just a string to initiate the new ftp object.
FtpClient ftp = new FtpClient("www.markonsolutions.com", "user", "password");
What is the best way to keep this password from prying eyes?
FTP supports only plain text authentication - if you want to hide the password from attackers you have to use FTPS (FTP over SSL).
UPDATE
Don't care about hiding and obfuscating the password in your source code as a first step - your application will have to decrypt it and send it over the wire in plain text. Everyone can just start WireShark or any other packet sniffer and get the password back in plain text. First make sure that you don't send the password in plain text over a network, then start thinking about obfuscating it in your code.
UPDATE
Obfuscating the password in your code yields no security at all while you are sending it in plain text, but you can do so. Just encrypting the string adds one level of indirection. Without obfuscation I have to finde the password in your application and that's a matter of minutes with Reflector, with obfuscation I have to find the key, the encrypted password, and the encryption method. This will probably still take only minutes.
Using an obfuscator to prevent me from decompiling you application (into readable code) might stop me for a few hours until I find the relevant call into a system library function (but I wouldn't try, but only read the password from the wire ;).
So I suggest not to try to hard to obfuscate the password - the average user is probably unable to find a plain text password in a executable and people willing to find the password cannot be stopped by obfuscation. In this case the only way would be not to include the password in your application in the first place.
You can use this to protect your plain text string from reflector like programs.
See this SO post about how to encrypt and decrypt a string, in this case your password.
You should also consider obfuscating your code to make it difficult for people with appropriate tools to get the password by debugging your code.
Make your passwords and connection URLs configuration parameters, in a protected file. I uses INI files, and they are placed in a directory that is protected by the web server such that a browser can't open nor see the file/directory.

Ways around putting a password in code

I have a bit of code that needs to run with elevated privileges (more that I want the rest of my code running at).
I have my code that sets up the Impersonation working, but it requires a username, domain and password. As my code is in C#.net I know that the password can be found by anyone determined enough.
Is there a way to encrypt the password in my code? Or otherwise secure this password and still be able to pass it in?
Here is the code I am calling:
using (new Impersonator("UserNameGoesHere", "DomainNameGoesGere", "Password Goes Here"))
{
uint output;
NetUserAdd(AUTHENTICATION_SERVER, 1, ref userinfo, out output);
return output;
}
I would love an example that shows how to fix this to not show my password in plain text.
I am using Visual Studio 2008, .NET 3.5 SP1, and running on Windows Server 2003.
Vaccano,
I would recommend investigating the data protection API (DPAPI) for what you're attempting to achieve. It is considered part of the solution in many best practice approaches to reversibly storing passwords needed by applications.
A good article discussing the DPAPI (and other techniques + concerns) can be found here:
http://msdn.microsoft.com/en-us/magazine/cc164054.aspx
With C# 2.0, P/Invoking isn't even required; managed wrappers exist:
http://blogs.freshlogicstudios.com/Posts/View.aspx?Id=41ca5a99-ddc0-4d0a-9919-2ce10bf50c7e
I hope this helps!
You have multiple options here.
You can hash the password the very first time and store the hash to a file. Now the next time, you want to execute the code with elevated privileges, you need to accept/retype the password and re-compute the hash and match it with the stored hash. Only if it matches will you execute your code in elevation modes. You could hash using SHA. Please look at System.Crytography namespace for examples on hashing.
Second option is to encrypt the password using algorithms like AES. However you will need to have a key to do this and you will have to worry about securing this key.
Third option is to use DPAPI and encrypt the password but not worry about securing the keys - much easier option than 2.
I would recommend 1 if you do not mind re-entering the password every time the application starts. If that is not a possibility, I would suggest going with 3 and use DPAPI.
Here are some links to get you started.
1.http://www.obviex.com/samples/dpapi.aspx
2. http://www.obviex.com/samples/Encryption.aspx
You can use safe-config nuget package. Internally it uses data protection api to encrypt and decrypt data.
//Save some configuration data at folder data\temp\
var configManager = new ConfigManager()
.WithOptions(DataProtectionScope.CurrentUser)
.Set("password", "my-massword")
.AtFolder(#"data\temp\")
.Save();
...
//Load configuration data
var loadedValue = new ConfigManager()
.AtFolder(#"data\temp\")
.Load()
.Get<string>("password");

How to check password before decrypting data

I am creating a program that needs to store the user's data in encrypted form. The user enters a password before encryption and is required to supply the password again to retrieve the data. Decryption takes a while if there is a lot of data.
Now, I want to check that the user has entered the correct password before doing the decryption. This check needs to be fast, and the decryption process is not.
How can I check the password before actually completing the decryption process ? I thought about storing a hash of the password as the first few bytes of an encrypted file - this would be easy and fast enough - but I am not sure whether it compromises security ?
I am using .NET and the built in cryptography classes.
Well, a cryptographic hash shouldn't compromise security as long as it is salted and has reasonable complexity; personally, though, I'd probably try to set it up so that data corruption (due to incorrect password) is obvious early on...
Any possibility of injecting checksums in the data at regular intervals? Or if the stream represents records, can you read it with an iterator (IEnumerable<T> etc) so that it reads lazily and breaks early?
(edit) Also - forcing it to decrypt a non-trivial chunk of data (but not the entire stream) before it can tell if the password was right should be enough to make it hard to brute-force. If it only has to work with the first 128 bytes (or whatever) that might be fast enough to make it worth-while trying (dictionary etc). But for regular usage (one try, password either right or wrong) it should have no performance impact.
I suppose you are using the password as a salt for the encryption/decryption process. The simplest approach would be to encrypt some standard phrase or may be the password that user provided as the input string with the same password as salt for the encryption process. When the user wants to decrypt the data take that password as salt for your decyption process and use ot to decrypt the encrypted password. If you get the password back then the user has provided the correct password and you can continue the decryption process otherwise notify the user that his password is incorrect.
The process would be:
User gived PASSWORD and DATA for enryption.
You encrypt the PASSWORD with PASSWORD as the salt. and store it as ENCRYPTED_PASSWORD.
Encrypt the DATA with PASSWORD and store it.
The user comes back gives you the PASSWORD.
You decrypt ENCRYPTED_PASSWORD with PASSWORD as salt.
If the result is equal to PASSWORD you decrypt the DATA otherwise you notify the user.

Categories