Wednesday 1 June 2016

CalculateHash from SHA256 algorithms in C# [solved]

Few SHA algorithms code snippet are:-

static string _SHA1CryptoServiceProvider(string password)
        {
            System.Security.Cryptography.SHA1CryptoServiceProvider crypt = new System.Security.Cryptography.SHA1CryptoServiceProvider();
            System.Text.StringBuilder hash = new System.Text.StringBuilder();
            byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(password), 0, Encoding.UTF8.GetByteCount(password));
            foreach (byte theByte in crypto)
            {
                hash.Append(theByte.ToString("x2"));
            }
            return hash.ToString();
        }
 public string _HMACSHA256(string data)
        {
            string hash = String.Empty;
            byte[] mbyte = Encoding.ASCII.GetBytes(data);
            HMACSHA256 hmac = new HMACSHA256();
            byte[] hmsg = hmac.ComputeHash(mbyte, 0, Encoding.ASCII.GetByteCount(data));
            foreach (byte theByte in hmsg)
            {
                hash += theByte.ToString("x2");
            }
            return hash;

        }

If FIPSAlgorithmPolicy  enabled

        static string _SHA256CryptoServiceProvider(string password)
        {
            System.Security.Cryptography.SHA256CryptoServiceProvider crypt = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            System.Text.StringBuilder hash = new System.Text.StringBuilder();
            byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(password), 0, Encoding.UTF8.GetByteCount(password));
            foreach (byte theByte in crypto)
            {
                hash.Append(theByte.ToString("x2"));
            }
            return hash.ToString();
        }
If FIPSAlgorithmPolicy not enabled
static string _SHA256Managed(string str) { SHA256Managed crypt = new SHA256Managed(); string hash = String.Empty; byte[] crypto = crypt.ComputeHash(Encoding.ASCII.GetBytes(str), 0, Encoding.ASCII.GetByteCount(str)); foreach (byte theByte in crypto) { hash += theByte.ToString("x2"); } return hash; }