Skip to content

Instantly share code, notes, and snippets.

@cooclsee
Last active December 6, 2015 03:58
Show Gist options
  • Save cooclsee/9f84d920b66851364e75 to your computer and use it in GitHub Desktop.
Save cooclsee/9f84d920b66851364e75 to your computer and use it in GitHub Desktop.
C# md5 and sha1 crypt
using System;
using System.Security.Cryptography;
using System.Text;
namespace Demo
{
public static class Md5Encrypt
{
/// <summary>
/// 获取由MD5加密的字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string EncryptToMd5(string str)
{
var md5 = new MD5CryptoServiceProvider();
return Encrypt(md5, str);
}
/// <summary>
/// 获取由SHA1加密的字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string EncryptToSha1(string str)
{
var sha1 = new SHA1CryptoServiceProvider();
return Encrypt(sha1, str);
}
private static string Encrypt(HashAlgorithm cryptProvider, string str)
{
if (cryptProvider != null && !string.IsNullOrEmpty(str))
{
byte[] str1 = Encoding.UTF8.GetBytes(str);
byte[] str2 = cryptProvider.ComputeHash(str1, 0, str1.Length);
cryptProvider.Clear();
cryptProvider.Dispose();
return Convert.ToBase64String(str2);
}
return string.Empty;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment