本文整理汇总了C#中System.Security.Cryptography.MD5CryptoServiceProvider.ComputeHash方法的典型用法代码示例。如果您正苦于以下问题:C# MD5CryptoServiceProvider.ComputeHash方法的具体用法?C# MD5CryptoServiceProvider.ComputeHash怎么用?C# MD5CryptoServiceProvider.ComputeHash使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.MD5CryptoServiceProvider
的用法示例。
在下文中一共展示了MD5CryptoServiceProvider.ComputeHash方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetMd5Sum
// Create an md5 sum string of this string
public static string GetMd5Sum(this string str)
{
// First we need to convert the string into bytes, which
// means using a text encoder.
Encoder enc = System.Text.Encoding.Unicode.GetEncoder();
// Create a buffer large enough to hold the string
byte[] unicodeText = new byte[str.Length * 2];
enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);
// Now that we have a byte array we can ask the CSP to hash it
MD5 md5 = new MD5CryptoServiceProvider();
byte[] result = md5.ComputeHash(unicodeText);
// Build the final string by converting each byte
// into hex and appending it to a StringBuilder
var sb = new StringBuilder();
for (int i = 0; i < result.Length; i++)
{
sb.Append(result[i].ToString("X2"));
}
// And return it
return sb.ToString();
}
示例2: FormatId
public static string FormatId(Type sagaType, string propertyName, object propertyValue)
{
if (propertyValue == null)
{
throw new ArgumentNullException(nameof(propertyValue), $"Property {propertyName} is a correlation property on {sagaType.Name} but contains a null value. Make sure that all correlation properties on the SagaData have a defined value.");
}
// use MD5 hash to get a 16-byte hash of the string
using (var provider = new MD5CryptoServiceProvider())
{
var inputBytes = Encoding.Default.GetBytes(propertyValue.ToString());
var hashBytes = provider.ComputeHash(inputBytes);
// generate a guid from the hash:
var value = new Guid(hashBytes);
var id = $"{sagaType.FullName.Replace('+', '-')}/{propertyName}/{value}";
// raven has a size limit of 255 bytes == 127 unicode chars
if (id.Length > 127)
{
// generate a guid from the hash:
var hash = provider.ComputeHash(Encoding.Default.GetBytes(sagaType.FullName + propertyName));
var key = new Guid(hash);
id = $"MoreThan127/{key}/{value}";
}
return id;
}
}
示例3: MD5
/**/
/// <summary>
/// 对字符串进行MD5加密
/// </summary>
/// <param name="text">要加密的字符串</param>
/// <param name="charset">字符串编码格式</param>
/// <example>str = MD5("木子屋","gb2312");</example>
/// <returns></returns>
public static string MD5(string text, string charset)
{
return (MD5(text, charset, false));
}
/**/
/// <summary>
/// 对字符串或参数值进行MD5加密
/// </summary>
/// <param name="text">要加密的字符串或参数名称</param>
/// <param name="charset">字符串编码格式</param>
/// <param name="isArg">加密字符串类型 true:参数值 false:字符串</param>
/// <returns></returns>
public static string MD5(string text, string charset, bool isArg)
{
try
{
MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
HttpRequest request = HttpContext.Current.Request;
if (isArg)
{
NameValueCollection Collect = HttpUtility.ParseQueryString(request.Url.Query, Encoding.GetEncoding(charset));//使用Collect接收参数值
if (Collect[text] != null)
{
return BitConverter.ToString(MD5.ComputeHash(Encoding.GetEncoding(charset).GetBytes(Collect[text].ToString()))).Replace("-", "");
}
}
else
{
return BitConverter.ToString(MD5.ComputeHash(Encoding.GetEncoding(charset).GetBytes(text))).Replace("-", "");
}
}
catch { }
return string.Empty;
}
示例4: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
_badPass.Visible = false;
if (IsPostBack)
{
SharedConfig.SharedConfig config = new SharedConfig.SharedConfig();
Byte[] submittedPassBytes;
Byte[] encodedBytes;
MD5 md5;
string amereSalt = "0ç__è-(''\"'-°\"Bhj5s9867";
md5 = new MD5CryptoServiceProvider();
submittedPassBytes = ASCIIEncoding.Default.GetBytes(amereSalt + this._oldpassTextBox.Text);
encodedBytes = md5.ComputeHash(submittedPassBytes);
string hash = BitConverter.ToString(encodedBytes);
if (hash == config.AdminPwdHash)
{
submittedPassBytes = ASCIIEncoding.Default.GetBytes(amereSalt + this._newPassBisTextBox.Text);
encodedBytes = md5.ComputeHash(submittedPassBytes);
hash = BitConverter.ToString(encodedBytes);
config.PropertyValues["AdminPwdHash"].PropertyValue = hash;
config.PropertyValues["LastUpdatedDate"].PropertyValue = DateTime.Now;
config.PropertyValues["LastUpdatedFrom"].PropertyValue = "Here";
config.Save();
_badPass.Visible = false;
Session.Abandon();
}
else
_badPass.Visible = true;
}
}
示例5: passChange_Click
private void passChange_Click(object sender, EventArgs e)
{
MD5 word = new MD5CryptoServiceProvider();
byte[] s = new byte[1000000];
string temp;
s = System.Text.Encoding.Unicode.GetBytes(oldPassword.Text.ToString());
s = word.ComputeHash(s);
temp = Convert.ToBase64String(s);
s = new byte[1000000];
if ((passString == temp) || (passString == oldPassword.Text.ToString()))
{
if (newPassword1.Text.ToString() == newPassword2.Text.ToString())
{
s = System.Text.Encoding.Unicode.GetBytes(newPassword2.Text.ToString());
s = word.ComputeHash(s);
passString = Convert.ToBase64String(s);
Properties.Settings.Default.gothrough = passString.ToString();
MessageBox.Show("Password changed to the Hash:\n" + passString.ToString(), "Password Changed");
}
else
{
MessageBox.Show("New Passwords must match.", "Unmatched Password");
oldPassword.Text = newPassword1.Text = newPassword2.Text = "";
}
}
else
{
MessageBox.Show("Invalid Password Entered", "ERROR");
oldPassword.Text = newPassword1.Text = newPassword2.Text = "";
}
}
示例6: UserAuthenticationHash
/// <summary>
/// First stage of user authentication.
/// </summary>
/// <returns>user authenticate part</returns>
private byte[] UserAuthenticationHash()
{
//If authzid is specified, then A1 is
//
//A1 = { H( { username-value, ":", realm-value, ":", passwd } ),
// ":", nonce-value, ":", cnonce-value, ":", authzid-value }
//
//If authzid is not specified, then A1 is
//
//A1 = { H( { username-value, ":", realm-value, ":", passwd } ),
// ":", nonce-value, ":", cnonce-value }
StringBuilder result = new StringBuilder();
MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
byte[] toHash = Encoding.Default.GetBytes(String.Concat(UserName, ":", Realm, ":", Password));
byte[] hash = MD5.ComputeHash(toHash);
result.Append(Encoding.Default.GetChars(hash));
result.Append(":");
result.Append(Nonce);
result.Append(":");
result.Append(Cnonce);
if (Authzid.Length != 0)
{
result.Append(":");
result.Append(Authzid);
}
toHash = Encoding.Default.GetBytes(result.ToString());
hash = MD5.ComputeHash(toHash);
return hash;
}
示例7: EncryptStr
public static string EncryptStr(string str, string strKey, string strIV)
{
CryptoStream cryptoStream = (CryptoStream) null;
MD5CryptoServiceProvider cryptoServiceProvider = new MD5CryptoServiceProvider();
try
{
Encrypt.RMCrypto = new RijndaelManaged();
if (str == null || str.Trim().Length == 0)
return "";
byte[] hash1 = cryptoServiceProvider.ComputeHash(Encoding.ASCII.GetBytes(strKey));
byte[] hash2 = cryptoServiceProvider.ComputeHash(Encoding.ASCII.GetBytes(strIV));
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(str));
cryptoStream = new CryptoStream((Stream) memoryStream, Encrypt.RMCrypto.CreateEncryptor(hash1, hash2), CryptoStreamMode.Write);
return Convert.ToBase64String(memoryStream.ToArray());
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (null != cryptoStream)
;
if (null != Encrypt.RMCrypto)
{
Encrypt.RMCrypto.Clear();
Encrypt.RMCrypto = (RijndaelManaged) null;
}
}
}
示例8: DoUpdate
public void DoUpdate(FormCollection form)
{
var cmd = new SqlCommand();
Byte[] password;
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
UTF8Encoding encoder = new UTF8Encoding();
password = md5Hasher.ComputeHash(encoder.GetBytes(form["old_pass"].ToString()));
string new_pass = Convert.ToBase64String(md5Hasher.ComputeHash(password));
if (form["old_pass"].ToString() == "")
{
cmd.CommandText = "UPDATE users SET [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected] WHERE [email protected]";
}
else {
cmd.CommandText = "UPDATE users SET [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected] WHERE [email protected]";
}
cmd.Parameters.AddWithValue("@first", form["firstname"].ToString());
cmd.Parameters.AddWithValue("@last", form["lastname"].ToString());
cmd.Parameters.AddWithValue("@sex", form["sex"].ToString());
cmd.Parameters.AddWithValue("@email", form["email"].ToString());
cmd.Parameters.AddWithValue("@phone", form["phone"].ToString());
cmd.Parameters.AddWithValue("@address", form["address"].ToString());
cmd.Parameters.AddWithValue("@position", form["position"].ToString());
cmd.Parameters.AddWithValue("@username", form["username"].ToString());
cmd.Parameters.AddWithValue("@des", form["description"].ToString());
cmd.Parameters.AddWithValue("@id", form["user_id"].ToString());
cmd.Parameters.AddWithValue("@pass",new_pass);
var result = new DataAdapter().RunNonQuery(cmd);
Response.Redirect("~/users");
}
示例9: FilesEqual
public static bool FilesEqual(string path1, string path2)
{
bool result = false;
MD5 md5 = new MD5CryptoServiceProvider();
FileStream stream1 = File.OpenRead(path1);
FileStream stream2 = File.OpenRead(path2);
byte[] hash1 = md5.ComputeHash(stream1);
byte[] hash2 = md5.ComputeHash(stream2);
stream1.Close();
stream2.Close();
if (hash1.Length == hash2.Length)
{
result = true;
for(int i=0; i < hash1.Length; i++)
{
if (hash1[i] != hash2[i])
{
result = false;
break;
}
}
}
return result;
}
示例10: CreateKeyDigest
static byte[] CreateKeyDigest(String password, byte[] docIdData)
{
Check16Bytes(docIdData, "docId");
int nChars = Math.Min(password.Length, 16);
byte[] passwordData = new byte[nChars * 2];
for (int i = 0; i < nChars; i++)
{
char ch = password[i];
passwordData[i * 2 + 0] = (byte)((ch << 0) & 0xFF);
passwordData[i * 2 + 1] = (byte)((ch << 8) & 0xFF);
}
byte[] kd;
MD5 md5 = new MD5CryptoServiceProvider();
byte[] passwordHash = md5.ComputeHash(passwordData);
md5.Clear();
md5.Initialize();
byte[] data=new byte[passwordHash.Length*16 + docIdData.Length*16];
int offset=0;
for (int i = 0; i < 16; i++)
{
Array.Copy(passwordHash, 0, data, offset, PASSWORD_HASH_NUMBER_OF_BYTES_USED);
offset+=passwordHash.Length;
Array.Copy(docIdData,0,data,offset,docIdData.Length);
offset += docIdData.Length;
}
kd = md5.ComputeHash(data);
byte[] result = new byte[KEY_DIGEST_LENGTH];
Array.Copy(kd, 0, result, 0, KEY_DIGEST_LENGTH);
return result;
}
示例11: MD5Value
// <summary>
/// 计算字符串或者文件MD5值
/// </summary>
/// <param name="str">需要计算的字符串或文件路径</param>
/// <param name="isStr">true为字符串,false为文件</param>
/// <returns>MD5值</returns>
public string MD5Value(String str, Boolean isStr)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] md5ch;
if (isStr)
{
byte[] ch = System.Text.Encoding.Default.GetBytes(str);
md5ch = md5.ComputeHash(ch);
}
else
{
if (!File.Exists(str))
return string.Empty;
FileStream fs = new FileStream(str, FileMode.Open, FileAccess.Read);
md5ch = md5.ComputeHash(fs);
fs.Close();
}
md5.Clear();
string strMd5 = "";
for (int i = 0; i < md5ch.Length - 1; i++)
{
strMd5 += md5ch[i].ToString("x").PadLeft(2, '0');
}
return strMd5;
}
示例12: FormatId
public static string FormatId(Type sagaType, KeyValuePair<string, object> uniqueProperty)
{
if (uniqueProperty.Value == null)
{
throw new ArgumentNullException("uniqueProperty", string.Format("Property {0} is marked with the [Unique] attribute on {1} but contains a null value. Please make sure that all unique properties are set on your SagaData and/or that you have marked the correct properties as unique.", uniqueProperty.Key, sagaType.Name));
}
// use MD5 hash to get a 16-byte hash of the string
using (var provider = new MD5CryptoServiceProvider())
{
var inputBytes = Encoding.Default.GetBytes(uniqueProperty.Value.ToString());
var hashBytes = provider.ComputeHash(inputBytes);
// generate a guid from the hash:
var value = new Guid(hashBytes);
var id = string.Format("{0}/{1}/{2}", sagaType.FullName.Replace('+', '-'), uniqueProperty.Key, value);
// raven has a size limit of 255 bytes == 127 unicode chars
if (id.Length > 127)
{
// generate a guid from the hash:
var hash = provider.ComputeHash(Encoding.Default.GetBytes(sagaType.FullName + uniqueProperty.Key));
var key = new Guid(hash);
id = string.Format("MoreThan127/{0}/{1}", key, value);
}
return id;
}
}
示例13: ValueToByteArray
protected override byte[] ValueToByteArray()
{
if (Value == null)
return null;
var md5 = new MD5CryptoServiceProvider();
var key = Secret + Encoding.Default.GetString(RequestAuthenticator);
var hash = md5.ComputeHash(Encoding.ASCII.GetBytes(key));
var hashed = System.BitConverter.ToString(hash).Replace("-", string.Empty);
var rounds = (int)Math.Ceiling((double)Value.Length / 16);
var result = new byte[rounds * 16];
for (var j = 0; j < rounds; j++)
{
var currentChunkStr = Value.Length < (j + 1) * 16 ? Value.Substring(j * 16, Value.Length - j * 16) : Value.Substring(j * 16, 16);
for (var i = 0; i <= 15; i++)
{
var pm = 2 * i > hashed.Length ? 0 : Convert.ToInt32(hashed.Substring(2 * i, 2), 16);
var pp = i >= currentChunkStr.Length ? 0 : currentChunkStr[i];
var pc = pm ^ pp;
result[(j * 16) + i] = (byte)pc;
}
var currentChunk = new byte[16];
Array.Copy(result, j * 16, currentChunk, 0, 16);
var currentKey = Secret + Encoding.Default.GetString(currentChunk);
hash = md5.ComputeHash(Encoding.Default.GetBytes(currentKey));
hashed = System.BitConverter.ToString(hash).Replace("-", string.Empty);
}
return result;
}
示例14: GetMD5Hash
public static string GetMD5Hash(string pathName, bool isFile = false)
{
string res = "";
string strHashData = "";
byte[] val;
FileStream teu = null;
using (var hsh = new MD5CryptoServiceProvider())
{
try
{
if (isFile)
{
teu = GetFileStream(pathName);
val = hsh.ComputeHash(teu);
teu.Close();
strHashData = BitConverter.ToString(val);
}
else
{
var b = Encoding.ASCII.GetBytes(pathName);
val = hsh.ComputeHash(b);
strHashData = BitConverter.ToString(val);
}
strHashData = strHashData.Replace("-", "");
res = strHashData;
}
catch { return null; }
}
return res;
}
示例15: hashCryptPrivate
private static string hashCryptPrivate(byte[] text, string genSalt, string itoa64)
{
string output = "*";
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
if (!genSalt.StartsWith("$H$")) return output;
// $count_log2 = strpos($itoa64, $setting[3]);
int count_log2 = itoa64.IndexOf(genSalt[3]);
if (count_log2 < 7 || count_log2 > 30) return output;
int count = 1 << count_log2;
byte[] salt = ASCIIEncoding.ASCII.GetBytes(genSalt.Substring(4, 8));
if (salt.Length != 8) return output;
byte[] hash = md5.ComputeHash(Combine(salt, text));
do
{
hash = md5.ComputeHash(Combine(hash, text));
} while (count-- > 1);
output = genSalt.Substring(0, 12);
output += hashEncode64(hash, 16, itoa64);
return output;
}