internal static byte[] EncodePapPassword(byte[] userPassBytes, byte[] requestAuthenticator, string sharedSecret) { if (userPassBytes.Length > 128) { throw new InvalidOperationException("the PAP password cannot be greater than 128 bytes..."); } byte[] encryptedPass = null; if (userPassBytes.Length % 16 == 0) { encryptedPass = new byte[userPassBytes.Length]; } else { encryptedPass = new byte[((userPassBytes.Length / 16) * 16) + 16]; } Array.Copy(userPassBytes, 0, encryptedPass, 0, userPassBytes.Length); for (int i = userPassBytes.Length; i < encryptedPass.Length; i++) { encryptedPass[i] = 0; } byte[] sharedSecretBytes = System.Text.Encoding.ASCII.GetBytes(sharedSecret); System.Security.Cryptography.MD5 md5; for (int chunk = 0; chunk < (encryptedPass.Length / 16); chunk++) { md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); md5.TransformBlock(sharedSecretBytes, 0, sharedSecretBytes.Length, sharedSecretBytes, 0); if (chunk == 0) { md5.TransformFinalBlock(requestAuthenticator, 0, requestAuthenticator.Length); } else { md5.TransformFinalBlock(encryptedPass, (chunk - 1) * 16, 16); } byte[] hash = md5.Hash; for (int i = 0; i < 16; i++) { int j = i + chunk * 16; encryptedPass[j] = (byte)(hash[i] ^ encryptedPass[j]); } } return(encryptedPass); }
byte[] IRunningHash.GetRunningHash() { var copy = new MD5CryptoServiceProvider(this); copy.TransformFinalBlock(empty, 0, 0); return(copy.Hash); }
public static string md5Hash(this Bitmap bitmap) { try { if (bitmap.isNull()) return null; //based on code snippets from http://dotnet.itags.org/dotnet-c-sharp/85838/ using (var strm = new MemoryStream()) { var image = new Bitmap(bitmap); bitmap.Save(strm, System.Drawing.Imaging.ImageFormat.Bmp); strm.Seek(0, 0); byte[] bytes = strm.ToArray(); var md5 = new MD5CryptoServiceProvider(); byte[] hashed = md5.TransformFinalBlock(bytes, 0, bytes.Length); string hash = BitConverter.ToString(hashed).ToLower(); md5.Clear(); image.Dispose(); return hash; } } catch (Exception ex) { ex.log("in bitmap.md5Hash"); return ""; } }
public void CalcHash() { using (var hash = new MD5CryptoServiceProvider()) { foreach (var xt in mXmitTaskList) { hash.TransformBlock(xt.xmitData, 0, xt.xmitData.Length, xt.xmitData, 0); } hash.TransformFinalBlock(new byte[0], 0, 0); mXmitDataHash = hash.Hash; } }
/// <summary> /// Gets the image URL for the gravatar with the given email /// </summary> /// <param name="email">The gravatar email</param> /// <param name="size">Optional size</param> /// <returns>The image URL</returns> public static string GetGravatarUrl(this UrlHelper helper, string email, int size = 0) { var input = UTF8Encoding.UTF8.GetBytes(email) ; var crypto = new MD5CryptoServiceProvider() ; var hash = Convert.ToBase64String(crypto.TransformFinalBlock(input, 0, input.Length)) ; crypto.Clear() ; return "http://www.gravatar.com/avatar/" + hash.ToLower() + (size > 0 ? "?s=" + size : "") ; }
public static byte[] encodePapPassword(byte[] userPassBytes,byte[] requestAuthenticator,string sharedSecret) { if (userPassBytes.Length > 128) throw new InvalidOperationException("the PAP password cannot be greater than 128 bytes..."); byte[] encryptedPass = null; if (userPassBytes.Length % 16 == 0) { encryptedPass = new byte[userPassBytes.Length]; } else { encryptedPass = new byte[((userPassBytes.Length / 16) * 16) + 16]; } System.Array.Copy(userPassBytes, 0, encryptedPass, 0, userPassBytes.Length); for(int i = userPassBytes.Length; i < encryptedPass.Length; i++) { encryptedPass[i] = 0; } byte[] sharedSecretBytes = System.Text.Encoding.ASCII.GetBytes(sharedSecret); System.Security.Cryptography.MD5 md5; for (int chunk = 0; chunk < (encryptedPass.Length / 16); chunk++) { md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); md5.TransformBlock(sharedSecretBytes, 0, sharedSecretBytes.Length, sharedSecretBytes, 0); if (chunk == 0) md5.TransformFinalBlock(requestAuthenticator, 0, requestAuthenticator.Length); else md5.TransformFinalBlock(encryptedPass, (chunk - 1) * 16, 16); byte[] hash = md5.Hash; for (int i = 0; i < 16; i++){ int j = i + chunk*16; encryptedPass[j] = (byte) (hash[i] ^ encryptedPass[j]); } } return encryptedPass; }
public byte[] CalcHash() { mRecvFragmentList = mRecvFragmentList.OrderBy(o => o.StartPos).ToList(); using (var hash = new MD5CryptoServiceProvider()) { foreach (var f in mRecvFragmentList) { hash.TransformBlock(f.Content, 0, f.Content.Length, f.Content, 0); } hash.TransformFinalBlock(new byte[0], 0, 0); byte[] result = new byte[HASH_BYTES]; Array.Copy(hash.Hash, result, HASH_BYTES); return result; } }
/// <summary> /// ���ļ�����MD5���� /// </summary> /// <param name="filePath"></param> public static void MD5File(string filePath) { FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); int bufferSize = 1048576; // ��������С��1MB byte[] buff = new byte[bufferSize]; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buff, 0, Convert.ToInt32(readSize)); // ��ȡһ�����ݵ������� if (offset + readSize < fs.Length) // �������һ�� { md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0); } else // ���һ�� { md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize)); } offset += bufferSize; } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString("X2")); } Console.WriteLine(sb.ToString()); Console.ReadLine(); }
/// <summary> /// MD5 hashing of the file using blocks, use 7Mb for chunks /// </summary> /// <param name="FileName">the file</param> /// <param name="blocksize">the chunk size</param> /// <returns></returns> public static string MD5HashFile(string FileName, int blocksize) { byte[] result; byte[] chunk = new byte[blocksize]; string HashString; System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); try { System.IO.Stream stream = System.IO.File.OpenRead(FileName); long filesize = stream.Length; while (filesize - stream.Position > chunk.Length) { stream.Read(chunk, 0, blocksize); md5.TransformBlock(chunk, 0, blocksize, chunk, 0); OnHashProgressed(new HashEventArgs(FileName, (int)(100 * stream.Position / filesize), stream.Position, filesize)); } int readCount = stream.Read(chunk, 0, (int)(filesize - stream.Position)); md5.TransformFinalBlock(chunk, 0, readCount); result = md5.Hash; System.Text.StringBuilder output = new System.Text.StringBuilder(2 + (result.Length * 2)); foreach (byte b in result) { output.Append(b.ToString("x2")); } HashString = output.ToString().ToUpper(); } catch (Exception ex) { chunk = null; result = null; GC.Collect(); return("0x0000"); } chunk = null; result = null; GC.Collect(); return(HashString); }
public static string GenerateChallengeRespose(string challengeToken, string productID, string productKey) { MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); byte[] bMD5Bytes = Encoding.Default.GetBytes(challengeToken + productKey); MD5.TransformFinalBlock(bMD5Bytes, 0, bMD5Bytes.Length); string strMD5Hash = To_Hex(MD5.Hash); ulong[] uMD5Ints = MD5_To_Int(strMD5Hash); string strCHLID = challengeToken + productID; strCHLID = strCHLID.PadRight(strCHLID.Length + (8 - (strCHLID.Length % 8)), '0'); ulong[] uCHLIDInts = CHLID_To_Int(strCHLID); ulong uKey = Create_Key(uMD5Ints, uCHLIDInts); ulong uPartOne = ulong.Parse(strMD5Hash.Substring(0, 16), NumberStyles.HexNumber); ulong uPartTwo = ulong.Parse(strMD5Hash.Substring(16, 16), NumberStyles.HexNumber); return String.Format("{0:x16}{1:x16}", uPartOne ^ uKey, uPartTwo ^ uKey); }
public static string getHash(string name) { string md5Final; int readsize = 64*1024; long read = 0; byte[] buffer = new byte[readsize*2]; MD5 md5 = new MD5CryptoServiceProvider(); using (var stream = new FileStream(name, FileMode.Open, FileAccess.Read)) { read = stream.Read(buffer, 0, readsize); stream.Seek(-readsize, SeekOrigin.End); read += stream.Read(buffer, readsize, readsize); md5.TransformFinalBlock(buffer, 0, buffer.Length); md5Final = String.Join("", md5.Hash.Select(x => x.ToString("x2"))); } return md5Final; }
/// <summary> /// 获取文件的MD5值 /// </summary> /// <param name="fileName"> 文件名 </param> /// <returns> 32位MD5 </returns> public static string GetFileMd5(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); const int bufferSize = 1024 * 1024; byte[] buffer = new byte[bufferSize]; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buffer, 0, (int)readSize); if (offset + readSize < fs.Length) { md5.TransformBlock(buffer, 0, (int)readSize, buffer, 0); } else { md5.TransformFinalBlock(buffer, 0, (int)readSize); } offset += bufferSize; } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); foreach (byte b in result) { sb.Append(b.ToString("X2")); } return sb.ToString(); }
private const int Md5ReadLen = 16 * 1024; // 一次读取长度 16384 = 16 * kb public static string GetMD5HashFromFile(string fileName) { byte[] buffer = new byte[Md5ReadLen]; int readLength = 0;//每次读取长度 var output = new byte[Md5ReadLen]; using (Stream inputStream = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (System.Security.Cryptography.HashAlgorithm hashAlgorithm = new System.Security.Cryptography.MD5CryptoServiceProvider()) { while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0) // 计算MD5 { hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0); } //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0) hashAlgorithm.TransformFinalBlock(buffer, 0, 0); var retVal = hashAlgorithm.Hash; var sb = new System.Text.StringBuilder(32); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } hashAlgorithm.Clear(); inputStream.Close(); return(sb.ToString()); } } }
public static string CreateQRY(string strProductID, string strProductKey, string strCHLData) { // First generate an MD5 hash object MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider(); byte[] bMD5Bytes = Encoding.Default.GetBytes(strCHLData + strProductKey); MD5.TransformFinalBlock(bMD5Bytes, 0, bMD5Bytes.Length); // Once we are done with that we should create 4 integers from the MD5 hash string strMD5Hash = To_Hex(MD5.Hash); ulong[] uMD5Ints = MD5_To_Int(strMD5Hash); // Create a new string from the ProdID and CHLData and padd with zero's, then convert it to ulongs :-) string strCHLID = strCHLData + strProductID; strCHLID = strCHLID.PadRight(strCHLID.Length + (8 - (strCHLID.Length % 8)), '0'); ulong[] uCHLIDInts = CHLID_To_Int(strCHLID); // Then fetch the key from the two arrays ulong uKey = Create_Key(uMD5Ints, uCHLIDInts); // And finally create the new hash :-) ulong uPartOne = ulong.Parse(strMD5Hash.Substring(0, 16), NumberStyles.HexNumber); ulong uPartTwo = ulong.Parse(strMD5Hash.Substring(16, 16), NumberStyles.HexNumber); return String.Format("{0:x16}{1:x16}", uPartOne ^ uKey, uPartTwo ^ uKey); }
protected void Page_PreRender(object sender, System.EventArgs e) { SharedBasePage requestPage = Page as SharedBasePage; Control root = this; HtmlGenericControl entry = new HtmlGenericControl("div"); if (SiteSecurity.GetUserByEmail(comment.AuthorEmail) == null) { entry.Attributes["class"] = "commentBoxStyle"; } else { entry.Attributes["class"] = "commentBoxStyle commentBoxAuthorStyle"; } root.Controls.Add(entry); HtmlGenericControl entryTitle = new HtmlGenericControl("div"); entryTitle.Attributes["class"] = "commentDateStyle"; //Add the unique anchor for each comment HtmlAnchor anchor = new HtmlAnchor(); anchor.Name = comment.EntryId; entryTitle.Controls.Add(anchor); if (requestPage.SiteConfig.AdjustDisplayTimeZone) { entryTitle.Controls.Add(new LiteralControl(requestPage.SiteConfig.GetConfiguredTimeZone().FormatAdjustedUniversalTime(comment.CreatedUtc))); } else { entryTitle.Controls.Add(new LiteralControl(comment.CreatedUtc.ToString("U") + " UTC")); } entry.Controls.Add(entryTitle); HtmlGenericControl entryBody = new HtmlGenericControl("div"); if (SiteSecurity.GetUserByEmail(comment.AuthorEmail) == null) { entryBody.Attributes["class"] = "commentBodyStyle"; } else { entryBody.Attributes["class"] = "commentBodyStyle commentBodyAuthorStyle"; } if (comment.Content != null) { entryBody.Controls.Add(new LiteralControl(Regex.Replace(comment.Content, "\n", "<br />"))); } if (!requestPage.HideAdminTools && SiteSecurity.IsInRole("admin")) { HtmlGenericControl spamStatus = new HtmlGenericControl("div"); spamStatus.Attributes["class"] = "commentSpamStateStyle"; spamStatus.InnerText = ApplicationResourceTable.GetSpamStateDescription(comment.SpamState); entryBody.Controls.Add(spamStatus); } entry.Controls.Add(entryBody); HtmlGenericControl footer = new HtmlGenericControl("div"); footer.Attributes["class"] = "commentBoxFooterStyle"; entry.Controls.Add(footer); if (requestPage.SiteConfig.CommentsAllowGravatar && String.IsNullOrEmpty(comment.AuthorEmail) == false) { string hash = ""; byte[] data, enc; data = Encoding.Default.GetBytes(comment.AuthorEmail.ToLowerInvariant()); using (MD5 md5 = new MD5CryptoServiceProvider()) { enc = md5.TransformFinalBlock(data, 0, data.Length); foreach (byte b in md5.Hash) { hash += Convert.ToString(b, 16).ToLower().PadLeft(2, '0'); } md5.Clear(); } string nogravpath = ""; if (requestPage.SiteConfig.CommentsGravatarNoImgPath != null) { if (requestPage.SiteConfig.CommentsGravatarNoImgPath != "") { if (requestPage.SiteConfig.CommentsGravatarNoImgPath.Substring(0, 4) == "http") { nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.CommentsGravatarNoImgPath); } else { nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.Root + requestPage.SiteConfig.CommentsGravatarNoImgPath); } } } if (String.IsNullOrEmpty(requestPage.SiteConfig.CommentsGravatarNoImgPath) == false) { if (requestPage.SiteConfig.CommentsGravatarNoImgPath == "identicon" || requestPage.SiteConfig.CommentsGravatarNoImgPath == "wavatar" || requestPage.SiteConfig.CommentsGravatarNoImgPath == "monsterid" || requestPage.SiteConfig.CommentsGravatarNoImgPath.Substring(0, 4) == "http") { nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.CommentsGravatarNoImgPath); } else { nogravpath = "&default=" + Server.UrlEncode(requestPage.SiteConfig.Root + requestPage.SiteConfig.CommentsGravatarNoImgPath); } } string gravborder = ""; if (requestPage.SiteConfig.CommentsGravatarBorder != null) { if (requestPage.SiteConfig.CommentsGravatarBorder != "") { gravborder = "&border=" + requestPage.SiteConfig.CommentsGravatarBorder; } } string gravsize = ""; if (requestPage.SiteConfig.CommentsGravatarSize != null) { if (requestPage.SiteConfig.CommentsGravatarSize != "") { gravsize = "&size=" + requestPage.SiteConfig.CommentsGravatarSize; } } string gravrating = ""; if (requestPage.SiteConfig.CommentsGravatarRating != null) { if (requestPage.SiteConfig.CommentsGravatarRating != "") { gravrating = "&rating=" + requestPage.SiteConfig.CommentsGravatarRating; } } HtmlGenericControl entryGRAVATAR = new HtmlGenericControl("span"); entryGRAVATAR.Attributes["class"] = "commentGravatarBlock"; entryGRAVATAR.InnerHtml = "<img class=\"commentGravatar\" src=\"http://www.gravatar.com/avatar.php?gravatar_id=" + hash + gravrating + gravsize + nogravpath + gravborder + "\"/>"; footer.Controls.Add(entryGRAVATAR); } string authorLink = null; if (comment.AuthorHomepage != null && comment.AuthorHomepage.Length > 0) { authorLink = FixUrl(comment.AuthorHomepage); } else if (comment.AuthorEmail != null && comment.AuthorEmail.Length > 0) { if (!requestPage.SiteConfig.SupressEmailAddressDisplay) { authorLink = "mailto:" + SiteUtilities.SpamBlocker(comment.AuthorEmail); } } if (authorLink != null) { HyperLink link = new HyperLink(); link.Attributes["class"] = "commentPermalinkStyle"; link.NavigateUrl = authorLink; link.Text = comment.Author; link.Attributes.Add("rel", "nofollow"); footer.Controls.Add(link); if (comment.OpenId) { System.Web.UI.WebControls.Image i = new System.Web.UI.WebControls.Image(); i.ImageUrl = "~/images/openid-icon-small.gif"; i.CssClass = "commentOpenId"; link.Controls.Add(i); Literal l = new Literal(); l.Text = comment.Author; link.Controls.Add(l); } } else { Label l = new Label(); l.Attributes["class"] = "commentPermalinkStyle"; l.Text = comment.Author; footer.Controls.Add(l); } if (!requestPage.SiteConfig.SupressEmailAddressDisplay) { if (comment.AuthorEmail != null && comment.AuthorEmail.Length > 0) { footer.Controls.Add(new LiteralControl(" | ")); HtmlGenericControl mailto = new HtmlGenericControl("span"); footer.Controls.Add(mailto); HyperLink link = new HyperLink(); link.CssClass = "commentMailToStyle"; link.NavigateUrl = "mailto:" + SiteUtilities.SpamBlocker(comment.AuthorEmail); link.Text = SiteUtilities.SpamBlocker(comment.AuthorEmail); mailto.Controls.Add(link); } } if (!requestPage.HideAdminTools && SiteSecurity.IsInRole("admin")) { if (!string.IsNullOrEmpty(comment.AuthorIPAddress)) { try { if (requestPage.SiteConfig.ResolveCommenterIP == true) { System.Net.IPHostEntry hostInfo = System.Net.Dns.GetHostEntry(comment.AuthorIPAddress); footer.Controls.Add( new LiteralControl(" (" + comment.AuthorIPAddress + " " + hostInfo.HostName + ") ")); } else { footer.Controls.Add(new LiteralControl(" (" + comment.AuthorIPAddress + ") ")); } } catch { footer.Controls.Add(new LiteralControl(" (" + comment.AuthorIPAddress + ") ")); } } footer.Controls.Add(new LiteralControl(" ")); // create delete hyperlink HyperLink deleteHl = new HyperLink(); deleteHl.CssClass = "deleteLinkStyle"; System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image(); img.CssClass = "deleteLinkImageStyle"; img.ImageUrl = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("deletebutton")).ToString(); img.BorderWidth = 0; deleteHl.Controls.Add(img); deleteHl.NavigateUrl = String.Format("javascript:deleteComment(\"{0}\", \"{1}\", \"{2}\")", Comment.TargetEntryId, Comment.EntryId, Comment.Author == null ? String.Empty : Comment.Author.Replace("\"", "\\\"")); ResourceManager resmgr = resmgr = ApplicationResourceTable.Get(); if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "deleteCommentScript")) { // add the javascript to allow deletion of the comment string scriptString = "<script type=\"text/javascript\" language=\"JavaScript\">\n"; scriptString += "function deleteComment(entryId, commentId, commentFrom)\n"; scriptString += "{\n"; scriptString += String.Format(" if(confirm(\"{0} \\n\\n\" + commentFrom))\n", resmgr.GetString("text_delete_confirm")); scriptString += " {\n"; scriptString += " location.href=\"deleteItem.ashx?entryid=\" + entryId + \"&commentId=\" + commentId\n"; scriptString += " }\n"; scriptString += "}\n"; scriptString += "</script>"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "deleteCommentScript", scriptString); } footer.Controls.Add(deleteHl); // create approve hyperlink, when a comment is not public or if its marked as spam if ((!Comment.IsPublic) || (Comment.SpamState == SpamState.Spam)) { HyperLink approveHl = new HyperLink(); approveHl.CssClass = "approveLinkStyle"; System.Web.UI.WebControls.Image okImg = new System.Web.UI.WebControls.Image(); okImg.CssClass = "approveImageStyle"; okImg.ImageUrl = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("okbutton-list")).ToString(); okImg.BorderWidth = 0; approveHl.Controls.Add(okImg); approveHl.NavigateUrl = String.Format("javascript:approveComment(\"{0}\", \"{1}\")", Comment.TargetEntryId, Comment.EntryId); if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "approveCommentScript")) { string approveScript = "<script type=\"text/javascript\" language=\"JavaScript\">\n"; approveScript += "function approveComment(entryId, commentId)\n"; approveScript += "{\n"; approveScript += " location.href=\"approveItem.ashx?entryid=\" + entryId + \"&commentId=\" + commentId\n"; approveScript += "}\n"; approveScript += "</script>"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "approveCommentScript", approveScript); } footer.Controls.Add(approveHl); } ISpamBlockingService spamBlockingService = requestPage.SiteConfig.SpamBlockingService; if ((spamBlockingService != null) && (comment.SpamState != SpamState.Spam)) { HyperLink reportSpamLink = new HyperLink(); reportSpamLink.CssClass = "approveLinkStyle"; System.Web.UI.WebControls.Image spamImg = new System.Web.UI.WebControls.Image(); spamImg.CssClass = "approveImageStyle"; spamImg.ImageUrl = new Uri(new Uri(SiteUtilities.GetBaseUrl(requestPage.SiteConfig)), requestPage.GetThemedImageUrl("reportspambutton")).ToString(); spamImg.BorderWidth = 0; reportSpamLink.Controls.Add(spamImg); reportSpamLink.NavigateUrl = String.Format("javascript:reportComment(\"{0}\", \"{1}\", \"{2}\")", Comment.TargetEntryId, Comment.EntryId, Comment.Author == null ? String.Empty : Comment.Author.Replace("\"", "\\\"")); string reportScript = "<script type=\"text/javascript\" language=\"JavaScript\">\n"; reportScript += "function reportComment(entryId, commentId, commentFrom)\n"; reportScript += "{\n"; reportScript += String.Format(" if(confirm(\"{0} \\n\\n\" + commentFrom))\n", resmgr.GetString("text_reportspam_confirm")); reportScript += " {\n"; reportScript += " location.href=\"deleteItem.ashx?report=true&entryid=\" + entryId + \"&commentId=\" + commentId\n"; reportScript += " }\n"; reportScript += "}\n"; reportScript += "</script>"; if (!Page.ClientScript.IsClientScriptBlockRegistered(this.GetType(), "reportCommentScript")) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "reportCommentScript", reportScript); } footer.Controls.Add(reportSpamLink); } } }
public static CipherSuite InitializeCipherSuite(byte[] master, byte[] clientrnd, byte[] serverrnd, CipherDefinition definition, ConnectionEnd entity) { CipherSuite ret = new CipherSuite(); SymmetricAlgorithm bulk = (SymmetricAlgorithm)Activator.CreateInstance(definition.BulkCipherAlgorithm); if (definition.BulkIVSize > 0) bulk.Mode = CipherMode.CBC; bulk.Padding = PaddingMode.None; bulk.BlockSize = definition.BulkIVSize * 8; // get the keys and IVs byte[] client_mac, server_mac, client_key, server_key, client_iv, server_iv; Ssl3DeriveBytes prf = new Ssl3DeriveBytes(master, clientrnd, serverrnd, false); client_mac = prf.GetBytes(definition.HashSize); server_mac = prf.GetBytes(definition.HashSize); client_key = prf.GetBytes(definition.BulkKeySize); server_key = prf.GetBytes(definition.BulkKeySize); client_iv = prf.GetBytes(definition.BulkIVSize); server_iv = prf.GetBytes(definition.BulkIVSize); prf.Dispose(); if (definition.Exportable) { // make some extra modifications if the keys are exportable MD5 md5 = new MD5CryptoServiceProvider(); md5.TransformBlock(client_key, 0, client_key.Length, client_key, 0); md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0); md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length); client_key = new byte[definition.BulkExpandedSize]; Buffer.BlockCopy(md5.Hash, 0, client_key, 0, client_key.Length); md5.Initialize(); md5.TransformBlock(server_key, 0, server_key.Length, server_key, 0); md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0); md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length); server_key = new byte[definition.BulkExpandedSize]; Buffer.BlockCopy(md5.Hash, 0, server_key, 0, server_key.Length); md5.Initialize(); md5.TransformBlock(clientrnd, 0, clientrnd.Length, clientrnd, 0); md5.TransformFinalBlock(serverrnd, 0, serverrnd.Length); client_iv = new byte[definition.BulkIVSize]; Buffer.BlockCopy(md5.Hash, 0, client_iv, 0, client_iv.Length); md5.Initialize(); md5.TransformBlock(serverrnd, 0, serverrnd.Length, serverrnd, 0); md5.TransformFinalBlock(clientrnd, 0, clientrnd.Length); server_iv = new byte[definition.BulkIVSize]; Buffer.BlockCopy(md5.Hash, 0, server_iv, 0, server_iv.Length); md5.Clear(); } // generate the cipher objects if (entity == ConnectionEnd.Client) { ret.Encryptor = bulk.CreateEncryptor(client_key, client_iv); ret.Decryptor = bulk.CreateDecryptor(server_key, server_iv); ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac); ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac); } else { ret.Encryptor = bulk.CreateEncryptor(server_key, server_iv); ret.Decryptor = bulk.CreateDecryptor(client_key, client_iv); ret.LocalHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, server_mac); ret.RemoteHasher = new Ssl3RecordMAC(definition.HashAlgorithmType, client_mac); } // clear sensitive data Array.Clear(client_mac, 0, client_mac.Length); Array.Clear(server_mac, 0, server_mac.Length); Array.Clear(client_key, 0, client_key.Length); Array.Clear(server_key, 0, server_key.Length); Array.Clear(client_iv, 0, client_iv.Length); Array.Clear(server_iv, 0, server_iv.Length); return ret; }
protected static byte[] ComputeMD5(byte[] key, byte[] salt, int saltHashRounds = DefaultSaltHashRounds) { // TODO: Test that saltHashRounds >= 1 using (var md5 = new MD5CryptoServiceProvider()) { // Hash key md5.TransformBlock(key, 0, key.Length, null, 0); // Hash salt (saltHashRounds-1) times for(int i = 1; i < saltHashRounds; i++) { md5.TransformBlock(salt, 0, salt.Length, null, 0); } // Final salt hash iteration md5.TransformFinalBlock(salt, 0, salt.Length); return md5.Hash; } }
private void GenerateStaticContent () { resources.Clear (); var random = new Random (); var root = "/tmp/hyena-download-test-server"; try { Directory.Delete (root, true); } catch { } Directory.CreateDirectory (root); for (int i = 0; i < ResourceCount; i++) { var md5 = new MD5CryptoServiceProvider (); var resource = new Resource () { Path = Path.Combine (root, i.ToString ()), Length = random.Next (MinResourceSize, MaxResourceSize + 1) }; if (Debug) Console.WriteLine (); using (var stream = File.OpenWrite (resource.Path)) { var buffer = new byte[32 << 10]; long written = 0; long remaining; while ((remaining = resource.Length - written) > 0) { var buffer_length = remaining > buffer.Length ? (int)buffer.Length : (int)remaining; random.NextBytes (buffer); stream.Write (buffer, 0, buffer_length); written += buffer_length; md5.TransformBlock (buffer, 0, buffer_length, null, 0); if (Debug) Console.Write ("\rCreating resource: {0} ({1:0.00} MB): [{2}/{3}] {4:0.0}% ", resource.Path, resource.Length / 1024.0 / 1024.0, i + 1, ResourceCount, written / (double)resource.Length * 100.0); } md5.TransformFinalBlock (buffer, 0, 0); resource.Checksum = BitConverter.ToString (md5.Hash).Replace ("-", String.Empty).ToLower (); } resources.Add (resource); } }
/// <summary> /// SSH1 RSA challenge /// </summary> /// <param name="e">public exponent</param> /// <param name="n">public modulus</param> /// <param name="encryptedChallenge">encrypted challenge</param> /// <param name="sessionId">session id</param> /// <param name="responseType">response type</param> private void SSH1IRSAChallenge(BigInteger e, BigInteger n, BigInteger encryptedChallenge, byte[] sessionId, uint responseType) { if (responseType != 1) { SendFailure(); return; } SSH1UserAuthKey key = SSH1FindKey(e, n); if (key == null) { SendFailure(); return; } BigInteger challenge = key.decryptChallenge(encryptedChallenge); byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).GetBytes(); byte[] hash; using (var md5 = new MD5CryptoServiceProvider()) { md5.TransformBlock(rawchallenge, 0, rawchallenge.Length, rawchallenge, 0); md5.TransformFinalBlock(sessionId, 0, sessionId.Length); hash = md5.Hash; } Send( new OpenSSHAgentForwardingMessage(OpenSSHAgentForwardingMessageType.SSH_AGENT_RSA_RESPONSE) .Write(hash) ); }
public static string MD5Decrypt(string strText) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] result = md5.TransformFinalBlock(System.Text.Encoding.Default.GetBytes(strText), 0, strText.Length); return System.Text.Encoding.UTF8.GetString(result); }
public byte[] Encode(byte[] data) { byte[] buffer = new byte[data.Length + 128]; using (MemoryStream stream = new MemoryStream(data)) { int num; MemoryStream stream2 = new MemoryStream(buffer); RSACryptoServiceProvider key = new RSACryptoServiceProvider(1024); byte[] buffer2 = new byte[86]; byte[] outputBuffer = new byte[86]; HashAlgorithm algorithm = new MD5CryptoServiceProvider(); algorithm.Initialize(); while ((num = stream.Read(buffer2, 0, 86)) == 86) { algorithm.TransformBlock(buffer2, 0, 86, outputBuffer, 0); stream2.Write(buffer2, 0, buffer2.Length); } buffer2 = algorithm.TransformFinalBlock(buffer2, 0, num); stream2.Write(buffer2, 0, buffer2.Length); RSAParameters parameters = new RSAParameters(); parameters.D = (byte[])this.rsaParameters.D.Clone(); parameters.DP = (byte[])this.rsaParameters.DP.Clone(); parameters.DQ = (byte[])this.rsaParameters.DQ.Clone(); parameters.Exponent = (byte[])this.rsaParameters.Exponent.Clone(); parameters.InverseQ = (byte[])this.rsaParameters.InverseQ.Clone(); parameters.Modulus = (byte[])this.rsaParameters.Modulus.Clone(); parameters.P = (byte[])this.rsaParameters.P.Clone(); parameters.Q = (byte[])this.rsaParameters.Q.Clone(); key.ImportParameters(parameters); AsymmetricSignatureFormatter formatter = new RSAPKCS1SignatureFormatter(key); formatter.SetHashAlgorithm("MD5"); outputBuffer = formatter.CreateSignature(algorithm.Hash); stream2.Write(outputBuffer, 0, outputBuffer.Length); stream2.Close(); stream.Close(); } return buffer; }
void HashTimer() { byte[] inArray1 = new byte[24]; byte[] inArray2 = new byte[30000*sizeof(double)]; int i; for (i = 0; i < 24; i++) inArray1[i] = (byte)(23 + i*2); MemoryStream binStream = new MemoryStream(inArray2); BinaryWriter binWriter = new BinaryWriter(binStream); for (i = 0; i < 30000; i++) binWriter.Write(i * (double)2.2); DateTime timerStart = DateTime.Now; for (i = 0; i < nIter; i++) { MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); md5Hasher.TransformBlock(inArray1, 0, inArray1.Length, inArray1, 0); md5Hasher.TransformFinalBlock(inArray2, 0, inArray2.Length); byte[] hash1 = md5Hasher.Hash; } DateTime timerEnd = DateTime.Now; TimeSpan timerDiff = timerEnd - timerStart; TimeLabelBlob.Content = String.Format("ChkSum --- Iterations: {0}; Duration: {1:hh\\:mm\\:ss\\.f}", i, timerDiff); i = 3; }
//RSA authentication private void DoRSAChallengeResponse() { //read key SSH1UserAuthKey key = new SSH1UserAuthKey(_param.IdentityFile, _param.Password); Transmit( new SSH1Packet(SSH1PacketType.SSH_CMSG_AUTH_RSA) .WriteBigInteger(key.PublicModulus) ); TraceTransmissionEvent(SSH1PacketType.SSH_CMSG_AUTH_RSA, "RSA challenge-reponse"); DataFragment response = ReceivePacket(); SSH1DataReader reader = new SSH1DataReader(response); SSH1PacketType pt = (SSH1PacketType) reader.ReadByte(); if (pt == SSH1PacketType.SSH_SMSG_FAILURE) throw new SSHException(Strings.GetString("ServerRefusedRSA")); else if (pt != SSH1PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE) throw new SSHException(String.Format(Strings.GetString("UnexpectedResponse"), pt)); TraceReceptionEvent(SSH1PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE, "received challenge"); //creating challenge BigInteger challenge = key.decryptChallenge(reader.ReadMPInt()); byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).GetBytes(); //building response byte[] hash; using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { md5.TransformBlock(rawchallenge, 0, rawchallenge.Length, rawchallenge, 0); md5.TransformFinalBlock(_sessionID, 0, _sessionID.Length); hash = md5.Hash; } Transmit( new SSH1Packet(SSH1PacketType.SSH_CMSG_AUTH_RSA_RESPONSE) .Write(hash) ); TraceReceptionEvent(SSH1PacketType.SSH_CMSG_AUTH_RSA_RESPONSE, "received response"); }
public string ComputeMD5() { MD5 md5 = new MD5CryptoServiceProvider(); byte[] hash = null; if (NumberOfFrames == 1) { byte[] frame = GetFrameDataU8(0); hash = md5.ComputeHash(frame); } else { for (int i = 0; i < NumberOfFrames; i++) { byte[] frame = GetFrameDataU8(i); if (i < (NumberOfFrames - 1)) md5.TransformBlock(frame, 0, frame.Length, frame, 0); else md5.TransformFinalBlock(frame, 0, frame.Length); } hash = md5.Hash; } return BitConverter.ToString(hash).Replace("-", ""); }
public static string AnyscMD5(string filepath, ProgressBar pBar, Label lab) { FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read); int bufferSize = 1048576; // 缓冲区大小,1MB byte[] buff = new byte[bufferSize]; double blockcount = Math.Ceiling(fs.Length / Convert.ToDouble(bufferSize)); if (pBar.InvokeRequired == true) { SetText LSetText = new SetText(DoSetText); SetValue PSetValue = new SetValue(DoSetMax); pBar.Invoke(PSetValue, new Object[] { pBar, Convert.ToInt32(blockcount) }); lab.Invoke(LSetText, new Object[] { lab, Convert.ToString(0) + "%" }); } int i = 1; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buff, 0, Convert.ToInt32(readSize)); // 读取一段数据到缓冲区 if (offset + readSize < fs.Length) // 不是最后一块 { md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0); } else // 最后一块 { md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize)); } offset += bufferSize; if (pBar.InvokeRequired == true) { SetValue PSetValue = new SetValue(DoSetValue); SetText LSetText = new SetText(DoSetText); pBar.Invoke(PSetValue, new Object[] { pBar, Convert.ToInt32(i) }); lab.Invoke(LSetText, new Object[] { lab, Convert.ToString(Math.Ceiling((double)(i / blockcount) * 100)) + "%" }); i++; Application.DoEvents(); } } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); for (int j = 0; j < result.Length; j++) { sb.Append(result[j].ToString("x2")); } return sb.ToString(); }
/// <summary> /// 生成某个文件的MD5 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string GenMD5(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); int bufferSize = 1048576; // 缓冲区大小,1MB byte[] buff = new byte[bufferSize]; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); md5.Initialize(); long offset = 0; while (offset < fs.Length) { long readSize = bufferSize; if (offset + readSize > fs.Length) { readSize = fs.Length - offset; } fs.Read(buff, 0, Convert.ToInt32(readSize)); // 读取一段数据到缓冲区 if (offset + readSize < fs.Length) // 不是最后一块 { md5.TransformBlock(buff, 0, Convert.ToInt32(readSize), buff, 0); } else // 最后一块 { md5.TransformFinalBlock(buff, 0, Convert.ToInt32(readSize)); } offset += bufferSize; } fs.Close(); byte[] result = md5.Hash; md5.Clear(); StringBuilder sb = new StringBuilder(32); for (int i = 0; i < result.Length; i++) { sb.Append(result[i].ToString("X2")); } return sb.ToString(); }
public static Byte[] CRAM_MD5_(String Token, String Login, String Password) { var token = Token. ToUTF8Bytes(); var password = Password.ToUTF8Bytes(); var ipad = new Byte[64]; var opad = new Byte[64]; var startIndex = 0; var length = token.Length; // see also: http://tools.ietf.org/html/rfc2195 - 2. Challenge-Response Authentication Mechanism (CRAM) // http://tools.ietf.org/html/rfc2104 - 2. Definition of HMAC #region Copy the password into inner/outer padding and XOR it accordingly if (password.Length > ipad.Length) { var HashedPassword = new MD5CryptoServiceProvider().ComputeHash(password); Array.Copy(HashedPassword, ipad, HashedPassword.Length); Array.Copy(HashedPassword, opad, HashedPassword.Length); } else { Array.Copy(password, ipad, password.Length); Array.Copy(password, opad, password.Length); } for (var i = 0; i < ipad.Length; i++) { ipad[i] ^= 0x36; opad[i] ^= 0x5c; } #endregion #region Calculate the inner padding byte[] digest; using (var MD5 = new MD5CryptoServiceProvider()) { MD5.TransformBlock (ipad, 0, ipad.Length, null, 0); MD5.TransformFinalBlock(token, startIndex, length); digest = MD5.Hash; } #endregion #region Calculate the outer padding // oPAD (will use iPAD digest!) using (var MD5 = new MD5CryptoServiceProvider()) { MD5.TransformBlock (opad, 0, opad.Length, null, 0); MD5.TransformFinalBlock(digest, 0, digest.Length); digest = MD5.Hash; } #endregion // result := login[space]digest return Login.ToUTF8Bytes(). Concat(new Byte[1] { 0x20 }). Concat(digest.ToHexString().ToUTF8Bytes()). ToArray(); }
/// <summary> /// Create the next upload message. /// </summary> private void CreateUploadMsg(MD5CryptoServiceProvider md5Hasher, out AnpMsg m, out List<UInt64> CompletedArray) { m = Share.CreateTransferMsg(KAnpType.KANP_CMD_KFS_PHASE_2); CompletedArray = new List<UInt64>(); // Add the number of submessages field. It will be updated later. m.AddUInt32(0); // Count the number of submessages. int nbSub = 0; // Loop until the message is full or we run out of files to upload. while (m.PayloadSize() < MAX_UPLOAD_SIZE && UploadIndex != FileArray.Length) { KfsUploadBatchFile ubf = FileArray[UploadIndex]; // The transfer of the current file was denied by the // server during phase 1. Do not attempt to talk about // it in phase 2. if (ubf.Status == BatchStatus.Error) { UploadNextFile(); continue; } // The transfer of the current file has been cancelled. Add an // abort submessage and pass to the next file. if (ubf.Status == BatchStatus.Cancelled) { m.AddUInt32(2); m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_ABORT); nbSub++; UploadNextFile(); continue; } // The current file is closed. Open the file and set the // remaining size. if (UploadedFile == null) { Debug.Assert(ubf.Status == BatchStatus.Queued); ubf.Status = BatchStatus.Started; UploadedFile = new FileStream(ubf.TransferPath, FileMode.Open, FileAccess.Read, FileShare.Read); RemainingSize = UploadedFile.Length; md5Hasher.Initialize(); } // Add a chunk submessage. if (RemainingSize > 0) { Debug.Assert(ubf.Status == BatchStatus.Started); // Compute the chunk size. UInt32 chunkSize = Math.Max(MIN_UPLOAD_CHUNK_SIZE, MAX_UPLOAD_SIZE - m.PayloadSize()); chunkSize = (UInt32)Math.Min((Int64)chunkSize, RemainingSize); RemainingSize -= chunkSize; // Read the chunk. byte[] chunkData = new byte[chunkSize]; UploadedFile.Read(chunkData, 0, (Int32)chunkSize); // Update the hash. md5Hasher.TransformBlock(chunkData, 0, (int)chunkSize, chunkData, 0); // Add the chunk submessage. m.AddUInt32(3); m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_CHUNK); m.AddBin(chunkData); nbSub++; } // Add a commit submessage, remember that the transfer of the file // is being completed in this message and pass to the next file. if (RemainingSize == 0) { Debug.Assert(ubf.Status == BatchStatus.Started); ubf.Status = BatchStatus.Done; // Update the hash. This call is required; Microsoft sucks. md5Hasher.TransformFinalBlock(new byte[0], 0, 0); m.AddUInt32(3); m.AddUInt32(KAnpType.KANP_KFS_SUBMESSAGE_COMMIT); m.AddBin(md5Hasher.Hash); nbSub++; CompletedArray.Add(ubf.OrderID); UploadNextFile(); } } // Update the number of submessages. m.Elements[0].UInt32 = (UInt32)nbSub; // If there are no submessages, don't bother sending the message. if (nbSub == 0) m = null; }
private static byte[] OpenSSHPassphraseToKey(string passphrase, byte[] iv, int length) { const int HASH_SIZE = 16; const int SALT_SIZE = 8; MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] pp = Encoding.UTF8.GetBytes(passphrase); byte[] buf = new byte[((length + HASH_SIZE - 1) / HASH_SIZE) * HASH_SIZE]; int offset = 0; while (offset < length) { if (offset > 0) md5.TransformBlock(buf, 0, offset, null, 0); md5.TransformBlock(pp, 0, pp.Length, null, 0); md5.TransformFinalBlock(iv, 0, SALT_SIZE); Buffer.BlockCopy(md5.Hash, 0, buf, offset, HASH_SIZE); offset += HASH_SIZE; md5.Initialize(); } md5.Clear(); byte[] key = new byte[length]; Buffer.BlockCopy(buf, 0, key, 0, length); return key; }
//void WriteArrayTest() //{ // int i; // double[] valArray = new double[nVals]; // for (i = 0; i < nVals; i++) // valArray[i] = i * 3; // for (i = 0; i < nIter; i++) // { // int id = ctsLib.WriteParametersRegularUnsafe(connNumber, "RunOutputTimeSeries", "OutputTimeSeriesTraces", // 3, 1, nVals, StartDate, // new String[6] { "RunGUID", "VariableType", "VariableName", "TimeSeriesType", "RunElementGUID", "Unit_Id" }, // new String[6] { "'EF8A01FE-C250-429C-A3AF-160076DE142B'", "'E'", "'D'", "1", "'EF8A01FE-C250-429C-A3AF-160076DE142B'", "1" }); // for (int t = 1; t <= 3; t++) // ctsLib.WriteTraceRegularUnsafe(connNumber, "RunOutputTimeSeries", "OutputTimeSeriesTraces", // id, t, valArray); // } //} void HashTest() { byte[] inArray1 = new ASCIIEncoding().GetBytes("PartA"); byte[] inArray2 = new ASCIIEncoding().GetBytes("PartB"); byte[] inArray3 = new ASCIIEncoding().GetBytes("PartAPartC"); byte[] hash1 =new byte[16], hash2 = new byte[16]; MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); md5Hasher.TransformBlock(inArray1, 0, inArray1.Length, inArray1, 0); md5Hasher.TransformFinalBlock(inArray2, 0, inArray2.Length); hash1 = md5Hasher.Hash; md5Hasher = new MD5CryptoServiceProvider(); md5Hasher.TransformFinalBlock(inArray3, 0, inArray3.Length); hash2 = md5Hasher.Hash; }