user840718
user840718

Reputation: 1611

C# use SHA1 to hash string into byte array

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?

Upvotes: 4

Views: 22858

Answers (2)

meziantou
meziantou

Reputation: 21337

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.

Upvotes: 15

tvanfosson
tvanfosson

Reputation: 532445

Use an Encoding to convert the string to a byte array

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

Upvotes: 1

Related Questions