I am having a bit of a conundrum here... basically I am performing some very very basic file compression steps as follows:
open file and read as string/into a string
parse through the string, and replace repeating patterns with smaller size of text that represents the pattern (ex: aaaaaaaaaaa (11 chars) is replaced with [a#$%11] (8 chars))
save the new, smaller string, into a separate file (can compare sizes)
For some reason, even though the new string in memory is like, 3% smaller than the original string, when I save the string into a file, the file itself is BIGGER than the original file on the file system?? How is that even possible? If someone could explain that to me it would be great!
Here is the code I am using to do this:
void bkg_DoWork(object sender, DoWorkEventArgs e)
{
try
{
string file = File.ReadAllText(this.txt_CompressFilename.Text);
int olength = file.Length;
int nlength = 0;
decimal pct = 0;
string lastchar = "";
int count = 0;
List<RepeatingPattern> SinglePatterns = new List<RepeatingPattern>();
List<RepeatingPattern> DoublePatterns = new List<RepeatingPattern>();
List<RepeatingPattern> TriplePatterns = new List<RepeatingPattern>();
List<RepeatingPattern> QuadruplePatterns = new List<RepeatingPattern>();
UpdateProgress("Read file contents", 0, 1, 6);
UpdateProgress("Finding single character replacements.", pct, 1, 6);
//single character replaces.
for (int i = 0; i < olength; i++)
{
if (file[i].ToString() == lastchar)
count += 1;
else
{
//create a pattern, if the count is more than what a pattern's compressed pattern looks like to save space... 8 chars
//[a#$%#]
if (count > 7)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!SinglePatterns.Contains(ptn))
SinglePatterns.Add(ptn);
}
count = 0;
lastchar = file[i].ToString();
}
}
//handle possible trailing pattern
if (count > 7)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!SinglePatterns.Contains(ptn))
SinglePatterns.Add(ptn);
}
if (SinglePatterns.Count > 0)
for (int i = 0; i < SinglePatterns.Count; i++)
file = file.Replace(SinglePatterns[i].ToString(), SinglePatterns[i].ToReplaceString());
nlength = file.Length;
pct = (decimal)(((double)(olength - nlength) / olength) * 100);
UpdateProgress("Found and replaced " + SinglePatterns.Count, pct, 2, 6);
UpdateProgress("Finding double character replacements.", pct, 2, 6);
lastchar = "";
count = 0;
//double character replaces.
for (int i = 0; i + 1 < file.Length; i = i + 2)
{
if ("" + file[i] + "" + file[i + 1] == lastchar)
count += 1;
else
{
//create a pattern, if the count is more than what a pattern's compressed pattern looks like to save space... 8 chars
//[aa#$%#]
if (count > 8)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!DoublePatterns.Contains(ptn))
DoublePatterns.Add(ptn);
}
count = 0;
lastchar = "" + file[i] + "" + file[i + 1];
}
}
//handle possible trailing pattern
if (count > 8)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!DoublePatterns.Contains(ptn))
DoublePatterns.Add(ptn);
}
if (DoublePatterns.Count > 0)
for (int i = 0; i < DoublePatterns.Count; i++)
file = file.Replace(DoublePatterns[i].ToString(), DoublePatterns[i].ToReplaceString());
nlength = file.Length;
pct = (decimal)(((double)(olength - nlength) / olength) * 100);
UpdateProgress("Found and replaced " + DoublePatterns.Count, pct, 3, 6);
UpdateProgress("Finding triple character replacements.", pct, 3, 6);
lastchar = "";
count = 0;
//triple character replaces.
for (int i = 0; i + 2 < file.Length; i = i + 3)
{
if ("" + file[i] + "" + file[i + 1] + "" + file[i + 2] == lastchar)
count += 1;
else
{
//create a pattern, if the count is more than what a pattern's compressed pattern looks like to save space... 8 chars
//[aaa#$%#]
if (count > 9)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!TriplePatterns.Contains(ptn))
TriplePatterns.Add(ptn);
}
count = 0;
lastchar = "" + file[i] + "" + file[i + 1] + "" + file[i + 2];
}
}
//handle possible trailing pattern
if (count > 9)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!TriplePatterns.Contains(ptn))
TriplePatterns.Add(ptn);
}
if (TriplePatterns.Count > 0)
for (int i = 0; i < TriplePatterns.Count; i++)
file = file.Replace(TriplePatterns[i].ToString(), TriplePatterns[i].ToReplaceString());
nlength = file.Length;
pct = (decimal)(((double)(olength - nlength) / olength) * 100);
UpdateProgress("Found and replaced " + TriplePatterns.Count, pct, 4, 6);
UpdateProgress("Finding quadruple character replacements.", pct, 4, 6);
lastchar = "";
count = 0;
//triple character replaces.
for (int i = 0; i + 3 < file.Length; i = i + 4)
{
if ("" + file[i] + "" + file[i + 1] + "" + file[i + 2] + "" + file[i + 3] == lastchar)
count += 1;
else
{
//create a pattern, if the count is more than what a pattern's compressed pattern looks like to save space... 8 chars
//[aaaa#$%#]
if (count > 10)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!QuadruplePatterns.Contains(ptn))
QuadruplePatterns.Add(ptn);
}
count = 0;
lastchar = "" + file[i] + "" + file[i + 1] + "" + file[i + 2] + "" + file[i + 3];
}
}
//Handle possible trailing pattern
if (count > 10)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!QuadruplePatterns.Contains(ptn))
QuadruplePatterns.Add(ptn);
}
if (QuadruplePatterns.Count > 0)
for (int i = 0; i < QuadruplePatterns.Count; i++)
file = file.Replace(QuadruplePatterns[i].ToString(), QuadruplePatterns[i].ToReplaceString());
nlength = file.Length;
pct = (decimal)(((double)(olength - nlength) / olength) * 100);
UpdateProgress("Found and replaced " + QuadruplePatterns.Count, pct, 5, 6);
UpdateProgress("Saving new .cmp file...", pct, 5, 6);
string newpath = this.txt_FolderName.Text + "\\" + Path.GetFileName(this.txt_CompressFilename.Text);
newpath = newpath.Substring(0, newpath.LastIndexOf("."));
newpath = newpath + ".cmp";
File.WriteAllText(newpath, file);
stopwatch.Stop();
UpdateProgress("Compression completed! Time to compress file: " + string.Format("{0}", stopwatch.Elapsed), pct, 6, 6);
string report = "Compression report\n\n";
FileInfo inf = new FileInfo(this.txt_CompressFilename.Text);
FileInfo infNew = new FileInfo(newpath);
report += "Single character replacements made: " + SinglePatterns.Count + "\n\n";
report += "Double character replacements made: " + DoublePatterns.Count + "\n\n";
report += "Triple character replacements made: " + TriplePatterns.Count + "\n\n";
report += "Quadruple character replacements made: " + QuadruplePatterns.Count + "\n\n";
report += "Total compression ration achieved in string: " + pct + "% \n\n";
report += "Old file size: " + inf.Length + "\nNew file size: " + infNew.Length + " in bytes.";
report += "Total time to achieve compression: " + string.Format("{0}", stopwatch.Elapsed);
e.Result = report;
}
catch (Exception ex)
{
e.Result = ex;
}
}
Here is the code for the RepeatingPattern class...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Compressor
{
public class RepeatingPattern : IEquatable<RepeatingPattern>
{
public string RepeatingChar { get; set; }
public int Count { get; set; }
public RepeatingPattern()
{
this.RepeatingChar = "";
this.Count = -1;
}
public RepeatingPattern(string rchar, int count)
{
this.RepeatingChar = rchar;
this.Count = count;
}
public RepeatingPattern(string FromReplaceString)
{
FromReplaceString = FromReplaceString.Replace("[", "").Replace("]", "");
List<string> parts = FromReplaceString.Split(new string[] { "#$%" }, StringSplitOptions.None).ToList();
if (parts.Count != 2)
throw new ArgumentException("Invalid argument count. Must be in this format: [a#$%N]");
try
{
this.RepeatingChar = parts[0];
this.Count = int.Parse(parts[1]);
}
catch (Exception ex)
{
throw new ArgumentException("Unable to cast the argument and create an object from it. Error: " + ex.Message);
}
}
public override bool Equals(object obj)
{
RepeatingPattern tmp = obj as RepeatingPattern;
if (tmp != null)
return base.Equals(tmp);
else
throw new Exception("Invalid comparison type. Both objects must be of type RepeatingPattern");
}
public bool Equals(RepeatingPattern tmp)
{
return this.RepeatingChar == tmp.RepeatingChar && this.Count == tmp.Count;
}
public override int GetHashCode()
{
return this.RepeatingChar.GetHashCode() ^ this.Count.GetHashCode();
}
public override string ToString()
{
string retval = "";
for (int i = 0; i < this.Count; i++)
retval += this.RepeatingChar;
return retval;
}
public string ToReplaceString()
{
return "[" + this.RepeatingChar + "#$%" + this.Count + "]";
}
}
}
Out of curiosity, I have made an attempt at the code. Some differences:
I made a helper function to find runs in the text
I build a new string (using StringBuilder) as I go through the old string instead of replacing in the old string
I think my code is a bit simpler than yours. I have tested with:
Input: "aaaaaaaaaaabbbcdcdcdcdcdcdxxxxxxxxxxxxxxxxxxhello"
Output: "[a#$%11]bbb[cd#$%6][x#$%18]hello"
Here's the code. This is a first draft. Probably lots of improvements to make:
static int FindRun(string s, int start, int length)
{
if (start + length >= s.Length) return 0;
int numRuns = 0;
string pattern = s.Substring(start, length);
for (int i = start + length; i <= s.Length - length; i += length)
{
if (s.Substring(i, length) == pattern) numRuns += 1;
else break;
}
return numRuns;
}
static string EncodeString(string src)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < src.Length; i++)
{
string theRun = null;
int numRuns = 0;
// Find runs of lengths 4, 3, 2, 1
for (int j = 4; j >= 1; j--)
{
int runs = FindRun(src, i, j);
if (runs > 1) // Run found!
{
// Save it for later. Want to append the longest run
theRun = src.Substring(i, j);
numRuns = runs;
}
}
// No run? Just append the letter
if (theRun == null)
{
sb.Append(src[i]);
}
else
{
// This is the size of the run
int replacementStringSize = (numRuns * theRun.Length) + (theRun.Length - 1);
// This is the code to use as a replacement
String runCode = String.Format("[{0}#$%{1}]", theRun, numRuns + 1);
// Only append if the code length is smaller than the original run
if (runCode.Length < replacementStringSize)
{
sb.Append(runCode);
}
else
{
// Don't encode. Put original run back
for (int j = 0; j <= numRuns; j++)
{
sb.Append(theRun);
}
}
// Skip over the run
i += replacementStringSize;
}
}
return sb.ToString();
}
The root cause of the much larger output files is because of encoding. ChromeSetup.exe is 1,397,976 bytes. When the file is read in using File.ReadAllText it attempts to detect the string encoding. The string is 1,327,384 characters long in this case. Here's the key though, because of encoding each character isn't necessarily a single byte. For example in UTF-8 each character is 1 to 4 bytes. So then when the result string is written out a single character could become multiple bytes.
For reading/writing executables/binary files you're better off using File.ReadAllBytes()`File.WriteAllBytes()`.
While attempting to run your code I came across several other bugs. Here are the bugs I found.
1) In the double/triple/quad character replaces the for loop bounds should check up to the character that will be used.
//double character replaces.
for (int i = 0; i < file.Length; i = i + 2)
{
if ("" + file[i] + "" + file[i + 1] == lastchar)
This will cause an out of index exception if the file string is an odd number of characters. Add in a + 1 to fix this.
for (int i = 0; i + 1 < file.Length; i = i + 2)
For the triple this will be + 2, for quad + 3.
2) If the string ends with a repeating pattern this isn't handled correctly. In the for loops the pattern count is only checked when a different char is encountered. So if the pattern is at the end of the string it isn't detected. You could handle this by checking the count after the for loop.
if (count > 7)
{
//create and add a pattern to the list if necessary.
RepeatingPattern ptn = new RepeatingPattern(lastchar.ToString(), count);
if (!SinglePatterns.Contains(ptn))
SinglePatterns.Add(ptn);
}
3) count and lastchar should be reset before each for loop. If one for loop ends with count = 17 and the next for loop runs it would add a repeating pattern of count 17, which has already been replaced.
4) As others have mentioned, doing replacements in your input string as you go along has the potential to cause issues.
If you can post your RepeatingPattern code and your input text file we can run down the exact cause of your larger output file.
Edit: Running with your RepeatingPattern code I see another small bug. The pattern "aaaaaaaaaa" becomes "[a#$%9]a". it should be replacing one more character. This could be making your output string slightly longer than expected. To fix this, in the replacement for loops set count to 1 (instead of 0) when a new pattern is started.
I am trying to write to a CSV file, and have researched a bit on how to do this and it seems pretty straightforward but it is not populating my CSV file when I run it. The program will write to a txt and my console with no issue.
StreamWriter vWriteFile = new StreamWriter("Positions2.csv");
var path = #"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReader3\Position_2016_02_25.0415.csv";
if (vShowBoth == false)
{
//This determines whether to view by account or by underlying.
Console.WriteLine("Please enter 0 if you wish to see sums by account, or 12 if you wish to see by underlying");
int vViewControl = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Account" + " Settle Sum" + " Open Sum" + " Buy Sum" + " Sell Sum");
using (var parsedLines = File.ReadLines(path).Select(line => line.Split(',')).GetEnumerator())
{
bool vMore = parsedLines.MoveNext();
while (vMore)
{
// Initialize
bool vWasSuccessful;
var vAccount = parsedLines.Current[vViewControl];
double vSettleMMSum = 0;
double vOpenSum = 0;
int vBuySum = 0;
int vSellSum = 0;
do
{
double vParseSettleMM = 0;
double vParseOpen = 0;
int vParseBuy = 0;
int vParseSell = 0;
//Parsing data read in from strings, into temp variables
vWasSuccessful = double.TryParse(parsedLines.Current[7], out vParseSettleMM);
vWasSuccessful = double.TryParse(parsedLines.Current[8], out vParseOpen);
vWasSuccessful = int.TryParse(parsedLines.Current[6], out vParseBuy);
vWasSuccessful = int.TryParse(parsedLines.Current[10], out vParseSell);
//adding temp variabels to sum
vSettleMMSum += vParseSettleMM;
vOpenSum += vParseOpen;
vBuySum += vParseBuy;
vSellSum += vParseSell;
vMore = parsedLines.MoveNext();
}
//sets up when to break
while (vMore && vAccount == parsedLines.Current[vViewControl]);
//After each Break need to print out Account name and sums from above.
// Do printing here as part of the loop, at the very end of the loop code block.
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine(vAccount + " " + vSettleMMSum + " " + vOpenSum + " " + vBuySum + " " +
vSellSum);
//vWriteFile.Write(vAccount + "," + vSettleMMSum + "," + vOpenSum + "," + vBuySum + "," +
// vSellSum);
vWriteFile.WriteLine("{0},{1},{2},{3},{4}", vAccount, vSettleMMSum, vOpenSum, vBuySum, vSellSum);
//reset sums for next loop
vSettleMMSum = 0;
vOpenSum = 0;
vBuySum = 0;
vSellSum = 0;
}
}
}
You should make it a habit to wrap your streams with the using keyword so you don't run into situations where you forget to close it out. It's a good practice to use the using keyword around anything that inherits IDisposable
So your code would look like this.
using(StreamWriter vWriteFile = new StreamWriter("Positions2.csv"))
{
var path = #"C:\Users\jhochbau\documents\visual studio 2015\Projects\CsvReader\CSVReader3\Position_2016_02_25.0415.csv";
if (vShowBoth == false)
{
//This determines whether to view by account or by underlying.
Console.WriteLine("Please enter 0 if you wish to see sums by account, or 12 if you wish to see by underlying");
int vViewControl = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Account" + " Settle Sum" + " Open Sum" + " Buy Sum" + " Sell Sum");
using (var parsedLines = File.ReadLines(path).Select(line => line.Split(',')).GetEnumerator())
{
bool vMore = parsedLines.MoveNext();
while (vMore)
{
// Initialize
bool vWasSuccessful;
var vAccount = parsedLines.Current[vViewControl];
double vSettleMMSum = 0;
double vOpenSum = 0;
int vBuySum = 0;
int vSellSum = 0;
do
{
double vParseSettleMM = 0;
double vParseOpen = 0;
int vParseBuy = 0;
int vParseSell = 0;
//Parsing data read in from strings, into temp variables
vWasSuccessful = double.TryParse(parsedLines.Current[7], out vParseSettleMM);
vWasSuccessful = double.TryParse(parsedLines.Current[8], out vParseOpen);
vWasSuccessful = int.TryParse(parsedLines.Current[6], out vParseBuy);
vWasSuccessful = int.TryParse(parsedLines.Current[10], out vParseSell);
//adding temp variabels to sum
vSettleMMSum += vParseSettleMM;
vOpenSum += vParseOpen;
vBuySum += vParseBuy;
vSellSum += vParseSell;
vMore = parsedLines.MoveNext();
}
//sets up when to break
while (vMore && vAccount == parsedLines.Current[vViewControl]);
//After each Break need to print out Account name and sums from above.
// Do printing here as part of the loop, at the very end of the loop code block.
Console.WriteLine("--------------------------------------------------------");
Console.WriteLine(vAccount + " " + vSettleMMSum + " " + vOpenSum + " " + vBuySum + " " +
vSellSum);
//vWriteFile.Write(vAccount + "," + vSettleMMSum + "," + vOpenSum + "," + vBuySum + "," +
// vSellSum);
vWriteFile.WriteLine("{0},{1},{2},{3},{4}", vAccount, vSettleMMSum, vOpenSum, vBuySum, vSellSum);
//reset sums for next loop
vSettleMMSum = 0;
vOpenSum = 0;
vBuySum = 0;
vSellSum = 0;
}
}
}
}
I'm working on PHD which entitled "secure localization for wireless sensor networks". I built my own .net simulator and built a localization algorithm over it and make this algorithm secure by implementing an Elliptic Curve Cryptography algorithm. Final step, I need to evaluate the performance of this security algorithm. Can any one help me? thanks in advance.
This is my code:
using System;
using System.IO;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using networkdll;
using Mapack;
using System.Security.Cryptography;
namespace Kalman_Filter_Secure
{
public class Kalman_Filter_Secure
{
public Label enc_label;
public Label dec_label;
public TimeSpan counter1;
public int counter, slot_duration, delimiter = 0, collision_percent;
public DateTime timeStart;
public String path;
public float locatorRadius = 0, sensorRadius = 0, BSSRadius = 0;
public object sender = null;
public PaintEventArgs e = null;
public ArrayList asensor = new ArrayList();
public ArrayList alocator = new ArrayList();
public ArrayList amlocator = new ArrayList();
public ArrayList aBase_Stations = new ArrayList();
public bool mobanchor = false;
//public Random rand = new Random((int)System.DateTime.Now.Ticks);
public Kalman_Filter_Secure(object sender, PaintEventArgs e, ArrayList asensor, ArrayList alocator, ArrayList amlocator, TimeSpan counter1, int slot_duration, String path, float locatorRadius, float sensorRadius, bool mobanchor, int delimiter, int collision_percent, float BSSRadius, ArrayList aBase_Stations, double q,/*double pd,*/ double r_x, double r_y, double r_vx, double r_vy, double ax_noise, double ay_noise, Label encrypt_label, Label decrypt_label)
{
set_parameters(locatorRadius, sensorRadius, counter1, slot_duration, mobanchor, collision_percent, BSSRadius, encrypt_label, decrypt_label);
connectm(asensor, amlocator, aBase_Stations);
Encrypt_Send(asensor);
Receive_Decrypt(asensor);
localize(sender, e, asensor, locatorRadius, path, delimiter, q, r_x, r_y, r_vx, r_vy, ax_noise, ay_noise);
}
public void set_parameters(float locatorRadius, float sensorRadius, TimeSpan counter1, int slot_duration, bool mobanchor, int collision_percent, float BSSRadius, Label encrypt_label, Label decrypt_label)
{
this.enc_label = encrypt_label;
this.dec_label = decrypt_label;
this.locatorRadius = locatorRadius;
this.sensorRadius = sensorRadius;
this.BSSRadius = BSSRadius;
this.counter1 = counter1;
this.slot_duration = slot_duration;
this.mobanchor = mobanchor;
this.collision_percent = collision_percent;
}
public void connectm(ArrayList asensor, ArrayList amlocator, ArrayList aBase_Stations)
{
int sensor_slot = 0, anchor_slot = 0;
//TDMA protocol for collision free
for (int j = amlocator.Count - 1; j >= 0; j--)//anchors slots
{
networkdll.Class1.Locator jLocator = (networkdll.Class1.Locator)amlocator[j];
jLocator.Slot = new ArrayList();
//Base Station Connection
for (int i = 0; i < aBase_Stations.Count; i++)
{
networkdll.Class1.Base_Station BSS = (networkdll.Class1.Base_Station)aBase_Stations[i];
float BSS_lRadius = (float)(Math.Sqrt(Math.Pow(BSS.x - jLocator.x, 2) + Math.Pow(BSS.y - jLocator.y, 2)));//BSS-locator distance
if (BSS_lRadius <= BSSRadius)
{
jLocator.Slot.Add((new networkdll.Class1.Slot(counter1.Milliseconds))); //BSS sensor connection
}
}
System.Threading.Thread.Sleep(0);
}
for (int j = asensor.Count - 1; j >= 0; j--)//sensors slots
{
networkdll.Class1.WirelessSensor jSensor = (networkdll.Class1.WirelessSensor)asensor[j];
jSensor.Slot = new ArrayList();
//Base Station Connection
for (int i = 0; i < aBase_Stations.Count; i++)
{
networkdll.Class1.Base_Station BSS = (networkdll.Class1.Base_Station)aBase_Stations[i];
float BSS_sRadius = (float)(Math.Sqrt(Math.Pow(BSS.x - jSensor.x, 2) + Math.Pow(BSS.y - jSensor.y, 2)));//BSS-sensor distance
if (BSS_sRadius <= BSSRadius)
{
jSensor.Slot.Add((new networkdll.Class1.Slot(counter1.Milliseconds))); //BSS sensor connection
}
}
System.Threading.Thread.Sleep(0);
}
for (int j = 0; j < asensor.Count; j++)
{
networkdll.Class1.WirelessSensor jSensor = (networkdll.Class1.WirelessSensor)asensor[j];
jSensor.apkts = new ArrayList();//anchors packets
jSensor.enc_apkts = new ArrayList();//encrypted anchors packets
jSensor.Connections = new ArrayList();//anchors connection
jSensor.spkts = new ArrayList();//neighbors packets
jSensor.enc_spkts = new ArrayList();//encrypted neighbors packets
jSensor.sConnection = new ArrayList();//neighbors connection
jSensor.two_hop_apkts = new ArrayList();//two hop anchors packets
jSensor.enc_two_hop_apkts = new ArrayList();//encrypted two hop anchors packets
jSensor.two_hop_Connections = new ArrayList();//two hop anchors connection
for (int i = 0; i < amlocator.Count; i++)
{
networkdll.Class1.Locator iLocator = (networkdll.Class1.Locator)amlocator[i];
float lsRadius = (float)(Math.Sqrt(Math.Pow(iLocator.x - jSensor.x, 2) + Math.Pow(iLocator.y - jSensor.y, 2)));
//get the associated slot for this anchor
foreach (networkdll.Class1.Slot Slot in iLocator.Slot)
anchor_slot = Slot.slot;
if (lsRadius <= locatorRadius && counter1.Milliseconds == anchor_slot)
{
jSensor.Connections.Add(new networkdll.Class1.WirelessSensorConnection(iLocator, jSensor)); //MCL-MP
for (int k = i + 1; k < amlocator.Count; k++)//2-hop anchor connections
{
networkdll.Class1.Locator kLocator = (networkdll.Class1.Locator)amlocator[k];
float llRadius = (float)(Math.Sqrt(Math.Pow(iLocator.x - kLocator.x, 2) + Math.Pow(iLocator.y - kLocator.y, 2)));//anchor-anchor distance
float slRadius = (float)(Math.Sqrt(Math.Pow(kLocator.x - jSensor.x, 2) + Math.Pow(kLocator.y - jSensor.y, 2)));//2-hop anchor-sensor distance
//get the associated slot for this anchor
foreach (networkdll.Class1.Slot Slot in kLocator.Slot)
anchor_slot = Slot.slot;
if (llRadius <= locatorRadius && llRadius != 0 && slRadius > locatorRadius && counter1.Milliseconds == anchor_slot)
{
jSensor.two_hop_Connections.Add(new networkdll.Class1.WirelessSensorConnection(kLocator, jSensor)); //2-hop anchors connection
}
}
}
}
for (int k = j + 1; k < asensor.Count; k++)
{
networkdll.Class1.WirelessSensor kSensor = (networkdll.Class1.WirelessSensor)asensor[k];
float ssRadius = (float)(Math.Sqrt(Math.Pow(kSensor.x - jSensor.x, 2) + Math.Pow(kSensor.y - jSensor.y, 2)));
//get the associated slot for this anchor
foreach (networkdll.Class1.Slot Slot in kSensor.Slot)
sensor_slot = Slot.slot;
if (ssRadius <= sensorRadius && counter1.Milliseconds == sensor_slot)
{
jSensor.sConnection.Add(new networkdll.Class1.WirelessSensorConnection(kSensor, jSensor)); //sensor-sensor connection
//2-hop anchor connection via 1-hop sensor
for (int a = 0; a < alocator.Count; a++)
{
networkdll.Class1.Locator kLocator = (networkdll.Class1.Locator)amlocator[a];
float lsRadius = (float)(Math.Sqrt(Math.Pow(kSensor.x - kLocator.x, 2) + Math.Pow(kSensor.y - kLocator.y, 2)));//2-hop anchor-sensor"neighbor" distance
float slRadius = (float)(Math.Sqrt(Math.Pow(kLocator.x - jSensor.x, 2) + Math.Pow(kLocator.y - jSensor.y, 2)));//2-hop anchor-sensor distance
//get the associated slot for this anchor
foreach (networkdll.Class1.Slot Slot in kLocator.Slot)
anchor_slot = Slot.slot;
if (lsRadius <= locatorRadius && lsRadius != 0 && slRadius > locatorRadius && counter1.Milliseconds == anchor_slot)
{
jSensor.two_hop_Connections.Add(new networkdll.Class1.WirelessSensorConnection(kLocator, jSensor)); //2-hop anchors connection
}
}
}
}
}
}
public static class Elliptic_Curve_Cryptography
{
private static Aes DeriveKeyAndIv(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey)
{
privateKey.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash;
privateKey.HashAlgorithm = CngAlgorithm.Sha256;
byte[] keyAndIv = privateKey.DeriveKeyMaterial(publicKey);//derive secret key and initialization vector
byte[] key = new byte[16];
Array.Copy(keyAndIv, 0, key, 0, 16);
byte[] iv = new byte[16];
Array.Copy(keyAndIv, 16, iv, 0, 16);
Aes aes = new AesManaged();
aes.Key = key; //secret (session) key
aes.IV = iv; //initialization vector
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
return aes;
}
public static byte[] Encrypt(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] data)
{
Aes aes = DeriveKeyAndIv(privateKey, publicKey);
return aes.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
}
public static byte[] Decrypt(ECDiffieHellmanCng privateKey, ECDiffieHellmanPublicKey publicKey, byte[] encryptedData)
{
Aes aes = DeriveKeyAndIv(privateKey, publicKey);
return aes.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
}
}
public void Encrypt_Send(ArrayList asensor)
{
ECDiffieHellmanCng Anchor_key = new ECDiffieHellmanCng();//Anchor private key
String plain = "";
String enc = "Encrypted\n";
foreach (networkdll.Class1.WirelessSensor sensor in asensor)
{
ECDiffieHellmanCng Sensor_key = new ECDiffieHellmanCng();//Sensor private key
foreach (networkdll.Class1.WirelessSensorConnection connection in sensor.Connections)//sensor - 1_hop anchor
{
plain = connection.sLocator.id + "," + connection.sLocator.x + ";" + connection.sLocator.y + ".";
byte[] data = Encoding.UTF8.GetBytes(plain);//plain text
byte[] encryptedData = Elliptic_Curve_Cryptography.Encrypt(Anchor_key, Sensor_key.PublicKey, data);//ECC cipher text
String encrypted = Encoding.UTF8.GetString(encryptedData);//encrypted string
sensor.enc_apkts.Add(new networkdll.Class1.enc_pkt(encryptedData, Anchor_key.PublicKey, Sensor_key));
enc += encrypted + "\n";
}
}
enc_label.Text = enc;
}
public void Receive_Decrypt(ArrayList asensor)
{
String dec = "Decrypted\n";
foreach (networkdll.Class1.WirelessSensor sensor in asensor)
{
foreach (networkdll.Class1.enc_pkt packet in sensor.enc_apkts)//sensor - 1-hop anchor
{
byte[] decryptedData = Elliptic_Curve_Cryptography.Decrypt(packet.sensor_private_key, packet.anchor_public_key, packet.Encrypted);
String decrypted = Encoding.UTF8.GetString(decryptedData);
sensor.apkts.Add(new networkdll.Class1.pkt(int.Parse(decrypted.Substring(0, decrypted.IndexOf(","))), int.Parse(decrypted.Substring(decrypted.IndexOf(",") + 1, decrypted.IndexOf(";") - decrypted.IndexOf(",") - 1)), int.Parse(decrypted.Substring(decrypted.IndexOf(";") + 1, decrypted.IndexOf(".") - decrypted.IndexOf(";") - 1))));
dec += decrypted.Substring(0, decrypted.IndexOf(",")) + " (" + decrypted.Substring(decrypted.IndexOf(",") + 1, decrypted.IndexOf(";") - decrypted.IndexOf(",") - 1) + "," + decrypted.Substring(decrypted.IndexOf(";") + 1, decrypted.IndexOf(".") - decrypted.IndexOf(";") - 1) + ")\n";
}
}
dec_label.Text = dec;
}
public void localize(object sender, PaintEventArgs e, ArrayList asensor, float locatorRadius, String path, int delimiter, double q, double r_x, double r_y, double r_vx, double r_vy, double ax_noise, double ay_noise)
{
Font font = new Font("Times New Roman", 7.0f);
StringFormat format = new StringFormat();
format.Alignment = StringAlignment.Center;
Graphics g = e.Graphics;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
Brush abrush = Brushes.PowderBlue; //Actual anchor position
Brush cbrush = Brushes.Purple; //corrected position
//Pen p = Pens.Violet;
// Pen p1 = Pens.Black;
String time = "";
long start, end, executiontime;
start = System.DateTime.Now.Ticks;
int s = 0, count = 0; //sensor index,count for average error
int ersum, avger = 0;//error summation
int comm_cost = 0;//communication cost = no. of packets generated
float coverage = 0; //no. of localized sensor nodes
String ext = "", del = "";//file extension and column delimiter type "comma or tab"
String result = "";
String result1 = "";//cumulate all results for all slot
if (delimiter == 0)
{
del = ","; ext = "xls";
result = "Node" + del + "EstX" + del + "EstY" + del + "ActualX" + del + "ActualY" + del + "Error" + del + "1hAnchor\n";
}
else if (delimiter == 1)
{
del = "\t"; ext = "doc";
result = "Node" + del + "EstX" + del + "EstY" + del + "ActualX" + del + "ActualY" + del + "Error" + del + "1hAnchor\n";
result += "========================================================================\n";
}
float estx = 0, esty = 0;
if (counter1.Minutes == 0)
counter = counter1.Seconds;
else counter = counter1.Seconds + counter1.Minutes * 60;
if (counter % slot_duration == 0)
{
ersum = 0; avger = 0;
s = 0;
foreach (networkdll.Class1.WirelessSensor sensor in asensor)
{
int ax = 0, ay = 0;
/* System.Random rs = new System.Random();//so as to change the random value with every slot
long seed = rs.Next();
Random r = new Random(seed, true);*/
Kalman k = new Kalman();
Random r = new Random();
//measured velocity
double mvx = 0; //sensor.speed * Math.Cos((360 - sensor.direction) * Math.PI / 180.0);
double mvy = 0; //sensor.speed * Math.Sin((360 - sensor.direction) * Math.PI / 180.0);
double velocity = 0, theta = 0;
if ((counter / slot_duration) >= 2)
{
String loca1 = path + "\\state(" + ((counter / slot_duration) - 2) + ")_Sensor(" + s + ")" + ".xls";
String loca2 = path + "\\state(" + ((counter / slot_duration) - 1) + ")_Sensor(" + s + ")" + ".xls";
Matrix predc1 = new Matrix(4, 1);
Matrix predc2 = new Matrix(4, 1);
try
{
//read previous state m_x
using (StreamReader re = new StreamReader(loca1))
{
for (int row = 0; row < 4; row++)
{
string line = re.ReadLine();
string[] values = line.Split(',');
for (int col = 0; col < 1; col++)
{
predc1[row, col] = double.Parse(values[col]);
}
}
}
using (StreamReader re = new StreamReader(loca2))
{
for (int row = 0; row < 4; row++)
{
string line = re.ReadLine();
string[] values = line.Split(',');
for (int col = 0; col < 1; col++)
{
predc2[row, col] = double.Parse(values[col]);
}
}
}
double predc1x = predc1[0, 0];
double predc1y = predc1[1, 0];
double predc2x = predc2[0, 0];
double predc2y = predc2[1, 0];
//measured direction
if (predc1x == predc2x && predc2y > predc1y)
theta = 270;
else if (predc1x == predc2x && predc2y < predc1y)
theta = 90;
else if (predc1y == predc2y && predc2x < predc1x)
theta = 180;
else if (predc1y == predc2y && predc2x > predc1x)
theta = 0;
else
theta = Math.Atan((predc2y - predc1y) / (predc1x - predc2x)) * (180 * 7 / 22);
if (theta < 0)
theta = -theta;
//measured velocity
velocity = (double)(Math.Sqrt(((predc2y - predc1y) * (predc2y - predc1y) + (predc1x - predc2x) * (predc1x - predc2x)))) / (double)slot_duration;
}
catch { velocity = 0; }
}
//measured speed in x and y directions (x',y')
mvx = velocity * Math.Cos((360 - theta) * Math.PI / 180.0);
mvy = velocity * Math.Sin((360 - theta) * Math.PI / 180.0);
////////////////1-hop anchor measurement/////////////////
foreach (networkdll.Class1.pkt packet1 in sensor.apkts) //1-hop anchor packet
{
ax += packet1.x;
ay += packet1.y;
}
/////////////////Slot 0: Reset Kalman Filter////////////////////////////
if (counter / slot_duration == 0)
{
k.Reset(s, path, q, slot_duration, r_x, r_y, r_vx, r_vy, 0, 0, 0, 0);
}
/////////Prediction and Correction Phases/////////////////
if (sensor.apkts.Count >= 1)
{
Matrix state = k.Update(s, path, (counter / slot_duration), (ax / sensor.apkts.Count) + r.NextGuass_Double(0, ax_noise), (ay / sensor.apkts.Count) + r.NextGuass_Double(0, ay_noise), mvx, mvy, slot_duration); //*, px_noise, py_noise*/
float erx, ery;//error (x,y)
estx = (float)state[0, 0];
esty = (float)state[1, 0];
erx = Math.Abs(estx - sensor.x);
ery = Math.Abs(esty - sensor.y);
result += s + del + estx + del + esty + del + sensor.x + del + sensor.y + del + (int)Math.Sqrt(erx * erx + ery * ery) + del + sensor.apkts.Count + "\n";
ersum += (int)Math.Sqrt(erx * erx + ery * ery);//sum error
comm_cost += sensor.apkts.Count;//communication cost
count++;
g.FillEllipse(abrush, ((float)ax / (float)sensor.apkts.Count) - 5, ((float)ay / (float)sensor.apkts.Count) - 5, 10, 10);
g.FillEllipse(cbrush, estx - 5, esty - 5, 10, 10);
g.DrawString("(" + ((int)Math.Sqrt(erx * erx + ery * ery) / sensorRadius).ToString() + ")", font, Brushes.Black, estx + 6, esty + 6);
//writing actual measurements without noise
if (counter / slot_duration == 0)
//Creat file to store actual measurements all slots in one file
using (FileStream fs = new FileStream(path + "\\Actual_Measurement_Sensor(" + s + ")" + ".xls", FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("slot_No,AM_X,AM_Y");
w.WriteLine(counter / slot_duration + "," + (ax / sensor.apkts.Count) + "," + (ay / sensor.apkts.Count));
}
}
else
//Append to file that contains actual measurements
using (FileStream fs = new FileStream(path + "\\Actual_Measurement_Sensor(" + s + ")" + ".xls", FileMode.Append))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine(counter / slot_duration + "," + (ax / sensor.apkts.Count) + "," + (ay / sensor.apkts.Count));
}
}
}
/////storing actual sensor data
double avx = sensor.speed * Math.Cos((360 - sensor.direction) * Math.PI / 180.0);
double avy = sensor.speed * Math.Sin((360 - sensor.direction) * Math.PI / 180.0);
//storing Actual position and velocity of sensor node
if ((counter / slot_duration) == 0)
//Create file to store actual state of sensor
using (FileStream fs = new FileStream(path + "\\Actual_Sensor(" + s + ")" + ".xls", FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine("slot_No,Actual_X,Actual_Y,Actual_X',Actual_Y'");
w.WriteLine((counter / slot_duration) + "," + sensor.x + "," + sensor.y + "," + avx + "," + avy);
}
}
else
//Append to file that contains actual state of sensor
using (FileStream fs = new FileStream(path + "\\Actual_Sensor(" + s + ")" + ".xls", FileMode.Append))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine((counter / slot_duration) + "," + sensor.x + "," + sensor.y + "," + avx + "," + avy);
}
}
s++;
}
end = System.DateTime.Now.Ticks;
executiontime = end - start;
time = " " + (double)(executiontime / 10000);
if (count != 0) { avger = ersum / count; }
if (s != 0 && count != 0) coverage = (float)((float)count / (float)s) * 100;
using (FileStream fs = new FileStream(path + "\\Kalman_of_slot" + (counter / slot_duration) + "." + ext, FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine(result + "\n\n" + "\nAverage" + del + "error = " + del + avger + del + "m" + "\nPercent" + del + " error = " + del + (avger / sensorRadius) + del + "R" + "\nCommunication" + del + "cost = " + del + comm_cost + del + "packet\n" + /*"Computation" + del + "cost =" + del + time + del + "ms\n"*/ "Localized" + del + "sensors =" + del + coverage + del + "%");
w.Dispose(); //allows reading file while simulator opened
}
}
//write all results for all slots
if (delimiter == 1)
result1 += (((counter)) / slot_duration) + del + (avger / sensorRadius) + del + del + del + comm_cost + del + del + /*time*/ del + coverage;
else
result1 += (((counter)) / slot_duration) + del + (avger / sensorRadius) + del + comm_cost + del + /*time*/ coverage;
if (counter == 0)
using (FileStream fs = new FileStream(path + "\\Kalman_total_results." + ext, FileMode.Create))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
if (delimiter == 1)
w.WriteLine("Slot" + del + "Localization" + del + "Communication" + del + /*"Computation"*/ "Localized\nNo." + del + "Error \"R\"" + del + del + "Cost \"packet\"" + del + /*"Cost \"ms\""*/ "Sensors \"%\"\n===================================================================\n" + result1);
else
w.WriteLine("Slot" + del + "Localization" + del + "Communication" + del + /*"Computation"*/"Localized\nNo." + del + "Error \"R\"" + del + "Cost \"packet\"" + del + /*"Cost \"ms\""*/ "Sensors \"%\"\n" + result1);
w.Dispose(); //allows reading file while simulator opened
}
}
else
using (FileStream fs = new FileStream(path + "\\Kalman_total_results." + ext, FileMode.Append))
{
using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
{
w.WriteLine(result1);
w.Dispose(); //allows reading file while simulator opened
}
}
}
// label.Text = output;
// label.Refresh();
}
}
}
You can just use eBATS: ECRYPT Benchmarking of Asymmetric Systems from Dan Bernstein and Tanja Lange (http://bench.cr.yp.to/ebats.html). It is part of eBACS: ECRYPT Benchmarking of Cryptographic Systems.
"If you use eBACS information in a paper then you should cite the web pages as follows:
Daniel J. Bernstein and Tanja Lange (editors). eBACS: ECRYPT Benchmarking of Cryptographic Systems. http://bench.cr.yp.to, accessed 7 March 2013.
Replace 7 March 2013 by your download date."