Is app.config file a secure place to store passwords? - c#

I need to store confidential passwords within the code. I cannot use Hashing techniques as the password itself is needed. How can I store these data securely within an app.config file?
Are there other ways I could accomplish this securely?
DPAPI and ProtectData Class is not an option because the keys are system specific eg:connection strings can't be stored this way for different end user systems.

You can use DPAPI (Data protection API) to encrypt certain section of your config files. Your code would still be using ConfigurationManager and decrypting will be taken of care by the framework. For more information on the same refer to this patterns and practices document How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI
Update
To encrypt or decrypt information from your code you could use ProtectedData.Protect & ProtectedData.Unprotect. This can be run as a part of custom action in your installer or when the user enters the credentials when using your application.
Sample Code
class SecureStringManager
{
readonly Encoding _encoding = Encoding.Unicode;
public string Unprotect(string encryptedString)
{
byte[] protectedData = Convert.FromBase64String(encryptedString);
byte[] unprotectedData = ProtectedData.Unprotect(protectedData,
null, DataProtectionScope.CurrentUser);
return _encoding.GetString(unprotectedData);
}
public string Protect(string unprotectedString)
{
byte[] unprotectedData = _encoding.GetBytes(unprotectedString);
byte[] protectedData = ProtectedData.Protect(unprotectedData,
null, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(protectedData);
}
}

Related

How to work with (and create) X509 Certificates for private/public key encryption of JWT Tokens

I am trying to figure out a way of authentication between two distributed services.
I don't want to have a shared secret distributed on every service host, because it would mean that once one host has been compromised, all hosts are compromised.
So my scenario is:
Host A knows the public key of Host B
Host A encodes and encryptes the jwt using Host B´s public key
Host B receives and decrypts the jwt using its private key, that it only knows itself.
The jose-jwt package:
https://github.com/dvsekhvalnov/jose-jwt
seems like a good option to me. Beside the signing of the jwt, it also supports encryption using private/public keys.
On the page there are the following examples for encoding and decoding a jwt:
Encode:
var publicKey=new X509Certificate2("my-key.p12", "password").PublicKey.Key as RSACryptoServiceProvider;
string token = Jose.JWT.Encode(payload, publicKey, JweAlgorithm.RSA_OAEP, JweEncryption.A256GCM);
Decode:
var privateKey=new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet).PrivateKey as RSACryptoServiceProvider;
string json = Jose.JWT.Decode(token,privateKey);
Now, here is what i don´t understand:
How can I create a .p12 certificate file that only contains the public key information (for the host/service A that encodes the jwt) ?
.. and how can I create a .p12 certificate file that contains both, the public and the private key information (for the host/service B that decodes the jwt) ?
From all the research that I have done, i get the impression that you can either only make a .p12 file that contains both, or one that contains only the public key. But it seems there is no way to create two .p12 files, one with both information and one with only the public key. What am I missing?
Thanks for your answers.
Normally a PKCS12/PFX is not used for public-only, but you can do it if you like.
Assuming that cert.HasPrivateKey is true: cert.Export(X509ContentType.Pkcs12, somePassword) will produce a byte[] that you can write to "publicAndPrivate.p12" (or whatever).
Normally for a public-only certificate you'll write it down just as the X.509 data, either DER-binary or PEM-DER encoded. .NET doesn't make PEM-DER easy, so we'll stick with DER-binary. You can get that data by either cert.RawData, or cert.Export(X509ContentType.Cert) (both will produce identical results, since this export form has no random data in it). (publicOnly.cer)
If you really want a PKCS12 blob which has just the public certificate:
using (X509Certificate2 publicOnly = new X509Certificate2(publicPrivate.RawData))
{
return publicOnly.Export(X509ContentType.Pkcs12, somePassword);
}
The resulting byte[] could then be publicOnly.p12.

Encrypt passwords existing in Database sql windowsForms

