私は「ワイヤレスセンサーネットワークの安全なローカリゼーション」というタイトルのPHDに取り組んでいます。私は独自の.netシミュレーターを構築し、その上にローカリゼーションアルゴリズムを構築し、楕円曲線暗号アルゴリズムを実装することでこのアルゴリズムを安全にしました。最後のステップとして、このセキュリティアルゴリズムのパフォーマンスを評価する必要があります。誰か助けてもらえますか?前もって感謝します。これは私のコードです:
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();
}
}
}