private string CRC32(string filename) { var crc32 = new DamienG.Security.Cryptography.Crc32(); String hash = String.Empty; using (System.IO.FileStream fs = System.IO.File.OpenRead(filename)) foreach (byte b in crc32.ComputeHash(fs)) { hash += b.ToString("X2"); } return(hash); }
/// <summary> /// Substitue for CatalogeTrack number in Muziekweb.nl database /// </summary> public string GenerateCRC32Key(string input) { // step 1, calculate MD5 hash from input DamienG.Security.Cryptography.Crc32 crc32 = new DamienG.Security.Cryptography.Crc32(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = crc32.ComputeHash(inputBytes); // step 2, convert byte array to hex string System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } //for return(sb.ToString()); }
/** * @fn private void SendServerInfoPacket(UdpClient client, IPEndPoint dest) * * @brief Sends a server information packet. * * @param client The client. * @param dest Destination for the. */ private void SendServerInfoPacket(UdpClient client, IPEndPoint dest) { var crcGen = new DamienG.Security.Cryptography.Crc32(); byte[] buf = new byte[17]; //fill packet buf[0] = Protocol.SERVER_INFO; Buffer.BlockCopy(BitConverter.GetBytes(GetAge()), 0, buf, 1, 4); Buffer.BlockCopy(BitConverter.GetBytes(uid), 0, buf, 5, 8); //crc byte[] crc = crcGen.ComputeHash(buf, 1, 12); Buffer.BlockCopy(crc, 0, buf, 13, 4); //send try { client.Send(buf, buf.Length, dest); } catch (SocketException) {} }
/// <summary> /// Hash a string. /// </summary> /// <param name="fullPath">Full path of a part.</param> /// <returns>A 32-bit int.</returns> static public int GetHash(string fullPath) { DamienG.Security.Cryptography.Crc32 crc = new DamienG.Security.Cryptography.Crc32(); byte[] b = new byte[fullPath.Length]; string hash = string.Empty; for (int i = 0; i < fullPath.Length; i++) { b[i] = (byte)fullPath[i]; } foreach (byte byt in crc.ComputeHash(b)) { hash += byt.ToString("x2").ToLower(); } try { return(int.Parse(hash, System.Globalization.NumberStyles.HexNumber)); } catch (Exception) { return(0); } }
private uint CalculateCRCWithDotNet(string fileName) { uint res = 0; try { DamienG.Security.Cryptography.Crc32 crc32 = new DamienG.Security.Cryptography.Crc32(); var f = File.OpenRead(fileName); var res2 = crc32.ComputeHash(f); if (BitConverter.IsLittleEndian) { Array.Reverse(res2); } res = BitConverter.ToUInt32(res2, 0); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } return(res); }
public String GetVehicles() { string resultContent = ""; try { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("User-Agent", "C# App"); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Tesla_token); string adresse = apiaddress + "api/1/vehicles"; var resultTask = client.GetAsync(adresse); HttpResponseMessage result = resultTask.Result; resultContent = result.Content.ReadAsStringAsync().Result; object jsonResult = new JavaScriptSerializer().DeserializeObject(resultContent); var r1 = ((System.Collections.Generic.Dictionary <string, object>)jsonResult)["response"]; var r1temp = (object[])r1; if (ApplicationSettings.Default.Car >= r1temp.Length) { Tools.Log("Car # " + ApplicationSettings.Default.Car + " not exists!"); return("NULL"); } var r2 = ((System.Collections.Generic.Dictionary <string, object>)r1temp[ApplicationSettings.Default.Car]); string OnlineState = r2["state"].ToString(); System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString() + " : " + OnlineState); string display_name = r2["display_name"].ToString(); Tools.Log("display_name :" + display_name); string vin = r2["vin"].ToString(); Tools.Log("vin :" + vin); Tesla_id = r2["id"].ToString(); Tools.Log("id :" + Tesla_id); Tesla_vehicle_id = r2["vehicle_id"].ToString(); Tools.Log("vehicle_id :" + Tesla_vehicle_id); byte[] tempTasker = System.Text.Encoding.UTF8.GetBytes(vin + ApplicationSettings.Default.TeslaName); TaskerHash = String.Empty; var crc32 = new DamienG.Security.Cryptography.Crc32(); foreach (byte b in crc32.ComputeHash(tempTasker)) { TaskerHash += b.ToString("x2").ToLower(); } Tools.Log("Tasker Config:\r\n Server Port : https://teslalogger.de\r\n Pfad : wakeup.php\r\n Attribute : &t=" + TaskerHash); /* * dynamic jsonResult = new JavaScriptSerializer().DeserializeObject(resultContent); * token = jsonResult["access_token"]; */ return(resultContent); } catch (Exception ex) { Tools.ExceptionWriter(ex, resultContent); } return("NULL"); }
/** * @fn private Task BroadcastHandlingTask() * * @brief Handles the udp broadcasting, sends server info to clients and resolves best host with other hosts. * * @return The Task. */ private Task BroadcastHandlingTask() { return(Task.Run(() => { var crcGen = new DamienG.Security.Cryptography.Crc32(); UdpClient udpClient = new UdpClient(); //set socket to allow multiple multiple binds and broadcasting udpClient.ExclusiveAddressUse = false; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.EnableBroadcast = true; udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, Protocol.PORT)); IPEndPoint destination = new IPEndPoint(IPAddress.Broadcast, Protocol.PORT); while (!stopping) { Task delay; if (GetAge() < 2) { delay = Task.Delay(100); } else { delay = Task.Delay(2000); } //send SERVER_INFO atleast once every loop SendServerInfoPacket(udpClient, destination); //read SERVER_INFO messages while (!delay.IsCompleted) { if (udpClient.Available == 0) { Task.Delay(20).Wait(); continue; } IPEndPoint sender = new IPEndPoint(IPAddress.Any, Protocol.PORT); byte[] bytes = udpClient.Receive(ref sender); //reply to info requests if (bytes[0] == Protocol.SERVER_INFO_REQUEST) { SendServerInfoPacket(udpClient, destination); } //check if SERVER_INFO else if (bytes[0] == Protocol.SERVER_INFO && bytes.Length == 17) { UInt32 thisAge = GetAge();//get age right away //check if own broadcast before CRC to prevent wasting resources UInt64 otherUid = BitConverter.ToUInt64(bytes, 5); if (otherUid == uid) { continue;//skip } //check crc byte[] crc = new byte[4]; Buffer.BlockCopy(bytes, 13, crc, 0, 4); if (crcGen.ComputeHash(bytes, 1, 12).SequenceEqual(bytes)) { continue;//skip } UInt32 otherAge = BitConverter.ToUInt32(bytes, 1); //if other server is more legitimate if (((Int64)otherAge - thisAge > 2) || (Math.Abs((Int64)otherAge - thisAge) <= 2 && otherUid > uid)) { Stop();//signal server to stop } } } } udpClient.Close(); })); }
/// <summary> /// Hash a string. /// </summary> /// <param name="fullPath">Full path of a part.</param> /// <returns>A 32-bit int.</returns> public static int GetHash(string fullPath) { DamienG.Security.Cryptography.Crc32 crc = new DamienG.Security.Cryptography.Crc32(); byte[] b = new byte[fullPath.Length]; string hash = string.Empty; for (int i = 0; i < fullPath.Length; i++) b[i] = (byte)fullPath[i]; foreach (byte byt in crc.ComputeHash(b)) hash += byt.ToString("x2").ToLower(); try { return int.Parse(hash, System.Globalization.NumberStyles.HexNumber); } catch (Exception) { return 0; } }
/** * @fn private List<CandidateServer> GetCandidateServers() * * @brief candidates are sorted from oldest to newest. * * @exception SocketException Thrown when a Socket error condition occurs. * * @return The candidate servers. */ private List <CandidateServer> GetCandidateServers() { List <CandidateServer> candidates = new List <CandidateServer>(); var crcGen = new DamienG.Security.Cryptography.Crc32(); using (UdpClient udpClient = new UdpClient()) { //set socket to allow multiple multiple binds and broadcasting udpClient.ExclusiveAddressUse = false; udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpClient.EnableBroadcast = true; udpClient.Client.Bind(new IPEndPoint(IPAddress.Any, Protocol.PORT)); IPEndPoint remoteEnd = new IPEndPoint(IPAddress.Broadcast, Protocol.PORT); DateTime stopTime = DateTime.UtcNow.AddSeconds(2); while (DateTime.UtcNow < stopTime) { Task delay = Task.Delay(100); //request server info udpClient.Send(new byte[] { Protocol.SERVER_INFO_REQUEST }, 1, remoteEnd); //read SERVER_INFO messages while (udpClient.Available > 0) { IPEndPoint sender = new IPEndPoint(IPAddress.Any, Protocol.PORT); byte[] bytes = udpClient.Receive(ref sender); //check if SERVER_INFO if (bytes.Length != 17 || bytes[0] != Protocol.SERVER_INFO) { continue;//skip this one } //check crc byte[] crc = new byte[4]; Buffer.BlockCopy(bytes, 13, crc, 0, 4); if (!crcGen.ComputeHash(bytes, 1, 12).SequenceEqual(crc)) { continue;//skip } IPAddress ip = sender.Address; UInt64 uid = BitConverter.ToUInt64(bytes, 5); UInt32 age = BitConverter.ToUInt32(bytes, 1); //check if allready in list bool skip = false; foreach (var server in candidates) { if (server.Ip.GetAddressBytes().SequenceEqual(ip.GetAddressBytes())) { skip = true;//skip this one break; } } if (skip) { continue; } //add to list of candidates candidates.Add(new CandidateServer(ip, age, uid)); //set remaining time to max of one second if (stopTime > DateTime.UtcNow.AddSeconds(1)) //more that 1 second left { stopTime = DateTime.UtcNow.AddSeconds(1); } } delay.Wait(); } } candidates.Sort(); return(candidates); }