Using BCrypt.Net to simulate Devise Password Encryption? - c#

I am trying to a pretty simple task here. I have a server that I am running which has a MySQL instance running on it, which my rails app uses to populate. Unfortunately for me I used devise to do all my user management and now am a little stuck.
So I have a C# application that I am writing. I want to simply verify the user and password through the MySQL database that I have already in place.
Right now here is what I know (or think I know):
Devise uses Bycrypt to do a one way encryption on their passwords which are then stored in the database. The problem is that I am not sure how to implement bycrypt properly to produce the proper encrypted passwords to validate.
Here is my current process for generating my hashed password:
string pass = password.Text;
string mySalt = BCrypt.Net.BCrypt.GenerateSalt();
string myHash = BCrypt.Net.BCrypt.HashPassword(pass, mySalt);
I think that this must be really wrong. I just don't quite know what I am missing here or what I am doing wrong. I will keep googling around and if I come up with an answer I will post back. Also if I broke any editting rules or something just let me know so I can fix them right quick.
Thanks in advance for your time :)

I think your problem is your generating the Salt each time you are hashing the password to verify against the database. You need to use the same Salt value that was used when the password was initially generated.

Alright so my question was actually pretty silly but for anyone else with the same logical fallacy as me I'll explain.
By default Devise does it's encryption using BCrypt, which is typically done with Blowfish, when they do this they always use BCrypts generate salt function which produces a random salt for each hashing of the password.
Because of the random salt BCrypt includes a utility function called Verify(password, hashed_pass). This function allows the testing of a non encrypted password and hashed pass to be compared. Nifty and very useful

Related

C# Decrypted Values and Public Class Properties...What is the risk?

(If this is a duplicate post, please point me to the original or tell me what to search for. I could not find anything. Thank you!)
So, I have an encrypted value saved in a database row. I want to retrieve the column values for the database row and store them in a class instance. Is it safe to create a public property on the class for the DECRYPTED value?
public class *DataRow*
{
public string *DataElement* { get; set; }
public string *Value_Decrypted* { get; set; }
}
Can an external process somehow access the public property? Do I need to use SecureString (or something else) to protect against memory hacks? Does .NET's DataProtection help with any of this?
Is there a practical guide/walkthrough somewhere for how to handle this (hopefully without too much coding overhead)?
These feel like pretty basic questions (ashamed), and I have heard talk about these concerns, but in my searching I could not find anything. Wasn't sure what to search for (other than what's in the Title of this post).
As always, any direction will be greatly appreciated.
Thank you!
EDIT:
Thank you everyone for the responses. Password was a BAD example--I understand it is ill advised and usually unnecessary to decrypt a password. I guess my question is more general, relative to how to handle data that does need to be decrypted. I have updated my example to reference an encrypted/decrypted value instead of a password.
I am writing a generic monitor program and need to save access values, paths and commands in a database. I feel it's best to encrypt these values in an effort to minimize exposure of our infrastructure, etc.
The consensus seems to be that saving the decrypted value in any form, property or otherwise, is a bad idea.
I am now thinking that I will store only the encrypted value and then decrypt it, using a SecureString, every time I need it.
Thank you all again!!
Usually password decryption is not necessary. If you let users pick their own passwords it is even unethical.
Having said that:
You should use a one way encryption. Otherwise a SecureString. Consider all public and private members unsafe in this context.
For the one way encryption,some basics: Encrypt password. Store it in database. If you want to check the password, encrypt the inputted data and check if it matches the encrypted value in the database. The encryption is usually seeded with a random salt value.
Check this link for encryption with salt:
https://stackoverflow.com/a/2138588/2416958
The best practice is that you use a One Way encyption method to scramble the password. This prevents the original data from being exposed to any third party and can be only verified by the owner of the password.
No matter what modifier you use for your password filed (private, protected), that value can still be stolen.
Just like Stefan says, it's never a good idea to decrypt the password and store the decrypted version anywhere for any period of time. It's unsafe and at times unethical. You shouldn't even be able to decrypt your users' passwords. Once the user keys in their password, that should be the last time said password is seen in it's decrypted form.
You don't want the encrypted password to be sent back from the server across the network either as an attacker may find a pattern and find out your encryption method which is again not desirable. That's why whenever a user tries to log in, you get their attempt and encrypt it internally and check it against the encrypted version.
Public/Private access modifiers to class's fields were never intended for security purposes. They are there for encapsulation and data hiding for design purposes(as an example a private field can always be accessed through reflection).

C#: Best practice for obfuscating password in text file?

