Tuesday, December 31, 2013

RSA Digital Signature C#

Using .net libraries we can easily implement RSA digital signature scheme. I wrote this blog post to explain how RSA digital signature algorithm works.

Here I get private and public key pair out of rsa object for more understandability of the code.

//Get rsaKeys
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048);
string publicKey = RSA.ToXmlString(false);
string privateKey = RSA.ToXmlString(true);
view raw rsaKeys hosted with ❤ by GitHub

The following method will explain how to sign a message. You need to provide a private key and a message need to be signed. This method will be returned signed message.

//Sign message
/// <summary>
/// Signs the message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="privateKey">The private key.</param>
/// <returns>signed message</returns>
private static string SignMessage(string message, string privateKey)
{
string signedMessage;
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
//Initiate a new instanse with 2048 bit key size
rsa.FromXmlString(privateKey);
// Load private key
signedMessage = Convert.ToBase64String(rsa.SignData(Encoding.UTF8.GetBytes(message), CryptoConfig.MapNameToOID("SHA512")));
//rsa.SignData( buffer, hash algorithm) - For signed data. Here I used SHA512 for hash.
//Encoding.UTF8.GetBytes(string) - convert string to byte messafe
//Convert.ToBase64String(string) - convert back to a string.
}
catch (Exception)
{
signedMessage = string.Empty;
}
return signedMessage;
}
view raw signRsa hosted with ❤ by GitHub

Next step is verify the message that you signed using your private key. You need to pass original message, signed message and public key to method. This method will be returned boolean value verified or not.

//Verify message
/// <summary>
/// Verifies the message.
/// </summary>
/// <param name="originalMessage">The original message.</param>
/// <param name="signedMessage">The signed message.</param>
/// <param name="publicKey">The public key.</param>
/// <returns>verify status</returns>
private static bool VerifyMessage(string originalMessage, string signedMessage, string publicKey)
{
bool verified;
try
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
rsa.FromXmlString(publicKey);
// load public key
verified = rsa.VerifyData(Encoding.UTF8.GetBytes(originalMessage), CryptoConfig.MapNameToOID("SHA512"), Convert.FromBase64String(signedMessage));
}
catch (Exception)
{
verified = false;
}
return verified;
}
view raw verifyRsa hosted with ❤ by GitHub

To this point we are done with methods we need to sign and verify. Lets see how to use them. I wrote it in main method.

//RSA main
static void Main(string[] args)
{
bool verifyState = false;
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048);
string publicKey = RSA.ToXmlString(false);
string privateKey = RSA.ToXmlString(true);
string plainText = "originalMessage";
string tamperMessage = "origiinalMessage";
string signedMessage = SignMessage(plainText, privateKey);
verifyState = VerifyMessage(plainText, signedMessage, publicKey); // return true
verifyState = VerifyMessage(tamperMessage, signedMessage, publicKey); // return false
}
view raw rsaMain hosted with ❤ by GitHub


Tuesday, August 13, 2013

How to create your own ssl certificate

Developers have to use Digital Certificates very often. We can use self signed certificates to our development process rather than buying certificates from certificate authorities.

There are few simple steps to create our own certificates using visual studio.

Step 1

Open visual studio command prompt as administrator. You can get cmd as administrator by right click on short cut exists in visual studio tools and select run as administrator. (Not native windows command prompt)

Step 2:

Change the directory to where you want to create certificates. And type following command.
makecert -sv myKey.pvk -n "cn=My Key" myKey.cer -b 08/13/2013 -e 08/13/2014 -r
view raw genCert hosted with ❤ by GitHub



  • -sv yourprivatekeyfile.pvk is the name of the file containing the private key.
  • -n "cert name" is the name that will appear on the certificate (and in the certificate store).
  • yourcertfile.cer is the name of the certificate file.
  • -b mm/dd/yyyy is the date when the certificate becomes valid.
  • -e mm/dd/yyyy is the date when the certificate expires.
  • -r indicates that this will be a self-signed certificate.


Step 3:

Then you'll be prompted to enter the password for private key.


Step 4:

After you enter password you'll be prompted to enter password for sign certificate.


Step 5: 

This is the final step. Enter following command in cmd

pvk2pfx -pvk myKey.pvk -spc myKey.cer -pfx myKey.pfx
view raw genCert hosted with ❤ by GitHub

Then it'll be prompted to enter private key password. Enter password and that's it.


  • -pvk yourprivatekeyfile.pvk is the private key file that you created
  • -spc yourcertfile.cer is the certificate file you created
  • -pfx yourpfxfile.pfx is the name of the .pfx file that will be created
You can see your certificates in hard disk






Sunday, May 5, 2013

Use Xgraph with NS2

XGRAPH is a general purpose x-y data plotter with interactive buttons for panning, zooming, printing, and selecting display options. It will plot data from any number of files on the same graph and can handle unlimited data-set sizes and any number of data files.