I have a database of logins and passwords. I wouldn't like that anyone who has access to the database can see everybody's password. How can I encrypt the passwords in the database?
In other words, I want the fields pwd (password) to be encrypted in the database but it is automatically decrypted when I enter it in the LoginForm.
I have found a method that encrypt the strings input but it doesn't solve my issue.
static string Encrypt(string value)
{
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
UTF8Encoding utf8 = new UTF8Encoding();
byte[] data = md5.ComputeHash(utf8.GetBytes(value));
return Convert.ToBase64String(data);
}
}
private void BtnEncrypt_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtPass.text))
{
MessageBox.Show("Please enter your password !");
}
texResult.Text=Encrypt(txtPass.Text);
}
Please, can somebody help me.
Thanks in advance.
You can Encrypt your password using your Encrypt function and store the Encrypted password in your database.
But Decrypting the password, is not a good option. Password Encryption should be one way.
To check whether the password is available in your database, you can Encrypt the password entered by user by using the same Encrypt function, then match that Encrypted password to encrypted password you have in your database.
Thanks
It is easy to muddle encryption with hashing. What you are asking about is encryption - encryption lets you turn your password into an apparently random sequence of characters which can then be decrypted to get the original password back. What you should be using (and some have suggested) is hashing.
There are lots of examples of how to do encryption/decryption on the net, just search. This is the first one that came up for me: http://www.codeproject.com/Articles/14150/Encrypt-and-Decrypt-Data-with-C Tempting as it is to copy and paste the code from there, I won't because this isn't what you should be doing. For storing user passwords in a database it is much better to use password hashing (with salt) than to store encrypted passwords. Why? because then if your system is hacked it is impossible for an attacker to recover people's passwords - all your accounts might still be compromised but given that people often use the same password for more than one system you won't be compromising your users.
A hash is a one way function, so you can't get the original password back. When someone wants to login you simply generate a hash and then compare it with the one you have stored in the database. If you want to read more about this and why you should be using it then this is a good start: https://crackstation.net/hashing-security.htm If you would like to jump in and get some working code then have a look at Hash and salt passwords in C#.
You can use any complex cryptography technique to encrypt a password and send the password key to be saved in database for corresponding user.
Now when the client tries to login and enters password, sends it to server.
From the server you can again convert the login details and compute the hash and finally send to a stored procedure to compare. If the two strings match, you return true else false as for authentication.
using System.Security.Cryptography;
...
...
...
private const string _alg = "HmacSHA256";
private const string _salt = "rz8LuOtFBXphj9WQfvFh"; // Generated at https://www.random.org/strings
public static string GenerateToken(string username, string password)
{
string hash = string.Join(":", new string[] { username, password });
using (HMAC hmac = HMACSHA256.Create(_alg))
{
hmac.Key = Encoding.UTF8.GetBytes(GetHashedPassword(password));
hmac.ComputeHash(Encoding.UTF8.GetBytes(hash));
hash = Convert.ToBase64String(hmac.Hash);
}
return Convert.ToBase64String(Encoding.UTF8.GetBytes(hash));
}
public static string GetHashedPassword(string password)
{
string key = string.Join(":", new string[] { password, _salt });
using (HMAC hmac = HMACSHA256.Create(_alg))
{
// Hash the key.
hmac.Key = Encoding.UTF8.GetBytes(_salt);
hmac.ComputeHash(Encoding.UTF8.GetBytes(key));
return Convert.ToBase64String(hmac.Hash);
}
}
MD5 is not secure anymore.
When a user register to use your application, hash the password with SHA512 bit with salt. You can find like PWDTK nuget package which we can easily use. Password is what we don't need to know what it means but just plays a secure role. Like some person commented above, when the user try to log-in after user registration, just encrypt the user's input(password) and compare it with that registered in SQL database. Password must be one-way.
After the login result comes up success or fail, the role of password is finished.
As of Winform cases, you need to deeply consider to secure the connectionstring to connect to SQL database. One possible option might be WCF middleware between Winform application and SQL database.
And for last but very importantly, you must use SSL for secure communication.
It seems you might consider these at later stages.

How to store information like passwords encrypted but not in hash

I need to store "password like information" in a database field. I would like it to be encrypted but I need to decrypt it before using it. So I can not use a Hash/Salt solution.
Granted if an attacker made it that far into the database it may be too far gone but I figure this would at least stop the mistaken dump of the data.
How to encrypt a value store it into the database and decrypt the same value for use later?
Hashing is not an option (I use it on other parts actually).
Where to store the private key? Users would not supply anything.
This a C# solution so .NET specific stuff would be great. My question is very similar but I am looking for a .net based solution: Two-way encryption: I need to store passwords that can be retrieved
EDIT:
Hogan pretty much answered my question. I found examples out there and they ranged from very complicated to rather simple. It looks like AES is still good so I will be using that method. thank you for all your help.
One solution that does not involve private keys is using DPAPI.
You can use it from .NET via the ProtectedData class.
Here is an example:
public void Test()
{
var password = "somepassword";
var encrypted_password = EncryptPassword(password);
var decrypted_password = DecryptPassword(encrypted_password);
}
public string EncryptPassword(string password)
{
var data = Encoding.UTF8.GetBytes(password);
var encrypted_data = ProtectedData.Protect(data, null, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encrypted_data);
}
public string DecryptPassword(string encrypted_password)
{
var encrypted_data = Convert.FromBase64String(encrypted_password);
var data = ProtectedData.Unprotect(encrypted_data, null, DataProtectionScope.CurrentUser);
return Encoding.UTF8.GetString(data);
}
Please note that DPAPI in this case depends on the current logged in user account. If you encrypt the password when your application is running as User1, then you can only decrypt the password running under the same user account. Please note that if you change the windows password for User1 in an incorrect way, then you will lose the ability to decrypt the password. See this question for details.
If you don't want use DPAPI, and prefer to have a private key. Then the best place to store such private key is in the user's key store. However, in order to store a private key in the local user store, you need to have a certificate for it. You can create a self signed certificate and store it with its corresponding private key into the local user certificate store.
You can access the user store in code using the X509Store class. You can use it to find the certificate (which is in C# a X509Certificate2 class) that you want to use and then use it to do encryption/decryption.
See this and this for more details.

Ruby on Rails Devise encrypted password read from C# .NET

We have a Ruby on Rails app that uses the Devise gem for user handling, including creating and authenticating user passwords. The passwords are encrypted in the MySQL database obviously. We are using Devise defaults for how it encrypts the password. Now we have another small same-LAN side app that (a C# ASP.NET app) needs to authenticate with a user/password directly with the database to do some read-only operations.
How can we best mimic what Devise does for user/password authentication in the C# ASP.NET app against the very same data in the MySQL database?
Essentially, I need to figure out how to recreate Devise's valid_password? method in C# .NET
http://www.rubydoc.info/github/plataformatec/devise/Devise/Models/DatabaseAuthenticatable#valid_password%3F-instance_method
# File 'lib/devise/models/database_authenticatable.rb', line 46
def valid_password?(password)
return false if encrypted_password.blank?
bcrypt = ::BCrypt::Password.new(encrypted_password)
password = ::BCrypt::Engine.hash_secret("#{password}#{self.class.pepper}", bcrypt.salt)
Devise.secure_compare(password, encrypted_password)
end
I think I understand the question correctly. What you want to do is authenticate a user on you .NET application using the credentials on your rails application. If so, I would suggest implementing an oauth server on the ruby side and a client in you .NET code. As for the server you have several gems that provide this functionality including
oauth-ruby
doorkeeper
oauth2-provider
Devise uses BCrypt for password storage, and so thankfully the verification process is fairly simple. Install the BCrypt.Net NuGet package (or any other BCrypt implementation), and then do this:
public static bool ValidPassword(string userSuppliedPassword, string hashedAndSaltedPassFromDatabase)
{
return BCrypt.Net.BCrypt.Verify(userSuppliedPassword, hashedAndSaltedPassFromDatabase);
}
I was having a similar requirement of verifying already existing users from the C# application.
I used package bcrypt.net - next for BCrypt.
Here is the code snippet which I used
static void Main(string[] args)
{
const string DEVISE_PEPPER = "Here comes the devise pepper value";
// One pass
string pass = "reE8TuLcZ44XwRz";
const string passHash = "$2a$10$1Rm.BC0hnF1laC7MFJ/B0eFu2rtG1Asy6fRqJVdqcfBO6LASn4Nqa";
// Second pass
const string secondPass = "FpRfaaqzNNRAum9";
const string secondPassHash = "$2a$10$/Ex4x9LkvxIncaXhByqVP.YRdwRlZFJ7p4H96BfqHk1oGmw3YwLMC";
// How Ruby BCyrpt verify? Ref - https://www.freecodecamp.org/news/how-does-devise-keep-your-passwords-safe-d367f6e816eb/
// 1. Fetch the input password
// 2. Fetch the salt of the stored password
// 3. Generate the hash from the password and salt using the same bcrypt version and cost factor
// 4. Check if the stored hash is the same one as the computed on step 3
// Ref - https://github.com/heartcombo/devise/blob/5d5636f03ac19e8188d99c044d4b5e90124313af/lib/devise/encryptor.rb#L14
var finalPass = $"{secondPass}{DEVISE_PEPPER}";
var verified = BCrypt.Net.BCrypt.Verify(finalPass, secondPassHash);
var verifiedTxt = verified ? "verified!" : "didn't verified.";
Console.WriteLine($"Password and hash {verifiedTxt}");
Console.ReadKey();
}
I was successfully able to verify the password.

Decrypting forms authentication token (AES, SHA1) in node js

Has anyone had luck decrypting a .NET forms authentication generated cookie in node js using the crypto library?
I'm using AES for encryption and SHA1 for validation in .NET forms authentication mechanism.
I was wondering if someone had this problem before and solved it?
I played with this and made the following code for Node.js:
var crypto = require('crypto');
var iconv = require('iconv-lite');
function hash(password) {
// your validation key from web.config + 00 at the end
var buf = new Buffer('...00', 'hex');
var hmac = crypto.createHmac('sha1', buf);
// convert password from utf8 to UTF16
var pass = iconv.encode(password, 'utf16le');
hmac.update(pass);
return hmac.digest('base64');
}
console.log(hash('test'));
Use it to compare hashes from your database.
It depends on web.config settings.
You can see the source code of Encryp and Decrypt here with all the different possibilities (Framework20SP1, Framework20SP2, etc)
https://github.com/Microsoft/referencesource/blob/master/System.Web/Security/FormsAuthentication.cs
For example, on Framework20SP1 the cookie looks like: Enc(IV+SerializedTicket+Modifier)+HMAC(Enc(IV+SerializedTicket+Modifier))

Categories

Resources