Firefox has to store passwords. That is totally unsafe, but it has to do it, that's all.
My C# app has the same requirement (it is a kind of browser).
Rather than storing passwords in plaintext, Firefox obfuscates them a bit.
What is the best practice for this kind of obfuscation?
For instance, here is Firefox's strategy, if I understand well:
Create a salt for the app's user
For each password, use the salt in a symmetric transformation when storing/retrieving
Store the passwords file in a directory named after the salt.
Is my understanding correct?
Is there any better strategy, or even a C# library for this?
Similar questions for other programming languages have unsatisfying answers, they don't not go as far as Firefox, just suggesting rot13 or base64, which makes it easy for automated malware to identify obfuscated passwords in unknown software. (just searching for the base64 value of common passwords)
Once again: it will not resist to any attacker, I know. But if Firefox cares I should too.
You should use the ProtectedData class to encrypt the passwords.
You can specify DataProtectionScope.CurrentUser to encrypt data using the current user's Windows login password, so that no other user can decrypt it (this also works if the user has no password)
It would probably be easiest to use an encryption rather than obfuscating. Obfuscating code generally makes it harder for someone to identify what is what in code if they viewed the source. If you don't encrypt the information however, people can still figure it out.
My advice would be is to use AES-256 or Tripple DES-128 Encryption.
Easily, you could have the passwords stored in a text file and then encrypted. Only then through your browsers can the file be decrypted.

C# - Storing user password for comparison

I am storing user logon encrypted passwords in a database (SQL Server). Because of an API restriction, the passwords need to be encrypted on the C# end of things, so I can't use the database's built-in encryption. what is the fastest/easiest way to encrypt these passwords so I can compare them to what the user would have typed in to a third-party service later?
I am new to C# and I understand that passwords should never be in plain text so that's why I want to make sure I have the highest security. I have tried using the RSA.EncryptValue() function but I'm pretty lost as to how to use it correctly.
Any help is appreciated - thanks in advance.
-Jimmy
You don't want to encrypt and store passwords. You want to generate a hash and store that. Then, when a user is logging in, you regenerate the hash and compare it to the one stored in the database.
The answers to this question provide examples of how one might hash a password in c# (one answer includes information on doing a "salted" hash).
Firstly dont encrypt; hash.
Secondly dont encrypt; hash.
A password should never be recoverable.
I'd advise reading...
http://www.troyhunt.com/2010/05/owasp-top-10-for-net-developers-part-1.html
front to back.
You should salt your passwords and hash using a decent hashing algorithm; take SHA512 for the low end, or if your serious about protecting that data look at something more along the lines of BCrypt http://code.google.com/p/bcryptnet/
The point in hashing rather than encrypting isn't to secure your site against brute force attacks, but more importantly, is to secure your users against data loss.
i.e.
http://www.bbc.co.uk/news/technology-11998648 - Gawker
https://www.google.co.uk/search?sourceid=chrome&ie=UTF-8&q=sony+hacked
People put allot of trust in the hands of web developers taking care of their, often pathetic, passwords. Taking good care of them can make a hell of a lot of difference.
With BCrypt you set a workfactor to the salting; I would also add a database salt (see the troy hunt membership provider article on how MSFT does it) to increase the original password value.
Example from the BCrypt site (BCrypt.net is also a NUGET package)
// Pass a logRounds parameter to GenerateSalt to explicitly specify the
// amount of resources required to check the password. The work factor
// increases exponentially, so each increment is twice as much work. If
// omitted, a default of 10 is used.
string hashed = BCrypt.HashPassword(password);
// Check the password.
bool matches = BCrypt.CheckPassword(candidate, hashed);
Hope thats been of use.
You can of course use the built in forms authentication encryption system to encrypt/decrypt your data. Though it's somewhere between daft and dangerous to encrypt passwords.
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.encrypt.aspx
http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.decrypt.aspx
You'd also need to add a machineKey tag to your web config, microsoft provides a generator for this; http://aspnetresources.com/tools/machineKey The tool creates a 256-bit decryption key and a 512-bit validation key, with Rijndael as the data validation algorithm.
And if you DO NEED (as in you'll be shot if you don't) to start throwing plaintext passwords around, for all that is holy, check the service is restricting by IP (IPSec) and please, dear god, use SSL.
Like Steve Wellens mentioned generate a hash.
Hope this gives some insight on the different ones available

Beginner Encryption, "Master Password" Question