How to Install:
sudo apt-get install xgraph
view raw gistfile1.txt hosted with ❤ by GitHub
This example goes with two previous posts:
1. NS2 UDP Example
2. NS2 TCP Example

You will need both source code to plot ns2 simulations in this example.

Additionally we have to use these perl scripts to extract data from output trace generated from NS2.

# type: perl throughput.pl <trace file> <required node> <granlarity> > output file
$infile=$ARGV[0];
$tonode=$ARGV[1];
$granularity=$ARGV[2];
#we compute how many bytes were transmitted during time interval specified
#by granularity parameter in seconds
$sum=0;
$clock=0;
open (DATA,"<$infile")
|| die "Can't open $infile $!";
while (<DATA>) {
@x = split(' ');
#column 1 is time
if ($x[1]-$clock <= $granularity)
{
#checking if the event corresponds to a reception
if ($x[0] eq 'r')
{
#checking if the destination corresponds to arg 1
if ($x[3] eq $tonode)
{
#checking if the packet type is TCP
if ($x[4] eq 'tcp')
{
$sum=$sum+$x[5];#number of bytes in the period
}
}
}
}
else
{ $throughput=$sum/$granularity;
print STDOUT "$x[1] $throughput\n";
$clock=$clock+$granularity;
$sum=0;
}
}#end while
$throughput=$sum/$granularity;
print STDOUT "$x[1] $throughput\n";
$clock=$clock+$granularity;
$sum=0;
close DATA;
exit(0);
view raw Perltcp.pl hosted with ❤ by GitHub
# type: perl throughput.pl <trace file> <required node> <granlarity> > output file
$infile=$ARGV[0];
$tonode=$ARGV[1];
$granularity=$ARGV[2];
#we compute how many bytes were transmitted during time interval specified
#by granularity parameter in seconds
$sum=0;
$clock=0;
open (DATA,"<$infile")
|| die "Can't open $infile $!";
while (<DATA>) {
@x = split(' ');
#column 1 is time
if ($x[1]-$clock <= $granularity)
{
#checking if the event corresponds to a reception
if ($x[0] eq 'r')
{
#checking if the destination corresponds to arg 1
if ($x[3] eq $tonode)
{
#checking if the packet type is TCP
if ($x[4] eq 'cbr')
{
$sum=$sum+$x[5];#number of bytes in the period
}
}
}
}
else
{ $throughput=$sum/$granularity;
print STDOUT "$x[1] $throughput\n";
$clock=$clock+$granularity;
$sum=0;
}
}#end while
$throughput=$sum/$granularity;
print STDOUT "$x[1] $throughput\n";
$clock=$clock+$granularity;
$sum=0;
close DATA;
exit(0);
view raw Perlcbr.pl hosted with ❤ by GitHub
I have written a shell script to do our job quickly.
#!bin/bash
perl Perltcp.pl outudp.tr 4 0.5 > tcp-udp-one.tr
perl Perlcbr.pl outudp.tr 5 0.5 > tcp-udp-two.tr
xgraph -bg white tcp-udp-one.tr tcp-udp-two.tr &
perl Perltcp.pl outtcp.tr 4 0.5 > tcp-tcp-one.tr
perl Perltcp.pl outtcp.tr 5 0.5 > tcp-tcp-two.tr
xgraph -bg white tcp-tcp-one.tr tcp-tcp-two.tr &
view raw genGraph.sh hosted with ❤ by GitHub
sh genGraph.sh
view raw gistfile1.txt hosted with ❤ by GitHub

Sample out put:
 



NS2 UDP Example

Previously I wrote a blog post about TCP example using NS2. In this post I am posting source code for UDP Example with NS2.

Source code:
# Create a ns object
set ns [new Simulator]
$ns color 1 Blue
$ns color 2 Red
# Open the Trace files
set TraceFile [open outudp.tr w]
$ns trace-all $TraceFile
# Open the NAM trace file
set NamFile [open outudp.nam w]
$ns namtrace-all $NamFile
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.25Mb 100ms DropTail # bottleneck link
$ns duplex-link $n3 $n4 2Mb 10ms DropTail
$ns duplex-link $n3 $n5 2Mb 10ms DropTail
$ns queue-limit $n2 $n3 20
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down
#TCP N0 and N4
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
#FTP TCP N0 and N4
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
#UDP N1 and N5
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_ 2
#CBR N1 and N5
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 500
$cbr set interval_ 0.005
$ns duplex-link-op $n2 $n3 queuePos 0.5
$ns at 0.1 "$ftp start"
$ns at 10.0 "$cbr start"
$ns at 40.0 "$cbr stop"
$ns at 50.0 "$ftp stop"
proc finish {} {
global ns TraceFile NamFile
$ns flush-trace
close $TraceFile
close $NamFile
exec nam outudp.nam &
exit 0
}
$ns at 60.0 "finish"
$ns run
view raw gistfile1.tcl hosted with ❤ by GitHub
Please follow the instruction mentioned in previous post to get output.

