11

I have that code to encrypt string to sha256 and next to base64:

 public static string Sha256encrypt(string phrase)
    {
        UTF8Encoding encoder = new UTF8Encoding();
        SHA256Managed sha256hasher = new SHA256Managed();
        byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(phrase));
        return Convert.ToBase64String(hashedDataBytes);
    }

How can I decrypt my password in other side?

1

3 Answers 3

25

You cannot decrypt the result of a One Way Hash. What you should do instead is compare a hash of the entered password versus the stored hash in the database.

Example:

var password = "1234";
var hashedPassword = Sha256encrypt(password);

var allowLogin = hashedPassword == storedPassword; //storedPassword from Database, etc.

This is only the very basics though, when using hashing algorithms you should consider using a Salt too.

4
  • 4
    More than a salt, you should be iterating your hash. Or better (much better), don't invent it yourself: use PBKDF2, scrypt, or bcrypt. Apr 23, 2012 at 2:53
  • Sha256 can be decrypted, please check the website md5decrypt.net/en/Sha256/#answer
    – obaid
    Nov 19, 2020 at 12:45
  • 2
    @obaid - that doesn't decrypt it, it just looks for a matching hash in a database. You cannot reverse SHA256 as it is destructive, you only ever get 256 bits no matter how much data you put in. War and Peace can be SHA256'd but you can not get War and Peace back from the Hashed Bits.
    – DaveShaw
    Nov 19, 2020 at 18:56
  • "you only ever get 256 bits no matter how much data you put in" that makes me understand SHA256 thank you @DaveShaw
    – obaid
    Nov 26, 2020 at 5:35
6

It is impossible per se. SHA is a hash function, which implies it is one-way and used just for validation and similar things. Since the result of SHA-256 is of fixed length (256 bits) that also means that most of the information is lost when computing it.

You can brute-force it though, meaning that you could try and compute hash of a large number of different inputs and see if the hash matches.

Sometime in the future a cryptographic weakness may be found for SHA thus making it breakable but practically it is not a reversible function.

See details about hash functions on Wikipedia.

0
0

In Ruby

digest = Digest::SHA256.new
decrypt_sha256 = digest.hexdigest(v)
if decrypt_sha256 == hash
  return v
end

end return nil

1
  • OP is asking about C# code, question is tagged with C# tag. Not ruby.
    – Prolog
    Apr 17 at 22:40

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.