public static string CalcMd5Hash(MD5 md5, string filePath) { byte[] hash; using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { hash = md5.ComputeHash(stream); } return BitConverter.ToString(hash).Replace("-", ""); }
private static void GenerateMD5() { if (md5Hash == null) { md5Hash = MD5.Create(); } }
static Map() { #if HASH hash = MD5.Create(); #endif NameMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); }
protected void Page_Load(object sender, EventArgs e) { try { string user=Request.QueryString["user"].ToString(); string pass = Request.QueryString["pass"].ToString(); MD5 EncodeMDS = new MD5(); DataSet ds = new DataSet(); UserManagerSystem UserManage = new UserManagerSystem(); ds=UserManage.GetUserAccount(user); if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { string PassUser = ds.Tables[0].Rows[0]["password"].ToString(); if (EncodeMDS.Verify(pass, PassUser)) { isOk = "ok"; string[] userAcount = new string[3]; userAcount[0] = ds.Tables[0].Rows[0]["id"].ToString(); userAcount[1] = ds.Tables[0].Rows[0]["UserName"].ToString(); userAcount[2] = ds.Tables[0].Rows[0]["ContactName"].ToString(); Session["infoUser"] = userAcount; } } } } catch (Exception ex) { Console.Write(ex.ToString()); } Response.Write(isOk); }
static public string GetMd5String(String source) { // Create the hash value from the array of bytes. MD5 md = new MD5(); byte[] hash = md.ComputeHash(source.ToByteArray()); return hash.ToHexString(); }
public void CalculateMD5Incremental(byte[] pBuf, int bytesRead) { if (md5Incremental == null) md5Incremental = MD5.Create(); dummy = pBuf; md5Incremental.TransformBlock(pBuf, 0, bytesRead, null, 0); }
public static void Main() { var triplet = new Regex(@"(.)\1\1"); md5 = MD5.Create(); salt = Console.ReadLine(); int keysFound = 0;; int index = -1; while (keysFound < 64) { index++; string hash = GetHash(index); Match match = triplet.Match(hash); if (match.Success) { char letter = match.Groups[0].Value[0]; var fiveOfThem = new Regex(new String(letter, 5)); for (int j = index + 1; j <= index + 1000; j++) { if (fiveOfThem.IsMatch(GetHash(j))) { keysFound++; break; } } } hashCache.Remove(index); } Console.WriteLine(index); }
public void EncodeTest() { const string data = "i am testing"; MD5 md5 = new MD5(); var result = md5.Encode(data); Assert.IsTrue(result == "C6BD2686D765C25433A11810493987BD"); }
public FileSystemProvider(string path = null) { this.md5 = MD5.Create(); this.binaryFormatter = new BinaryFormatter(); this.InitializeDirectories(path); this.InitializeMetaData(); this.CheckHashes(); }
// upload public async Task<InputFile> UploadFile(string filename, Stream stream, FileUploadProcessHandler handler) { TLApi api = await session.GetFileSessionMain(); long fileId = Helpers.GenerateRandomLong(); MD5 hash = new MD5(); if(stream.Length < 128*1024) { handler(0.0f); byte[] data = new byte[stream.Length]; stream.Read(data, 0, (int) stream.Length); bool result = await api.upload_saveFilePart(fileId, 0, data); //while(result != true) { // result = await api.upload_saveFilePart(fileId, 0, data); //} hash.Update(data); handler(1.0f); return TL.inputFile(fileId, 1, filename, hash.FinalString()); } bool big = stream.Length > 10*1024*1024; float allStreamLength = stream.Length; int chunkSize = 128*1024; int chunkCount = (int) (stream.Length/chunkSize); int lastChunkSize = (int) (stream.Length - chunkSize*chunkCount); int allChunksCount = chunkCount + (lastChunkSize != 0 ? 1 : 0); for(int i = 0; i < chunkCount; i++) { handler((float) i*(float) chunkSize/allStreamLength); byte[] data = new byte[chunkSize]; stream.Read(data, 0, chunkSize); bool result = big ? await api.upload_saveBigFilePart(fileId, i, allChunksCount, data) : await api.upload_saveFilePart(fileId, i, data); //while(result != true) { // result = await api.upload_saveFilePart(fileId, i, data); //} hash.Update(data); } if(lastChunkSize != 0) { handler((float) chunkCount*(float) chunkSize/allStreamLength); byte[] lastChunkData = new byte[lastChunkSize]; stream.Read(lastChunkData, 0, lastChunkSize); bool lastChunkResult = big ? await api.upload_saveBigFilePart(fileId, chunkCount, allChunksCount, lastChunkData) : await api.upload_saveFilePart(fileId, chunkCount, lastChunkData); //while(lastChunkResult != true) { // lastChunkResult = await api.upload_saveFilePart(fileId, chunkCount, lastChunkData); //} hash.Update(lastChunkData); } handler(1.0f); return TL.inputFile(fileId, allChunksCount, filename, hash.FinalString()); }
public static string GetHash(MD5 hash, string input) { StringBuilder result = new StringBuilder(); byte[] data = hash.ComputeHash(Encoding.UTF8.GetBytes(input)); for (int i = 0; i < data.Length; i++) { result.Append(data[i].ToString("x2")); } return result.ToString(); }
public static string GetMd5Hash(MD5 md5Hash, string input) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); }
/** * Clear this helper class.. * * @param void. * @return void. */ public void Clear() { if (null == m_cMd5) { return; } m_cMd5.Clear(); m_cMd5 = null; }
/// <summary> /// Verify a hash against a string. /// </summary> /// <param name="md5Hash"></param> /// <param name="input"></param> /// <param name="hash"></param> /// <returns></returns> static bool VerifyMD5Hash(MD5 md5Hash, string input, string hash) { // Hash the input. string hashOfInput = GetMD5Hash(md5Hash, input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; return comparer.Compare(hashOfInput, hash) == 0; }
public static bool VerifyHash(MD5 hash, string input, string hashString) { PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Input String: {0}", input); PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Received Hash: {0}", hashString); string hashString1 = GetHash(hash, input); PTR3Core.LOG.Log(MsgStatusEnum.MS_Info, "Calculated Hash: {0}", hashString1); StringComparer comparer = StringComparer.OrdinalIgnoreCase; return comparer.Compare(hashString1, hashString) == 0; }
public override Stream CreateFileStream(string uploadFileName) { UploadFileName = uploadFileName; FileStream stream = new FileStream(m_TempFilePath, FileMode.CreateNew); m_UploadFileMD5 = MD5CryptoServiceProvider.Create(); return new CryptoStream(stream, m_UploadFileMD5, CryptoStreamMode.Write); }
public NefitEncryption(string serial, string access, string password) { _rijndael = new RijndaelManaged(); _md5 = MD5.Create(); _rijndael.Mode = CipherMode.ECB; _rijndael.Padding = PaddingMode.Zeros; _chatKey = GenerateKey(_chat, access, password); //_emailKey = GenerateKey(_email, serial, "gservice_smtp"); //_alarmKey = GenerateKey(_alarm, serial, "gservice_alarm"); }
//public static ImageSource ToImageSource(this Icon icon) //{ // ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon( // icon.Handle, // Int32Rect.Empty, // BitmapSizeOptions.FromEmptyOptions()); // return imageSource; //} public static string GetMd5Hash(MD5 md5Hash, string input) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); foreach (byte t in data) { sBuilder.Append(t.ToString("x2")); } return sBuilder.ToString(); }
private static string GetMd5Hash(MD5 md5Hash, string input) { byte[] array = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < array.Length; i++) { stringBuilder.Append(array[i].ToString("x2")); } return stringBuilder.ToString(); }
private string GetMD5HashCode(MD5 md5Hash, User user) { byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(user.Email + DateTime.UtcNow.ToString() + user.Password)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); }
public static string GetHash(MD5 crypto, string value) { byte[] hashByte = crypto.ComputeHash(Encoding.UTF8.GetBytes(value)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < hashByte.Length; i++) { sBuilder.Append(hashByte[i].ToString("x2")); } return sBuilder.ToString(); }
// Verify a hash against a string. public static bool VerifyMd5Hash(MD5 md5Hash, string src, string hash) { // Hash the input. string hashOfInput = GetMd5Hash(md5Hash, src); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; return 0 == comparer.Compare(hashOfInput, hash); }
private string GetMd5Hash(MD5 md5Hash, Stream inputStream) { byte[] data = md5Hash.ComputeHash(inputStream); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); }
static string GetMd5Hash(MD5 md5Hash, string input) { if (string.IsNullOrEmpty(input)) return ""; var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); var sBuilder = new StringBuilder(); for (var i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); }
public static bool VerifyMD5Hash(MD5 md5Hash, byte[] input, string hash) { string hashOfInput = GetMD5Hash(md5Hash, input); StringComparer comparer = StringComparer.OrdinalIgnoreCase; if (0 == comparer.Compare(hashOfInput, hash)) return true; else return false; }
/// <summary> /// Accepts a JSON-Base64 encoded string as input and returns the decoded headers. /// </summary> /// <param name="Line">A line of JSON-Base64 encoded input.</param> /// <returns>A list of decoded headers.</returns> /// <exception cref="JB64Exception">Thrown if headers are unable to be decoded.</exception> public List<JB64Header> DecodeHeaders(string Line) { this.Headers = null; this.Map = null; Hash = MD5.Create(); JArray Headers = DecodeLine(Line); return SetHeaders(Headers); }
public static string GetMD5Hash(MD5 md5Hash, byte[] input) { byte[] data = md5Hash.ComputeHash(input); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) sBuilder.Append(data[i].ToString("x2")); return sBuilder.ToString(); }
private static string GetMd5Hash(MD5 md5Hash, string input) { var data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); var sb = new StringBuilder(); for (var i = 0; i < data.Length; i++) { sb.Append(data[i].ToString("x2")); } return sb.ToString(); }
static MD5Helper() { Lock = new object(); if (MD5Instance == null) { lock (Lock) { MD5Instance = MD5.Create(); } } }
protected virtual void Dispose(bool disposing) { if (disposing) { if (md5 != null) { md5.Dispose(); md5 = null; } } }
/// <summary> /// 返回指定字符串的Md5(32位) /// </summary> /// <param name="strInput">指定字符串</param> /// <returns>返回字符串的Md5</returns> public static string GetMd5Hash(string strInput) { // Create a new instance of the MD5CryptoServiceProvider object. MD5 md5Hasher = MD5.Create(); // Convert the input string to a byte array and compute the hash. byte[] btData = md5Hasher.ComputeHash(Encoding.Default.GetBytes(strInput)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < btData.Length; i++) { sBuilder.Append(btData[i].ToString("x2")); } // Return the hexadecimal string. return(sBuilder.ToString()); }
/// <summary> /// /// </summary> /// <param name="order"></param> public CdekStatusAnswer CallCustomer(Order order) { var dateExecute = DateTime.UtcNow.Date.ToString("yyyy-MM-ddThh:mm:ss"); var resultXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; resultXml += string.Format( "<ScheduleRequest Date=\"{0}\" Account=\"{1}\" Secure=\"{2}\" OrderCount=\"1\">", dateExecute, AuthLogin, GetMd5Hash(MD5.Create(), dateExecute + "&" + AuthPassword)); resultXml += string.Format( "<Order DispatchNumber=\"{0}\" Number=\"{1}\" Date=\"{2}\"/>", string.Empty,//order.OrderID, order.Number, order.OrderDate.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ss")); resultXml += string.Format( "<Attempt ID=\"{0}\" Date=\"{1}\"/>", order.OrderID, DateTime.Now.AddDays(1).ToString("yyyy-MM-ddThh:mm:ss")); resultXml += "</ScheduleRequest>"; var responceString = PostRequestGetString(_urlNewSchedule, "xml_request=" + resultXml, "application/x-www-form-urlencoded"); if (responceString.Contains("ERR_INVALID_NUMBER")) { return(new CdekStatusAnswer { Message = string.Format("Заказ {0} не найден в системе СДЭК", order.Number), Status = false }); } else { return(new CdekStatusAnswer { Message = string.Format("Прозвон получателя создан в заказе {0}", order.Number), Status = true }); } }
private void btnmd5_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection(conString); conn.Open(); //Mở kết nối SqlCommand cmd = new SqlCommand("SP_INS_ENCRYPT_SINHVIEN", conn); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add("@masv", SqlDbType.VarChar).Value = txtMasv.Text; cmd.Parameters.Add("@hoten", SqlDbType.VarChar).Value = txtHoten.Text; cmd.Parameters.Add("@ngaysinh", SqlDbType.DateTime).Value = datetimeNS.Text; cmd.Parameters.Add("@diachi", SqlDbType.VarChar).Value = txtDiaChi.Text; cmd.Parameters.Add("@malop", SqlDbType.VarChar).Value = txtMalop.Text; cmd.Parameters.Add("@tendn", SqlDbType.VarChar).Value = txtTenDN.Text; using (MD5 md5Hash = MD5.Create()) { txtHashValue.Text = GetMd5Hash(md5Hash, txtMatkhau.Text); cmd.Parameters.Add("@matkhau", SqlDbType.VarChar).Value = txtHashValue.Text; } cmd.ExecuteScalar(); conn.Close(); }
public static string Crypt(string password, string hash) { var output = "*0"; if (hash.StartsWith(output)) { output = "*1"; } if (!hash.StartsWith("$P$") && !hash.StartsWith("$H$")) { return(output); } var count_log = itoa64.IndexOf(hash[3]); if (count_log < 7 || count_log > 30) { return(output); } var count = 1 << count_log; var salt = hash.Substring(4, 8); if (salt.Length != 8) { return(output); } using (var md5 = MD5.Create()) { var hashMd5 = md5.ComputeHash(Encoding.UTF8.GetBytes(salt + password)); var passwordByteArray = Encoding.UTF8.GetBytes(password); while (count > 0) { hashMd5 = md5.ComputeHash(hashMd5.Concat(passwordByteArray).ToArray()); count -= 1; } return(hash.Substring(0, 12) + Encode64(hashMd5, 16)); } }
private static string GetMd5Hash(string input) { using (MD5 md5Hash = MD5.Create()) { // Convert the input string to a byte array and compute the hash. byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return(sBuilder.ToString()); } }
public static string CreateMD5(byte[] bytes) { if (bytes == null || !bytes.Any()) { return(null); } using (var md5 = MD5.Create()) { byte[] data = md5.ComputeHash(bytes); // Create a new Stringbuilder to collect the bytes and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return(sBuilder.ToString()); } }
public static string GenerateGravitarLink(string email, int size = -1) { email = email.Trim().ToLower(); var hash = MD5.GetHashString(email); var gravitar = string.Empty; if (size > 0) { //show to size gravitar = string.Format("{0}{1}?s={2}", "http://www.gravatar.com/avatar/", hash.ToLower(), size); } else { gravitar = string.Format("{0}{1}", "http://www.gravatar.com/avatar/", hash.ToLower()); } return(gravitar); }
private string callApi(string action, string data) { string API_URI = FX.Utils.UrlUtil.GetSiteUrl(); var client = new RestClient(API_URI); var request = new RestRequest(action); request.Method = Method.POST; request.AddHeader("Admin-Agent", "VSI-HDDT"); request.AddHeader("Content-Type", "application/json"); //Calculate UNIX time DateTime epochStart = new DateTime(1970, 01, 01, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan timeSpan = DateTime.UtcNow - epochStart; string Timestamp = Convert.ToUInt64(timeSpan.TotalSeconds).ToString(); request.AddParameter("application/json", data, ParameterType.RequestBody); //Mã duy nhất string nonce = Guid.NewGuid().ToString("N").ToLower(); //Tạo dữ liệu mã hóa string signatureRawData = String.Format("{0}{1}{2}", request.Method.ToString().ToUpper(), Timestamp, nonce); MD5 md5 = MD5.Create(); var hash = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(signatureRawData)); var signature = Convert.ToBase64String(hash); //Tạo dữ liệu Authentication string value = string.Format("{0}:{1}:{2}:{3}", signature, nonce, Timestamp, HttpContext.Current.User.Identity.Name); request.AddHeader("Authentication", value); IRestResponse response = client.Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { return("ERR:1 - Tài khoản không có quyền thực hiện"); } return(response.Content); }
public void Generate(string inputFileName, string outputFileName) { // normalize file names inputFileName = Path.GetFullPath(inputFileName); outputFileName = Path.GetFullPath(outputFileName); using (var stream = new FileStream(inputFileName, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var reader = new StreamReader(stream)) { var relativeInputFileName = $"{Path.DirectorySeparatorChar}{PathTools.GetRelativePath($"{ProjectDirectory}{Path.DirectorySeparatorChar}", inputFileName)}"; var item = engine.FileSystem.GetItem(relativeInputFileName, "mvc"); var codeDocument = engine.Process(item); var result = codeDocument.GetCSharpDocument(); // normalize new lines (is there better way to do this?) var code = result.GeneratedCode.Replace("\r\n", "\n"); if (File.Exists(outputFileName)) { using (var md5 = MD5.Create()) /*DevSkim: ignore DS126858*/ using (var inputStream = File.OpenRead(outputFileName)) { var codeHash = md5.ComputeHash(inputStream); var fileHash = md5.ComputeHash(Encoding.GetBytes(code)); if (codeHash.SequenceEqual(fileHash)) { return; } } } using (var outputStream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read)) using (var writer = new StreamWriter(outputStream, Encoding)) { writer.Write(code); } } }
/// <summary> /// Gets the MD5 hashcode from the value. /// </summary> /// <param name="value">The value to generate the hash code for.</param> /// <returns>The generated hash code.</returns> public static string GetHashcodeMD5(string value) { int i = 0; // Generate the hash code MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] byteValue = Encoding.ASCII.GetBytes(value); byte[] hashValue = md5.ComputeHash(byteValue); // Get the string value of hashcode. string[] octetArrayByte = new string[hashValue.Count()]; foreach (Byte item in hashValue) { octetArrayByte[i++] = item.ToString("X2"); } // Create the octet string of bytes. string octetValue = String.Join("", octetArrayByte); return(octetValue); }
public static byte[] EncryptStringToBytes(string plainText, string key) { // Check arguments. if (plainText == null || plainText.Length <= 0) { throw new ArgumentNullException("plainText"); } if (key == null || key.Length <= 0) { throw new ArgumentNullException("Key"); } byte[] encrypted; // Create an Aes object // with the specified key and IV. using (Aes aesAlg = Aes.Create()) { aesAlg.Key = SHA256Managed.Create().ComputeHash(Encoding.ASCII.GetBytes(key)); aesAlg.IV = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(key)); // Create an encryptor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encrypted = msEncrypt.ToArray(); } } } return(encrypted); }
//Refer MonoManager, ScriptAssetExporter, ScriptExportManager void DoExport(Func <MonoScript, bool> selector = null) { var managedPath = Path.Combine(GameDir, "Managed"); var globalgamemanagersPath = Path.Combine(GameDir, "globalgamemanagers.assets"); var gameStructure = GameStructure.Load(new string[] { globalgamemanagersPath, managedPath }); fileCollection = gameStructure.FileCollection; if (selector == null) { selector = (o) => true; } var assets = fileCollection.FetchAssets().Where(o => o is MonoScript ms && selector(ms)).ToArray(); ScriptExportManager scriptManager = new ScriptExportManager(gameStructure.FileCollection.Layout, ExportPath); Dictionary <Object, ScriptExportType> exportTypes = new Dictionary <Object, ScriptExportType>(); foreach (Object asset in assets) { MonoScript script = (MonoScript)asset; if (ScriptByName) { using (MD5 md5 = MD5.Create()) { var data = md5.ComputeHash(Encoding.UTF8.GetBytes($"{script.AssemblyName}.{script.Namespace}.{script.ClassName}")); Util.SetGUID(script, data); } } ScriptExportType exportType = script.GetExportType(scriptManager); exportTypes.Add(asset, exportType); } foreach (KeyValuePair <Object, ScriptExportType> exportType in exportTypes) { string path = scriptManager.Export(exportType.Value); } //scriptManager.ExportRest(); }
/// <summary> /// /// </summary> /// <param name="order"></param> public CdekStatusAnswer ReportOrderStatuses(Order order) { var dateExecute = DateTime.UtcNow.Date.ToString("yyyy-MM-ddThh:mm:ss"); var resultXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; resultXml += string.Format( "<StatusReport Date=\"{0}\" Account=\"{1}\" Secure=\"{2}\" ShowHistory=\"{3}\">", dateExecute, AuthLogin, GetMd5Hash(MD5.Create(), dateExecute + "&" + AuthPassword), 1); resultXml += string.Format("<Order DispatchNumber=\"{0}\" Number=\"{1}\" Date=\"{2}\" />", order.OrderID, order.Number, order.OrderDate.ToUniversalTime().ToString("yyyy-MM-ddThh:mm:ss")); resultXml += "</StatusReport>"; var responceString = PostRequestGetString(_urlOrdersStatusReport, "xml_request=" + resultXml, "application/x-www-form-urlencoded"); CdekOrderStatusInfo result; using (var reader = new StringReader(responceString)) { var serializer = new XmlSerializer(typeof(CdekOrderStatusInfo)); result = (CdekOrderStatusInfo)serializer.Deserialize(reader); } return(new CdekStatusAnswer { Message = result != null && result.Orders != null ? "Информация о статусах получена" : string.Format("Заказ {0} в системе не найден", order.Number), Status = result != null && result.Orders != null, Object = CreateOrderStatusReport(result) }); }
/// <summary> /// 把内容进行MD5加密 /// </summary> /// <param name="parameters"></param> /// <param name="key"></param> /// <returns></returns> public static string GetMd5Hash(IDictionary <string, string> parameters, string key) { StringBuilder buff = new StringBuilder(); foreach (KeyValuePair <string, string> pair in parameters) { if (pair.Value == null) { throw new Exception("字典内部含有值为null的字段!"); } if (pair.Key != "sign" && pair.Value.ToString() != "") { if (buff.Length > 0) { buff.Append('&'); } buff.Append(pair.Key); buff.Append('='); buff.Append(pair.Value); } } buff.Append("&key="); buff.Append(key); //MD5加密 using (MD5 md5Hash = MD5.Create()) { var bs = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(buff.ToString())); var sb = new StringBuilder(); foreach (byte b in bs) { sb.Append(b.ToString("x2")); } //所有字符转为大写 return(sb.ToString().ToUpper()); } }
public static bool FilesAreEqual_Hash(string path1, string path2) { if (string.IsNullOrEmpty(path1) || string.IsNullOrEmpty(path2)) { return(false); } if (!File.Exists(path1) || !File.Exists(path2)) { return(false); } try { MD5 md5 = MD5.Create(); using (FileStream fs1 = new FileStream(path1, FileMode.Open, FileAccess.Read)) using (FileStream fs2 = new FileStream(path2, FileMode.Open, FileAccess.Read)) { byte[] hash1 = md5.ComputeHash(fs1); byte[] hash2 = md5.ComputeHash(fs2); for (int byteIdx = 0; byteIdx < hash1.Length; byteIdx++) { if (hash1[byteIdx] != hash2[byteIdx]) { return(false); } } } } catch (Exception ex) { DebugUtility.ShowExceptionMessageBox(string.Format("对比\n文件:({0})\n文件:({1})\n内容失败", path1, path2), ex); return(false); } return(true); }
public static string GenerateSignature(string query, string securitySecret, Method method) { // security secret provided, sort and sign request if (method == Method.md5hash) { query += securitySecret; var hashgen = MD5.Create(); var hash = hashgen.ComputeHash(Encoding.UTF8.GetBytes(query)); return(ByteArrayToHexHelper.ByteArrayToHex(hash).ToLower()); } else { var securityBytes = Encoding.UTF8.GetBytes(securitySecret); var input = Encoding.UTF8.GetBytes(query); HMAC hmacGen = new HMACMD5(securityBytes); switch (method) { case Method.md5: hmacGen = new HMACMD5(securityBytes); break; case Method.sha1: hmacGen = new HMACSHA1(securityBytes); break; case Method.sha256: hmacGen = new HMACSHA256(securityBytes); break; case Method.sha512: hmacGen = new HMACSHA512(securityBytes); break; } var hmac = hmacGen.ComputeHash(input); var sig = ByteArrayToHexHelper.ByteArrayToHex(hmac).ToUpper(); return(sig); } }
internal static bool StartDownload(int id, string path, FileType type, int len, string md5hash, string resource) { if (CurrentFile != null) { LogManager.DebugLog("CurrentFile isn't null -- " + CurrentFile.Type + " " + CurrentFile.Filename); return(false); } if ((type == FileType.Normal || type == FileType.Script) && Directory.Exists(FileTransferId._DOWNLOADFOLDER_ + path.Replace(Path.GetFileName(path), "")) && File.Exists(FileTransferId._DOWNLOADFOLDER_ + path)) { byte[] myData; using (var md5 = MD5.Create()) using (var stream = File.OpenRead(FileTransferId._DOWNLOADFOLDER_ + path)) { myData = md5.ComputeHash(stream); } string hash = myData.Select(byt => byt.ToString("x2")).Aggregate((left, right) => left + right); FileIntegrity.Set(path, md5hash); if (hash == md5hash) { if (type == FileType.Script) { PendingScripts.ClientsideScripts.Add(LoadScript(path, resource, File.ReadAllText(FileTransferId._DOWNLOADFOLDER_ + path))); } LogManager.DebugLog("HASH MATCHES, RETURNING FALSE"); return(false); } } CurrentFile = new FileTransferId(id, path, type, len, resource); return(true); }
public FunctionMetadata GetMetadata(Type functionType) { FunctionMetadata functionMetadata = new FunctionMetadata(functionType); functionMetadata.Id = MD5.GetHashString(functionType.FullName); var displayNameAttr = functionType.GetCustomAttribute <DisplayNameAttribute>(); functionMetadata.DisplayName = displayNameAttr != null ? displayNameAttr.DisplayName : null; var categoryAttr = functionType.GetCustomAttribute <CategoryAttribute>(); functionMetadata.Category = categoryAttr != null ? categoryAttr.Category : null; var sectionAttr = functionType.GetCustomAttribute <SectionAttribute>(); functionMetadata.Section = sectionAttr != null ? sectionAttr.Name : null; var descriptionAttr = functionType.GetCustomAttribute <DescriptionAttribute>(); functionMetadata.Description = descriptionAttr != null ? descriptionAttr.Description : null; foreach (var signature in functionType.GetCustomAttributes <FunctionSignatureAttribute>()) { functionMetadata.Signatures.Add(GetFunctionSignatureMetadata(signature)); } foreach (var exampleUsage in functionType.GetCustomAttributes <ExampleUsageAttribute>()) { functionMetadata.ExampleUsages.Add(new ExampleUsage(exampleUsage.Expression, exampleUsage.Result) { CanMultipleResults = exampleUsage.CanMultipleResults }); } return(functionMetadata); }
public async Task OpenWriteAsyncReturnsWritableStream() { // Arrange var folderName = CoreConstants.Folders.ValidationFolderName; var fileName = _prefixA; var expectedContent = "Hello, world."; var bytes = Encoding.UTF8.GetBytes(expectedContent); string expectedContentMD5; using (var md5 = MD5.Create()) { expectedContentMD5 = Convert.ToBase64String(md5.ComputeHash(bytes)); } var container = _clientA.GetContainerReference(folderName); var file = container.GetBlobReference(fileName); // Act using (var stream = await file.OpenWriteAsync(accessCondition: null)) { await stream.WriteAsync(bytes, 0, bytes.Length); } // Assert // Reinitialize the blob to verify the metadata is fresh. file = container.GetBlobReference(fileName); using (var memoryStream = new MemoryStream()) { await file.DownloadToStreamAsync(memoryStream); var actualContent = Encoding.ASCII.GetString(memoryStream.ToArray()); Assert.Equal(expectedContent, actualContent); Assert.NotNull(file.ETag); Assert.NotEmpty(file.ETag); Assert.Equal(expectedContentMD5, file.Properties.ContentMD5); } }
private bool VerifyHash() { if (SignedHash == null) { return(false); } // 2. Initialize a hash algorithm context. HashAlgorithm hashAlgorithm; switch (SignedHash.Length) { case 16: hashAlgorithm = MD5.Create(); break; case 20: hashAlgorithm = SHA1.Create(); break; case 32: hashAlgorithm = SHA256.Create(); break; case 48: hashAlgorithm = SHA384.Create(); break; case 64: hashAlgorithm = SHA512.Create(); break; default: return(false); } var hash = ComputeAuthenticodeHashFromPeFile(hashAlgorithm); return(hash != null && SignedHash.SequenceEqual(hash)); }
public void Day05_GeneratePart2DoorPassword() { string doorId = "uqwqemis"; string expectedPassword = "******"; string pwd = "qqqqqqqq"; char[] pwdchs = pwd.ToCharArray(); int ich = 0; int pwdLength = 0; using (MD5 md5 = MD5.Create()) { long index = 0; do { index++; string input = $"{doorId}{index}"; byte[] inputBytes = Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); if (hash[0] == 0 && hash[1] == 0 && hash[2] < 16) { ich = hash[2]; if (ich < 8 && pwdchs[ich] == 'q') { pwdchs[ich] = hash[3].ToString("x2").ToCharArray()[0]; pwdLength++; } } } while (pwdLength != 8); } StringBuilder pwdSb = new StringBuilder(); foreach (var ch in pwdchs) { pwdSb.Append(ch); } Assert.Equal(expectedPassword, pwdSb.ToString()); }
public LoginResponse LogIn(LogInUser logInUser) { Uzytkownicy user; using (PP_testEntities context = new PP_testEntities()) { user = (from u in context.Uzytkownicies where u.email == logInUser.Email && u.haslo == logInUser.Password select u).FirstOrDefault(); } if (user == null) { return new LoginResponse() { Result = "Failed", Reason = "Bad email or password" } } ; var time = DateTime.Now; string str = time.ToString("yyyyMMddHHmmssfffffff") + logInUser.Email + logInUser.UserAgent; MD5 md5 = MD5.Create(); byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(str)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } var token = sBuilder.ToString(); sessions.Add(token, logInUser.Email); return(new LoginResponse() { Token = token, Result = "OK" }); }
/// <summary> /// Verifies that the URL has not been tampered with using a secret key /// </summary> /// <param name="md5Hash">An MD5 instance used genereate hashes</param> /// <param name="url">The URL to verify</param> /// <param name="SharedEventKey">The secret key</param> /// <param name="PlaceInQueueEncryptString">The encrypted queue number (the p-parameter)</param> /// <returns>Returns -1 if the URL has been tampered with - otherwhise the queue number of the request. The queue number may be 9999999 if the queue number is unknown</returns> public static long VerifyMD5Hash(MD5 md5Hash, string url, string SharedEventKey, string PlaceInQueueEncryptString) { try { //input must not be empty if (!string.IsNullOrEmpty(url) & !string.IsNullOrEmpty(SharedEventKey) & !string.IsNullOrEmpty(PlaceInQueueEncryptString)) { long placeInQueue = -1; string parsedHashValue = url.Substring(url.Length - 32); //The hash value is the last 32 chars of the URL string input = url.Substring(0, url.Length - 32) + SharedEventKey; //Remove hash value and add SharedEventKey // Hash the input. string hashOfInput = GetMd5Hash(md5Hash, input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; if (0 == comparer.Compare(hashOfInput, parsedHashValue)) { placeInQueue = DecryptPlaceInQueue(PlaceInQueueEncryptString); } else { placeInQueue = -1; } return(placeInQueue); } else { return(-2); //Input values not valid } } catch (Exception) { return(-2); } }
public async Task ExecuteTest(string data) { var targetPath = $"{TestContext.CurrentContext.TestDirectory}.\\test2.txt"; var listener = new TcpListener(IPAddress.Any, 8888); try { using (var writer = new StreamWriter(File.OpenWrite(targetPath))) { await writer.WriteAsync(data); } listener.Start(); using (var client = new TcpClient("localhost", 8888)) { var acceptedClient = listener.AcceptTcpClient(); var command = new GetCommand(targetPath, acceptedClient); await command.Execute(); using (var md5 = MD5.Create()) { var expectedString = $"{data.Length} {data}"; var buffer = new byte[expectedString.Length]; await client.GetStream().ReadAsync(buffer, 0, expectedString.Length); var actual = md5.ComputeHash(buffer); var expected = md5.ComputeHash(Encoding.UTF8.GetBytes($"{data.Length} {data}")); CollectionAssert.AreEqual(expected, actual); } } } finally { listener.Stop(); File.Delete(targetPath); } }
/// <summary> /// 给TOP请求签名。 /// </summary> /// <param name="parameters">所有字符型的TOP请求参数</param> /// <param name="secret">签名密钥</param> /// <param name="qhs">是否前后都加密钥进行签名</param> /// <returns>签名</returns> public static string SignTopRequest(IDictionary <string, string> parameters, string secret, bool qhs) { // 第一步:把字典按Key的字母顺序排序 IDictionary <string, string> sortedParams = new SortedDictionary <string, string>(parameters); IEnumerator <KeyValuePair <string, string> > dem = sortedParams.GetEnumerator(); // 第二步:把所有参数名和参数值串在一起 StringBuilder query = new StringBuilder(secret); while (dem.MoveNext()) { string key = dem.Current.Key; string value = dem.Current.Value; if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value)) { query.Append(key).Append(value); } } if (qhs) { query.Append(secret); } // 第三步:使用MD5加密 MD5 md5 = MD5.Create(); byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString())); // 第四步:把二进制转化为大写的十六进制 StringBuilder result = new StringBuilder(); for (int i = 0; i < bytes.Length; i++) { result.Append(bytes[i].ToString("X2")); } return(result.ToString()); }
public static bool Md5HashEquals(string filePath1, string filePath2) { if (!File.Exists(filePath1) || !File.Exists(filePath2)) { return(false); } byte[] file1Hash; byte[] file2Hash; using (var md5 = MD5.Create()) { using (var stream = File.OpenRead(filePath1)) { file1Hash = md5.ComputeHash(stream); } using (var stream = File.OpenRead(filePath2)) { file2Hash = md5.ComputeHash(stream); } } if (file1Hash.Length != file2Hash.Length) { return(false); } for (var i = 0; i < file1Hash.Length; i++) { if (file1Hash[i] != file2Hash[i]) { return(false); } } return(true); }
private void ButtonUnlockClick(object sender, RoutedEventArgs e) { Directory mainDir = null; string pass = passwordBox.Password.Length > 0 ? passwordBox.Password : "******"; string hash; using (MD5 md5 = MD5.Create()) { hash = Encoding.Default.GetString(md5.ComputeHash(Encoding.UTF8.GetBytes(pass))); } if (System.IO.File.Exists("Passwords.bin")) { byte[] bytes = System.IO.File.ReadAllBytes("Passwords.bin"); byte[] decrypted = WPF_Project.DataEncryption.Decrypt(hash, bytes); if (decrypted == null) { MessageBox.Show("Invalid password!", "Password Manager", MessageBoxButton.OK, MessageBoxImage.Error); return; } using (MemoryStream ms = new MemoryStream(decrypted)) { BinaryFormatter formatter = new BinaryFormatter(); try { mainDir = (Directory)formatter.Deserialize(ms); } catch { MessageBox.Show("Deserialization error!", "Password Manager", MessageBoxButton.OK, MessageBoxImage.Error); return; } } } NavigationService.Navigate(new MainPage(hash, mainDir)); }
static void Main(string[] args) { var source = "Test"; MD5 md5Hash = MD5.Create(); string hash = GetMd5Hash(md5Hash, source); Console.WriteLine("The MD5 hash of " + source + " is: " + hash + "."); Console.WriteLine("Verifying the hash..."); if (VerifyMd5Hash(md5Hash, source, hash)) { Console.WriteLine("The hashes are the same."); } else { Console.WriteLine("The hashes are not same."); } var user = new UserDto() { UserName = "******", Address = "Street Test", DateCreated = DateTime.Now, Email = "[email protected]", FirstName = "FirstNameTest", IsDeleted = false, LastName = "LastNameTest", Password = "******", Phone = "098765483", UserType = DataLayer.Enumerations.UserType.Service }; userService.Create(user); //var userTest = userService.Login(user.UserName,"Test"); //unit.Commit(); }
private static string Md5Hash(string input, bool base64) { // step 1, calculate MD5 hash from input var md5 = MD5.Create(); var inputBytes = Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); if (base64) { return(Convert.ToBase64String(hash)); } // step 2, convert byte array to hex string var sb = new StringBuilder(); for (var i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return(sb.ToString()); }
public static string MakeSign(this string plaintext, string signType, string payKey) { if (signType == WxPayData.SIGN_TYPE_MD5) { var md5 = MD5.Create(); var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(plaintext)); var sb = new StringBuilder(); foreach (byte b in bs) { sb.Append(b.ToString("x2")); } //所有字符转为大写 return(sb.ToString().ToUpper()); } else if (signType == WxPayData.SIGN_TYPE_HMAC_SHA256) { return(CalcHMACSHA256Hash(plaintext, payKey)); } else { throw new ArgumentException("sign_type 不合法"); } }