4

I'm using SHA1 to encrypt some values like password. This is my code:

String passwd = Membership.GeneratePassword(10, 2);
SHA1 sha = new SHA1CryptoServiceProvider();
byte [] password = sha.ComputeHash(passwd);

But VS returns error, because passwd is a string. I have to store the password in a byte array, so is there a way to solve this?

2
  • 2
    SHA1 is not an encryption algorithm. You mean hash. Commented Mar 23, 2014 at 23:31
  • You are using unsalted SHA1, just like LinkedIn in the past. As you might have heard, that didn't work out too well for them. Instead use bcrypt, it slows down password crackers a couple orders of magnitude and has built-in salting. Commented Mar 24, 2014 at 0:01

2 Answers 2

15
String passwd = Membership.GeneratePassword(10, 2);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(passwd);
SHA1 sha = new SHA1CryptoServiceProvider();
byte [] password = sha.ComputeHash(bytes);

Note that SHA1 does not encrypt data but hash them instead. Encrypted data can be decrypted. Hash algorithms are one way.

Sign up to request clarification or add additional context in comments.

2 Comments

Although @tvanfosson got it correctly first, +1 from me for enhancing your answer after being accepted.
byte[] password = new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input)); as a one liner.
1

Use an Encoding to convert the string to a byte array

var bytes= Encoding.UTF8.GetBytes(passwd);
var password = sha.ComputeHash(bytes);

2 Comments

I would change the variable name to encoded, otherwise this is a bit confusing, isn't it?
The new name bytes is much better. And I'd go with your answer using UTF8 rather that the accepted answer with Unicode. You beat me to it, so +1 from me ;).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.