I'm writing a program that, using Rijndael, will encrypt and decrypt files/folders using a user chosen password. Currently, when the user wants to encrypt something, they have to enter a password, that password is used to encrypt and when the user is ready to, decrypt the file/folder.
However, I would like to have a "master password" that will allow the user to only enter the password once in a "preferences" portion of the program, and then the program will automatically use that password for all encryption/decryption. This way they don't have to put in a password every time they want to encrypt/decrypt.
Now, since programs like this are prone to many different kinds of attacks, how do I safely store the user's "master password" so someone couldn't get a hold of it? Storing it in the program in plain text is obviously not a good idea, so I could encrypt/decrypt the password with another password, chosen by me, and stored in the program.
However, again, if someone gets access to the password chosen by me to encrypt/decrypt the master password, then they could decrypt the master password and again, that wouldn't be good.
SO! How do programs safely do this?
Currently I'm saving the "master password" by encrypting it using my own, chosen password, and storing it in a User-scoped setting. If you think this isn't a good idea, please tell me why and what would you change about the process I currently have implemented?
Thank you!
Review this:
http://www.redkestrel.co.uk/Articles/StoringSecrets.html
It's a great article on your options.
That said, I think your use case is already pretty well natively covered by windows itself through EFS....
http://technet.microsoft.com/en-us/library/cc700811.aspx
Just wanted to add one thing:
It is fundamentally impossible to protect a "secret" from those who have physical access to the machine. This has been proven time and again even for hard drives that support native encryption schemes.
All you can do is make it somewhat difficult for those that have no idea what they are doing.
The fundamental problem is that something has to have access to the decryption key. Whether it's the BIOS of the machine, Firmware of the Harddrive, or even if it's stored in some folder hidden through DPAPI. Which means the only effective way is to force the user to supply the necessary credentials when it's time to encrypt / decrypt the files.
If those credentials are sufficiently short then it's possible to use brute force to get to them. Right now the recommendation is to use minimum key lengths of 128 bits or greater. Of course, if you are limited to use common letters then the number of bits to test goes down dramatically. And if you allow values such as those found in hacking dictionaries then the time to crack goes down further.
Another wrinkle are keyloggers. If one's installed (and they can be hidden from most users) then all an attacker has to do is wait for the user to type their decryption password in and forward that to an interested party.
Heck, for the truly paranoid, there are devices that can detect what you typed based solely on the sound your keyboard makes as you type. For others, RAM maintains state for a certain period of time even after the machine has been shut off...
So, what does all this mean? First, you have to ask them to provide the credentials on each encrypt / decrypt request. Second, they have to be sure that no keyloggers are installed. Third, the credentials can't be something easily remembered. Fourth, the computer cannot be in a physically accessible location. Fifth, even the keyboard has to be secured...
All of which adds up to a situation that says if its on a computer, someone else can get it.
Do you know why websites won't tell you your password when you lost it and they ask for a new one?
Because they don't know it. Yes, they don't know it. They hash it and hash it good so they can only check your input password's hash against the one in the database.
Why all that?
Because they cannot store it safely.
They cannot encrypt it safely.
This is a similar case.
The best way is not to use a master password.
When you encrypt a file, ask for a password and encrypt with the hash of the password.
When decrypting, do ask for a password and attempt to decrypt.
If it fails then it's wrong.
If it's okay then it's the right one.
You can add some (shorter) dummy data before the file's contents that you can use to check the key.
If you try to use that to store the master password, you will enter an infinite loop of security, which is not a good idea.
You'll encrypt the password, and then encrypt the key used and then encrypt the key used to encrypt the first key etc.
Edit: I am sorry about the discouraging nature of this answer but what you need to do is truly impossible.
Consider storing you master password in memory using the SecureString Class.
I'll be frank about this. Leave security to security experts. Security is not easy, and is very very hard to get right even for people who are supposedly experts in the area.
If you really have to store sensitive data that your users are expecting to be secure then asking in SO on how to do it is definitely NOT a good sign and not the way to go. You should seek professional guidance or consider using well tested implementations available in the market or in Windows itself.
Don't persist the user's password, take a hash and be sure to salt it. Use the hash to encrypt and decrypt the files. Beware if the user forgets their password you will not be able to recover it for them however you could still decrypt the files for them. This also means your app would be vulnerable to somebody hacking/patching it to get it to decrypt files without providing the password.
If the encryption method is standard, documented, obvious and/or well-known then to prevent hackers from just reading the hash and using it to decrypt the files themselves you could do this: use the stored hash along with some other info to generate a new hash that you then use to encrypt/decrypt the files and never persist. The other info could be made up of the size of the file, the created date, etc. Hackers could use this info but they would have to hack/reverse engineer your app before they know they need it. Technically it's security through obscurity since those keys are hidden in plain view.

How to create a secure Access to a RestAPI of a (WPF)-Application

I'm trying to create an application (in c# WPF) which should communicate with a RESTApi.
I want to create the RESTApi by myself.
So at the moment I'm trying to figure out what's the best way to let the user of my c# application, logon to the RESTApi so he can receive data of the database.
My first thought was Basic Authentication. After some research I realized that i really don't want to pass a password in plaintext (Even if I use SSL).
I'm aware of the importance of salts and I know the best way would be, to use Hash methods which already provides random salts.
But in my specific case I thought about saving a hash in my database with a specific salt using the blowfish algorithm.
Next I would implement a logic which will provide a combination of a salt, like
a combination of username, some pepper,salt and the actual hashed password. Maybe even a sequence which i could build into this logic. Which would be hard to implement if I want to use the Application on different computers, because I have to remember the last sequence.
Anyways, both the RESTApi and my WPF-application would know this logic to create a hash which would be different each time I call the logic (due to the sequence).
So i could match the outcome every time I use the logic.
Basically I did some research about Hashing algorithms. I found BCrypt for both C# and PHP. I already achieved to create Hashs of a password which the user will type in my WPF application. On the other side i used crypt() on my website to create a blowfish hash. Both matched perfectly (using the same salt).
My thoughts were: How can I pass a hashed password to my RESTApi without storing/pass passwords in plaintext.
So my basic question is:
Is there any better way? Am I on the right track to create a halfway secure "logic". Or is it enough to use Baisc/Digest Authentication if I use SSL?
I know that Security is a very hard thing to achieve but I really want to learn how I can implement such things.

Categories