In C# how we can use SHA1 automatically?
Is SHA1 better than MD5?(We use hashing for user name and password and need speed for authentication)
views:
1628answers:
4How to use SHA1 or MD5 in C#?(which one is better in performance and security for authentication)
From MSDN
byte[] data = new byte[DATA_SIZE];
byte[] result;
SHA1 sha = new SHA1CryptoServiceProvider();
// This is one implementation of the abstract class SHA1.
result = sha.ComputeHash(data);
For comparison you can check this
Not sure what you mean by automatically, but you should really use SHA256
and higher. MD5 has been cracked, so using it for security of passwords is not a great idea. Also always use a Salt (code) with your hashes.
byte[] data = new byte[DATA_SIZE];
byte[] result;
SHA256 shaM = new SHA256Managed();
result = shaM.ComputeHash(data);
Will do the trick for you using SHA256 and is found at MSDN.
SHA1 is stronger than MD5 so if you have the choice it would be better to use it. Here's an example:
public static string CalculateSHA1(string text, Encoding enc)
{
byte[] buffer = enc.GetBytes(text);
SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider();
return BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", "");
}
Both are too fast to be used, directly at least. Use Key Strengthening to "slow down" the password hashing procedure. Speed is the unfortunately the enemy to password security.
How slow is slow enough? Slowing down a password hash from ~microseconds to ~hundreds of milliseconds will not adversely affect the perceived performance of your application... but will make cracking passwords literally a hundred thousand times slower.
View this article for details: http://chargen.matasano.com/chargen/2007/9/7/enough-with-the-rainbow-tables-what-you-need-to-know-about-s.html
The problem is that MD5 is fast. So are its modern competitors, like SHA1 and SHA256. Speed is a design goal of a modern secure hash, because hashes are a building block of almost every cryptosystem, and usually get demand-executed on a per-packet or per-message basis.
Speed is exactly what you don’t want in a password hash function.
... snip ...
The password attack game is scored in time taken to crack password X. With rainbow tables, that time depends on how big your table needs to be and how fast you can search it. With incremental crackers, the time depends on how fast you can make the password hash function run.
That said, use BCrypt. SCrypt was recently developed, but I doubt that any stable (or production ready) libraries exist for it yet. Theoretically, SCrypt claims to improve upon BCrypt. "Building your own" is not recommended, but iterating MD5 / SHA1 / SHA256 thousands of times ought to do the trick (ie: Key Strengthening).
And in case you don't know about them, be sure to read up on Rainbow Tables. Basic security stuff.