SHA stands for Secure Hash Algorithm. This hash algorithm are applied to encrpt the string and store in un-readable format. SHA-1 is the best established of the existing SHA hash functions, and is employed in several widely used security applications and protocols. SHA-1 is implemented in .Net using System.Security.Cryptography.SHA1 Namespace.
First the given string is converted to byte array using ASCIIEncoding class in System.Text Namespace. GetBytes method on ASCIIEncoding class converts given string to byte[]
ComputeHash method in SHA1 class create a hash with SHA-1 Algorithm. Resultant Hashed byte[] is convert to string using Convert.ToBase64String Method
Hashed on encrpted string cannot be decryted (for security reasons). Raw string can be compared with hashed string only by hashing the raw string using the same hash function.
public static string HashCode(string str)
{
string rethash = "";
try
{
System.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1.Create();
System.Text.ASCIIEncoding encoder = new System.Text.ASCIIEncoding();
byte[] combined = encoder.GetBytes(str);
hash.ComputeHash(combined);
rethash = Convert.ToBase64String(hash.Hash);
}
catch (Exception ex)
{
string strerr = "Error in HashCode : " + ex.Message;
}
return rethash;
}
I needed to calculate a hash from an incoming field in my SSIS package (SQL Server Integration Services) and this is exactly what I needed, thanks! It works great in a Script Component transformation, and the corresponding data type to store the byte array in a field the data flow is DT_BYTES. Thought I'd mention it in case someone ens up here with the same purpose as I did :-)
SHA1 is a hash, not an encryption, you cannot encrypt a string using SHA1, only hash it encryptions store the data they protect, and that data can be accessed through a decryption algorithm SHA1 and other hashes do not store the original text, and therefore cannot be decrypted
you may want to look at this online sha1 encrypter pretty cool to check how a sha1 message looks like David
MD5 encrypt , Can I used this code to apply?
One MAJOR mistake you've made is converting the source string to an ASCII byte array BEFORE you generated the hash. By default all .NET applications are setup for Unicode strings, so unless you switched your app to UTF-8 or ASCII your code is broken. Why... The simple answer is that your code is NOT unicode compliant and any unicode string (say Greek or Chinese) you pass in will be treated as an array of ASCII char 63 (i.e. '?'). That said, you CAN convert the result of the hash to unicode since it's hexidecimal and therefore will fit into the ASCII char set.