安全哈希算法(Secure Hash Algorithm)主要适用于数字签名标准 (Digital Signature Standard DSS)里面定义的数字签名算法(Digital Signature Algorithm DSA)。对于长度小于2^64位的消息,SHA1会产生一个160位的消息摘要。当接收到消息的时候,这个消息摘要可以用来验证数据的完整性。在传输的过程中,数据很可能会发生变化,那么这时候就会产生不同的消息摘要。 SHA1有如下特性:不可以从消息摘要中复原信息;两个不同的消息不会产生同样的消息摘要,(但会有1x10 ^ 48分之一的机率出现相同的消息摘要,一般使用时忽略)。
- /// <summary>
- /// SHA1 加密,返回大写字符串
- /// </summary>
- /// <param name="content">需要加密字符串</param>
- /// <returns>返回40位UTF8 大写</returns>
- public static string SHA1(string content)
- {
- return SHA1(content, Encoding.UTF8);
- }
- /// <summary>
- /// SHA1 加密,返回大写字符串
- /// </summary>
- /// <param name="content">需要加密字符串</param>
- /// <param name="encode">指定加密编码</param>
- /// <returns>返回40位大写字符串</returns>
- public static string SHA1(string content, Encoding encode)
- {
- try
- {
- SHA1 sha1 = new SHA1CryptoServiceProvider();
- byte[] bytes_in = encode.GetBytes(content);
- byte[] bytes_out = sha1.ComputeHash(bytes_in);
- sha1.Dispose();
- string result = BitConverter.ToString(bytes_out);
- result = result.Replace("-", "");
- return result;
- }
- catch (Exception ex)
- {
- throw new Exception("SHA1加密出错:" + ex.Message);
- }
- }