// 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(); }
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; } } }
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; }
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; } }
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; }
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 = ""; } }
public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2) { CompareResult cr = CompareResult.ciCompareOk; // removed the size test - all images compared will be the same size! (32-bit x height x width) //Convert each image to a byte array System.Drawing.ImageConverter ic = new System.Drawing.ImageConverter(); byte[] btImage1 = new byte[1]; btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType()); byte[] btImage2 = new byte[1]; btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType()); //Compute a hash for each image //Pointless to use SHA256 when MD5 is good enough. Speed advantage is worth it here. MD5 shaM = new MD5CryptoServiceProvider(); byte[] hash1 = shaM.ComputeHash(btImage1); byte[] hash2 = shaM.ComputeHash(btImage2); //Compare the hash values for (int i = 0; i < hash1.Length && i < hash2.Length && cr == CompareResult.ciCompareOk; i++) { if (hash1[i] != hash2[i]) cr = CompareResult.ciPixelMismatch; } return cr; } // end function
public static string GenerateUniqueIdentityRecordId(string uniqueValue, ISagaInfo sagaInfo) { // use MD5 hash to get a 16-byte hash of the string using (var provider = new MD5CryptoServiceProvider()) { var inputBytes = Encoding.Default.GetBytes(uniqueValue); byte[] hashBytes = provider.ComputeHash(inputBytes); // generate a guid from the hash: var value = new Guid(hashBytes); var id = string.Format("{0}/{1}", sagaInfo.SagaUniqueIdentityKeyPrefix, value); // raven has a size limit of 255 bytes == 127 unicode chars if (id.Length > 127) { // generate a guid from the hash: var key = new Guid( provider.ComputeHash(Encoding.Default.GetBytes(sagaInfo.SagaDataTypeFullName + sagaInfo.UniqueField))); id = string.Format("MoreThan127/{0}/{1}", key, value); } return id; } }
public object Get(string method, object parameters = null) { Dictionary<string, string> properties = parameters.ToDictionary(); properties.Add("method", method); properties.Add("application_key", _applicationPublic); string arguments = string.Join(string.Empty, properties.OrderBy(p => p.Key).Select(p => string.Format("{0}={1}", p.Key, p.Value))); MD5 md5 = new MD5CryptoServiceProvider(); byte[] secretBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(_accessToken + _applicationSecret)); arguments += BitConverter.ToString(secretBytes).Replace("-", string.Empty).ToLowerInvariant(); byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(arguments)); string hashHex = BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLowerInvariant(); properties.Add("access_token", _accessToken); properties.Add("sig", hashHex); arguments = string.Join("&", properties.Select(p => string.Format("{0}={1}", p.Key, p.Value))); var client = new HttpClient(); string requestUrl = string.Format(ApiUrl, arguments); HttpResponseMessage result = client.GetAsync(requestUrl).Result; string response = result.Content.ReadAsStringAsync().Result; return JsonConvert.DeserializeObject(response); }
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; } }
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; }
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 firstname=@first,lastname=@last,gender=@sex,email=@email,phone=@phone,address=@address,position=@position,username=@username,description=@des WHERE userid=@id"; } else { cmd.CommandText = "UPDATE users SET firstname=@first,lastname=@last,gender=@sex,email=@email,phone=@phone,address=@address,position=@position,username=@username,password=@pass,description=@des WHERE userid=@id"; } 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"); }
/**/ /// <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; }
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; }
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; } }
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; }
// <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; }
/// <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; }
public static string GetMd6Str(string ConvertString) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8).Replace("-", "B"); t2 += BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8).Replace("-","Z"); t2 += BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8).Replace("-", "W"); return t2; }
public static bool IsSame(string password1, string password2) { using (var md5 = new MD5CryptoServiceProvider()) { var str1 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password1))); var str2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(password2))); return str1 == str2; } }
private string CalculateDigestFromUserDigest(string userDigest, string httpMethod) { var text1 = string.Format("{0}:{1}", httpMethod, Path); var encoding = Encoding.GetEncoding(Constants.Enconding); var md5 = new MD5CryptoServiceProvider(); var digest1 = DigestUtils.ToHexString(md5.ComputeHash(encoding.GetBytes(text1))); var text2 = string.Format("{0}:{1}:{2}:{3}:{4}:{5}", userDigest, ServerNonce, SequenceNumber, ClientNonce, "auth", digest1); return DigestUtils.ToHexString(md5.ComputeHash(encoding.GetBytes(text2))); }
public static string GetMd5Hash(string input) { const string hashKey = "Aa1@#$,.Klj+{>.45oP"; using (var md5 = new MD5CryptoServiceProvider()) { string hashCode = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(input))).Replace("-", "") + BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(hashKey))).Replace("-", ""); return BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(hashCode))).Replace("-", ""); } }
/// <summary> /// AES解密 /// </summary> /// <param name="cipherText">加密文本内容</param> /// <param name="key">加密Key值</param> /// <returns>原本内容</returns> public static string AESDecrypt(string cipherText, string key) { var AES = new RijndaelManaged(); var MD5 = new MD5CryptoServiceProvider(); byte[] cipherTextData = Convert.FromBase64String(cipherText); byte[] keyData = MD5.ComputeHash(Encoding.Unicode.GetBytes(key)); byte[] IVData = MD5.ComputeHash(Encoding.Unicode.GetBytes("Alex Lee")); ICryptoTransform transform = AES.CreateDecryptor(keyData, IVData); byte[] outputData = transform.TransformFinalBlock(cipherTextData, 0, cipherTextData.Length); return Encoding.Unicode.GetString(outputData); }
/// <summary> /// Encrypts the string to a byte array using the MD5 Encryption /// Algorithm with an additional Salted Hash. /// <see cref="System.Security.Cryptography.MD5CryptoServiceProvider"/> /// </summary> /// <param name="ToEncrypt">System.String. Usually a password.</param> /// <returns>System.Byte[]</returns> public static byte[] MD5SaltedHashEncryption(string ToEncrypt) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hashedbytes; byte[] saltedhash; UTF8Encoding textencoder = new UTF8Encoding(); hashedbytes = md5.ComputeHash(textencoder.GetBytes(ToEncrypt)); ToEncrypt += textencoder.GetString(hashedbytes); saltedhash = md5.ComputeHash(textencoder.GetBytes(ToEncrypt)); md5.Clear(); return saltedhash; }
/// <summary> /// 多次使用MD5值以及内部拼hashKey法,增加穷举破解的难度 /// </summary> /// <param name="argInput">输入的字符串</param> /// <returns>输出特殊处理过的MD5值</returns> public static string GetMd5Hash(string argInput) { string hashKey = "Kae@#$@!,.Js+{f>.294oE"; using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { string hashCode = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(argInput))) .Replace("-", "") + BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(hashKey))) .Replace("-", ""); return BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(hashCode))).Replace("-", ""); } }
/// <summary> /// MD5加密 返回纯字节 /// </summary> /// <param name="k"></param> /// <returns></returns> public static byte[] MD5Bytes(string sourceString) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] keyBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceString)); md5.Clear(); return keyBytes; }
static public string MD5Encoding(string Data) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] bdrr = System.Text.Encoding.UTF8.GetBytes(Data); byte[] barr = md5.ComputeHash(bdrr); return Convert.ToBase64String(barr); }
public static string Encrypt(String plainText ) { string encrypted = null; try { byte[] inputBytes = ASCIIEncoding.ASCII.GetBytes(plainText); byte[] pwdhash = null; MD5CryptoServiceProvider hashmd5; //generate an MD5 hash from the password. //a hash is a one way encryption meaning once you generate //the hash, you cant derive the password back from it. hashmd5 = new MD5CryptoServiceProvider(); pwdhash = hashmd5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(key)); hashmd5 = null; // Create a new TripleDES service provider TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider(); tdesProvider.Key = pwdhash; tdesProvider.Mode = CipherMode.ECB; encrypted = Convert.ToBase64String( tdesProvider.CreateEncryptor().TransformFinalBlock(inputBytes, 0, inputBytes.Length)); } catch(Exception e) { string str = e.Message; throw ; } return encrypted; }
/// <summary> 从路径获取文件的MD5 </summary> public static string GetMD5FromFile(string filePath) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); Security.Cryptography.MD5CryptoServiceProvider md5 = new Security.Cryptography.MD5CryptoServiceProvider(); byte[] md5byte = md5.ComputeHash(fs); int i, j; string md5Str = string.Empty; foreach (byte b in md5byte) { i = Convert.ToInt32(b); j = i >> 4; md5Str += Convert.ToString(j, 16); j = ((i << 4) & 0x00ff) >> 4; md5Str += Convert.ToString(j, 16); } fs.Close(); fs.Dispose(); return(md5Str); }
internal string Decrypt(string value) { MD5CryptoServiceProvider hashProvider = null; TripleDESCryptoServiceProvider provider = null; try { hashProvider = new MD5CryptoServiceProvider(); var hashPassPhrase = hashProvider.ComputeHash(Encoding.UTF8.GetBytes(passPhrase)); provider = new TripleDESCryptoServiceProvider(); provider.Key = hashPassPhrase; provider.Mode = CipherMode.ECB; provider.Padding = PaddingMode.PKCS7; var dataToEncrypt = Convert.FromBase64String(value); var decryptor = provider.CreateDecryptor(); var results = decryptor.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length); return Encoding.UTF8.GetString(results); } finally { if (provider != null) provider.Clear(); if (hashProvider != null) hashProvider.Clear(); } }
/// <summary> /// 创建签名 /// </summary> /// <param name="text">明文</param> /// <param name="merchantKey">商户密钥</param> /// <returns>签名</returns> public static string CreateSign(string text, string merchantKey) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(text + "&Key=" + merchantKey)); return BitConverter.ToString(hashBytes).Replace("-", "").ToUpper(); }
private string GetEasyPassSign(string guid, int rInt) { var key = string.Format("{0}:{1}:{2}", guid, DateTime.Now.ToString("yyyy-MM-dd"), rInt); var md5Provider = new System.Security.Cryptography.MD5CryptoServiceProvider(); var source = Encoding.UTF8.GetBytes(key.ToLower()); return(BitConverter.ToString(md5Provider.ComputeHash(source)).Replace("-", "")); }
/// <summary> /// 把一个字符串按MD5加密 /// </summary> /// <param name="s"></param> /// <returns></returns> public static string StringSec(string s) { MD5CryptoServiceProvider mycecWay = new System.Security.Cryptography.MD5CryptoServiceProvider(); string t = BitConverter.ToString(mycecWay.ComputeHash(System.Text.Encoding.UTF8.GetBytes(s))); t = t.Replace("-", ""); return(t); }
public string HashPassword(string password) { System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.UTF8.GetBytes(password); data = x.ComputeHash(data); String md5Hash = System.Text.Encoding.UTF8.GetString(data); return(md5Hash); }
//md5 加密 public static string MD5(String str) { System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.Default.GetBytes(str); byte[] result = md5.ComputeHash(data); string s = BitConverter.ToString(result); return(s); }
/// <summary> /// MD5 加密 /// </summary> /// <param name="inputstr"></param> /// <returns></returns> public string MD5(string inputstr) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); //加密Byte[]数组 byte[] data = System.Text.Encoding.UTF8.GetBytes(inputstr); byte[] result = md5.ComputeHash(data); //将加密后的数组转化为字段 return(BitConverter.ToString(result).Replace("-", "")); }
public static string encrypt(string x) { System.Security.Cryptography.MD5CryptoServiceProvider test123 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] data = System.Text.Encoding.ASCII.GetBytes(x); data = test123.ComputeHash(data); String md5Hash = System.Text.Encoding.ASCII.GetString(data); return(md5Hash); }
/// <summary> /// 计算文件的MD5值 /// </summary> /// <param name="MD5File">MD5签名文件字符数组</param> /// <param name="index">计算起始位置</param> /// <param name="count">计算终止位置</param> /// <returns>计算结果</returns> private static string MD5Buffer(byte[] MD5File, int index, int count) { System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash_byte = get_md5.ComputeHash(MD5File, index, count); string result = System.BitConverter.ToString(hash_byte); result = result.Replace("-", ""); return(result); }
/// <summary> /// 获取加密后的机器特征码 /// </summary> public static string GetEncryptMachinId() { string ret = ""; // C盘序列号 uint serNum = 0; uint maxCompLen = 0; StringBuilder VolLabel = new StringBuilder(256); // Label UInt32 VolFlags = new UInt32(); StringBuilder FSName = new StringBuilder(256); // File System Name long Ret = GetVolumeInformation("C:\\", VolLabel, (UInt32)VolLabel.Capacity, ref serNum, ref maxCompLen, ref VolFlags, FSName, (UInt32)FSName.Capacity); ret = Convert.ToString(serNum, 16).ToUpper(); { // 物理网卡Mac地址 ManagementClass mc; ManagementObjectCollection moc; mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); moc = mc.GetInstances(); string str = ""; foreach (ManagementObject mo in moc) { if ((bool)mo["IPEnabled"] == true) { str = mo["MacAddress"].ToString().Replace(':', '-'); ret += str; break; } } } // 加密 System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); string input = ret; byte[] hash_byte = md5.ComputeHash(Encoding.Default.GetBytes(ret)); ret = System.BitConverter.ToString(hash_byte); ret = ret.Replace("-", "").ToLower(); hash_byte = md5.ComputeHash(Encoding.Default.GetBytes(ret)); ret = System.BitConverter.ToString(hash_byte); ret = ret.Replace("-", "").ToLower(); return(ret); }
public static string MD5Encrypt(string strText) { MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(strText)); string strMd5 = BitConverter.ToString(result); strMd5 = strMd5.Replace("-", ""); return(strMd5);// System.Text.Encoding.Default.GetString(result); }
private String FileMd5(string filePath) { using (System.IO.FileStream FileCheck = System.IO.File.OpenRead(filePath)) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] md5Hash = md5.ComputeHash(FileCheck); return(BitConverter.ToString(md5Hash).Replace("-", "").ToLower()); } }
public static string MD5Hash(this string text) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); return(System.Text.RegularExpressions.Regex.Replace( BitConverter.ToString( md5.ComputeHash(ASCIIEncoding.Default.GetBytes(text)) ) , "-", "" )); }
/// <summary> /// Generates a simple MD5-Hash /// </summary> /// <param name="wert"></param> /// <returns></returns> public static String GenerateMD5(String wert) { byte[] bWert = Encoding.UTF8.GetBytes(wert); MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash = md5.ComputeHash(bWert); string md5Wert = BitConverter.ToString(hash).Replace("-", "").ToLower(); return(md5Wert); }
public static string md5_hash(byte[] bytes) { System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hash_byte = get_md5.ComputeHash(bytes); string resule = System.BitConverter.ToString(hash_byte); resule = resule.Replace("-", ""); return(resule); }
static public string GenMD5(string fn) { var md5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider(); var fs = new System.IO.FileStream(fn, FileMode.Open, FileAccess.Read); var arrbytHashValue = md5CSP.ComputeHash(fs); var strHashData = System.BitConverter.ToString(arrbytHashValue).Replace("-", ""); fs.Close(); return(strHashData); }
/// <summary> /// MD5加密 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string MD5(string str) { System.Security.Cryptography.MD5CryptoServiceProvider md5CSP = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] testEncrypt = System.Text.Encoding.Unicode.GetBytes(str); byte[] resultEncrypt = md5CSP.ComputeHash(testEncrypt); string testResult = System.Text.Encoding.Unicode.GetString(resultEncrypt); return(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5")); }
/// <summary> /// 获取指定文件的MD5码 /// </summary> /// <param name="FilePath">文件路径</param> /// <returns>文件MD5值</returns> public static string GetFileMd5(string FilePath) { byte[] data = File.ReadAllBytes(FilePath); //byte[] data = System.IO.File.ReadAllBytes(System.Web.HttpContext.Current.Request.MapPath(FilePath)); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] result = md5.ComputeHash(data); string Md5str = BitConverter.ToString(result).Replace("-", ""); return(Md5str); }
//GET RequestKey private static byte[] GetRequestKey(string aes_key, string timestamp) { //获取要加密的字段,并转化为Byte[]数组 byte[] data = System.Text.Encoding.UTF8.GetBytes(string.Format("{0}{1}", aes_key, timestamp).ToCharArray()); //建立加密服务 System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); //加密Byte[]数组 return(md5.ComputeHash(data)); //return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(aes_key + timestamp, "MD5").ToLower(); }
/// <summary> /// Decrypts provided string parameter /// </summary> public static bool IsMatch(string key, string apiLogin, string transactionID, decimal amount, string expected) { var unencrypted = string.Format("{0}{1}{2}{3}", key, apiLogin, transactionID, amount.ToString()); var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); var hashed = Regex.Replace(BitConverter.ToString(md5.ComputeHash(ASCIIEncoding.Default.GetBytes(unencrypted))), "-", ""); // And return it return(hashed.Equals(expected)); }
public byte[] HashByte(byte[] bytes) { // encrypt bytes System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(bytes); // Convert the encrypted bytes back to a string (base 16) return(hashBytes); }
public static string EncodingPassword(string password) { System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] hashedBytes; System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(password)); return(BitConverter.ToString(hashedBytes).Replace("-", "").ToLower()); }
public static string MD5Encrypt(Stream inStream) { using (System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider()) { inStream.Seek(0, SeekOrigin.Begin); byte[] hash_byte = get_md5.ComputeHash(inStream); string resule = System.BitConverter.ToString(hash_byte); resule = resule.Replace("-", "").ToLower(); return(resule); } }
public static string MD5(string Input) { CryptoLibrary.MD5 MD5 = new CryptoLibrary.MD5CryptoServiceProvider(); MD5.ComputeHash(System.Text.ASCIIEncoding.ASCII.GetBytes(Input)); System.Text.StringBuilder StringBuilder = new System.Text.StringBuilder(); for (int i = 0; i < MD5.Hash.Length; i++) { StringBuilder.Append(MD5.Hash[i].ToString("x2")); } return(StringBuilder.ToString()); }
/// <summary> /// Returns an hash (computed with MD5 algorithm) of the given string /// </summary> /// <param name="input">string to hash</param> /// <param name="printLowerCase">true to print the hexadecimal form in lower case</param> /// <returns></returns> public static string ComputeMD5HashSQLServerCompliant(this string password, bool printLowerCase = false) { if (password.IsNullOrWhiteSpaceOrEOF()) { password = string.Empty; } System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] binaryInput = Encoding.Unicode.GetBytes(password); byte[] hashOfInput = md5.ComputeHash(binaryInput); return(hashOfInput.PrintHexByteArray(printLowerCase)); }
/// <summary> /// 计算字符串的三次MD5 /// </summary> /// <param name="s" /></param> /// <returns></returns> private static String md5_3(String s) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s); bytes = md5.ComputeHash(bytes); bytes = md5.ComputeHash(bytes); bytes = md5.ComputeHash(bytes); md5.Clear(); string ret = ""; for (int i = 0; i < bytes.Length; i++) { ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0'); } return(ret.PadLeft(32, '0')); }
/// <summary> /// MD5加密 /// </summary> /// <param name="s">需要加密的字符串</param> /// <returns></returns> public static string EncryptMD5(string originalValue) { var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); var result = ""; if (!string.IsNullOrWhiteSpace(originalValue)) { result = BitConverter.ToString(md5.ComputeHash(UnicodeEncoding.UTF8.GetBytes(originalValue))).Replace("-", "").ToUpper(); } return(result); }
//private void KeyPress(object sender, KeyEventArgs e) //{ // if (e.Key == Key.Escape) // { // returnToFinalPage(sender, e); // } //} private void CheckPassword(object sender, RoutedEventArgs e) { try { string userPassword = userpassword.Password; byte[] data = System.Text.Encoding.ASCII.GetBytes(userPassword); data = hashConverter.ComputeHash(data); userPassword = System.Text.Encoding.ASCII.GetString(data); userPassword = Regex.Replace(userPassword, @"\t|\n|\r", ""); password = Regex.Replace(password, @"\t|\n|\r", ""); if (userPassword == password) { // NavigationWindow win = (NavigationWindow)Window.GetWindow(this); hostWatcher.EnableRaisingEvents = false; runningTimer.Stop(); Window appwindow = (Window)App.Current.MainWindow; var hwnd = new WindowInteropHelper(appwindow).Handle; SetWindowLongPtr(hwnd, GWL_STYLE, StartPage.getwindow); appwindow.UpdateLayout(); int getwin = GetWindowLong(hwnd, GWL_STYLE); string systemRest = (string)this.FindResource("SettingRestoredMessage"); SettingRestore(PasswordRequire.filePath, hostfile_location, restoreDNS); Xceed.Wpf.Toolkit.MessageBox.Show(systemRest); if (getwin != 382337024) { SetWindowLongPtr(hwnd, GWL_STYLE, StartPage.getwindow); } AdittionalOptions.httpserver.Dispose(); // Stopping HttpServer StartPage startObj = new StartPage(); this.NavigationService.Navigate(startObj); ShowsNavigationUI = false; // string appStatus = (string)this.FindResource("ApplicationInactive"); setNotifyIconText(PasswordRequire.notifyIcon, (string)FindResource("ApplicationInactive")); } else { //string passWrong = (string)this.FindResource("PasswordWrongMessage"); Xceed.Wpf.Toolkit.MessageBox.Show((string)this.FindResource("PasswordWrongMessage")); userpassword.Clear(); } } catch (Exception ex) { MessageBox.Show(ex.Message + ex.StackTrace); } }
/// <summary> /// 将字符串进行编码格式转换,并进行MD5加密,返回签名串,【dataStr:原文;codeType:字符串编码类型,指定gb2312或utf-8】 /// </summary> public static string GetMD5(string dataStr, string codeType) { System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(System.Text.Encoding.GetEncoding(codeType).GetBytes(dataStr)); System.Text.StringBuilder sb = new System.Text.StringBuilder(32); for (int i = 0; i < t.Length; i++) { sb.Append(t[i].ToString("x").PadLeft(2, '0')); } return(sb.ToString()); }
public static string GetMD5(string s) { var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); var result = ""; if (!string.IsNullOrWhiteSpace(s)) { result = BitConverter.ToString(md5.ComputeHash(UnicodeEncoding.UTF8.GetBytes(s.Trim()))); } return(result); }
public static byte[] GetMD5Encrypted(string password) { System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); UTF8Encoding encoder = new System.Text.UTF8Encoding(); System.IO.MemoryStream ms = new System.IO.MemoryStream(md5.ComputeHash(encoder.GetBytes(password))); byte[] hashedBytes = ms.ToArray(); return(hashedBytes); }