Generate SHA - CSharp System.Security.Cryptography

CSharp examples for System.Security.Cryptography:SHA1

Description

Generate SHA

Demo Code


using System.Diagnostics.Contracts;
using System.Security.Cryptography;
using System.Text;
using System;/*from  w  w  w  .ja  va  2s. c  o  m*/

public class Main{
        /// <summary>
        /// M?todo respons?vel por encriptar 
        /// </summary>
        /// <param name="plainTextString">Texto puro</param>
        /// <param name="salt">Array de bytes que representa chave de criptografia</param>
        /// <returns>Texto encriptado</returns>
        [Pure]
        public static string GenerateSHA1(string plainTextString, byte[] salt)
        {
            if (string.IsNullOrWhiteSpace(plainTextString))
            {
                throw new ArgumentNullException("plainTextString", "the string to be hashed needs to be different then null");
            }

            salt = salt == null 
                ? new byte[0] 
                : salt;

            HashAlgorithm algorithm = new SHA1Managed();
            var plainTextBytes = Encoding.UTF8.GetBytes(plainTextString);

            var plainTextWithSaltBytes = AppendByteArray(plainTextBytes, salt);
            var saltedSHA1 = BitConverter.ToString(
                SHA1.Create().ComputeHash(
                    plainTextWithSaltBytes
                )
            )
            .Replace("-", string.Empty); ;

            return saltedSHA1;
        }
        /// <summary>
        /// M?todo respons?vel por encriptar 
        /// </summary>
        /// <param name="plainTextString">Texto puro</param>
        /// <returns>Texto encriptado</returns>
        [Pure]
        public static string GenerateSHA1(string plainTextString)
        {
            return GenerateSHA1(plainTextString, null);
        }
}

Related Tutorials