Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHA1 C# equivalent of this Java

Tags:

java

c#

sha1

Looking for the same equivalent to this method in C#

try {
          MessageDigest md = MessageDigest.getInstance("SHA-1");
          md.update(password.getBytes());
          BigInteger hash = new BigInteger(1, md.digest());
          hashword = hash.toString(16);
      } catch (NoSuchAlgorithmException ex) {
          }
}
return hashword;
like image 421
Julio Avatar asked Sep 11 '25 19:09

Julio


2 Answers

Super easy in C#:

using System;
using System.Text;
using System.Security.Cryptography;

namespace CSharpSandbox
{
    class Program
    {
        public static string HashPassword(string input)
        {
            var sha1 = SHA1.Create();
            byte[] inputBytes = Encoding.ASCII.GetBytes(input);
            byte[] outputBytes = sha1.ComputeHash(inputBytes);
            return BitConverter.ToString(outputBytes).Replace("-", "").ToLower();
        }

        public static void Main(string[] args)
        {
            string output = HashPassword("The quick brown fox jumps over the lazy dog");
        }
    }
}
like image 91
Juliet Avatar answered Sep 13 '25 10:09

Juliet


Have a look at Sha1CryptoServiceProvider. It provides a good amount of flexibility. Like most of the algorithms in System.Security.Cryptography, it provides methods for handling byte arrays and streams.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!