Sample screen of output:


Related posts:
http://beyondtechs.blogspot.com/2013/05/ns2-tcp-example.html

NS2 TCP Example

NS2 is a free but a powerful simulator. It is capable to simulate most of complex scenarios in wired and wireless networks.

How to install:
Get your teminal and type this
sudo apt-get install ns2
view raw gistfile1.sh hosted with ❤ by GitHub
Then you'll need NAM

sudo apt-get install nam
view raw gistfile1.txt hosted with ❤ by GitHub
Source code:
# Create a ns object
set ns [new Simulator]
$ns color 1 Blue
$ns color 2 Red
# Open the Trace files
set TraceFile [open outtcp.tr w]
$ns trace-all $TraceFile
# Open the NAM trace file
set NamFile [open outtcp.nam w]
$ns namtrace-all $NamFile
# Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 0.25Mb 100ms DropTail # bottleneck link
$ns duplex-link $n3 $n4 2Mb 10ms DropTail
$ns duplex-link $n3 $n5 2Mb 10ms DropTail
$ns queue-limit $n2 $n3 20
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down
#TCP N0 and N4
set tcp1 [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp1
set sink1 [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink1
$ns connect $tcp1 $sink1
$tcp1 set fid_ 1
$tcp1 set window_ 8000
$tcp1 set packetSize_ 600
#TCP N0 and N4
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ftp1 set type_ FTP
#TCP N1 and N5
set tcp2 [new Agent/TCP/Newreno]
$ns attach-agent $n1 $tcp2
set sink2 [new Agent/TCPSink/DelAck]
$ns attach-agent $n5 $sink2
$ns connect $tcp2 $sink2
$tcp2 set fid_ 2
$tcp2 set window_ 8000
$tcp2 set packetSize_ 600
#FTP TCP N1 and N5
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
$ftp2 set type_ FTP
$ns at 0.1 "$ftp1 start"
$ns at 10.0 "$ftp2 start"
$ns at 50.0 "$ftp1 stop"
$ns at 45.0 "$ftp2 stop"
proc finish {} {
global ns TraceFile NamFile
$ns flush-trace
close $TraceFile
close $NamFile
exec nam outtcp.nam &
exit 0
}
$ns at 60.0 "finish"
$ns run
view raw gistfile1.tcl hosted with ❤ by GitHub
How to run:
ns newTCP.tcl
view raw gistfile1.txt hosted with ❤ by GitHub
You may need to create outtcp.nam file in source code directory.

Sample screen of out put.



Related post:

http://beyondtechs.blogspot.com/2013/05/ns2-udp-example.html

Wednesday, March 6, 2013

Convert object into DataTable C#

Recently I got a requirement in a project to convert own type of object to DataTable. Here I am sharing my code with you.

Steps

1. Create datatable and give a name
DataTable dt = new DataTable();
dt.TableName = "localVehicleDetails";
view raw gistfile1.txt hosted with ❤ by GitHub
2. Create Column Names
foreach (PropertyInfo property in vehicle.GetType().GetProperties())
{
dt.Columns.Add(new DataColumn(property.Name, property.PropertyType));
}
view raw gistfile1.cs hosted with ❤ by GitHub
3. Create a Data Row
DataRow newRow = dt.NewRow();
view raw gistfile1.cs hosted with ❤ by GitHub
4. Add Data in to DataRow
foreach (PropertyInfo property in vehicle.GetType().GetProperties())
{
newRow[property.Name] = vehicle.GetType().GetProperty(property.Name).GetValue(vehicle, null);
}
view raw gistfile1.cs hosted with ❤ by GitHub
5. Add DataRow to DataTable
dt.Rows.Add(newRow);
view raw gistfile1.cs hosted with ❤ by GitHub
Thats it...
Here some Extended Method to how to use this method
public static DataTable SetVehiclesDetails(List<VehicleDetails> vehicleDetailsList)
{
DataTable dt = new DataTable();
try
{
dt.TableName = "localVehicleDetails";
foreach (PropertyInfo property in vehicleDetailsList[0].GetType().GetProperties())
{
dt.Columns.Add(new DataColumn(property.Name, property.PropertyType));
}
foreach (var vehicle in vehicleDetailsList)
{
DataRow newRow = dt.NewRow();
foreach (PropertyInfo property in vehicle.GetType().GetProperties())
{
newRow[property.Name] = vehicle.GetType().GetProperty(property.Name).GetValue(vehicle, null);
}
dt.Rows.Add(newRow);
}
return dt;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return null;
}
}
view raw gistfile1.cs hosted with ❤ by GitHub
https://github.com/cbjpdev/DataTableX