6 comments Wednesday, April 01, 2009

Beside from the security we squeeze from appliance such as firewall and antivirus, it is a must for our applications to have a second layer of defense. Most often than not you already have several company-wide applications that are interconnected to each other. If you have remote offices, your data will be transmitted over broadband network or internet but how sure are you that each of the application is only accepting data from valid sender? For example, a billing software at remote office that transmits payment confirmation to the financial system located at your head office. Fortunately for .NET developers we can make use of digital certificates. Using digital signatures, we can implement the following security check on our example scenario:

Where:
App 1 - Billing Software located at the remote office
App 2 - Financial System located at the head office

1. App 1 sign the unique message using digital certificate private key. For example: "POST TRANSACTION"
2. App 1 send the digital signature to App 2 (via web service or ftp file)
3. App 2 receives the digital signature and verify command by using digital certificate public key

Let's put it in C# Code:

1. Sign the text or message using digital certificate's private key. You can have set of commands that are expected by the client application.


private byte[] SignCertificate(string text)
{
// Open certificate store of current user

X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);
my.Open(OpenFlags.ReadOnly);

// Look for the certificate with specific subject
RSACryptoServiceProvider csp = null;
foreach (X509Certificate2 cert in my.Certificates)
{
if (cert.Subject.Contains("CN=WINGROUP\\micwein"))
{
// retrieve private key
csp = (RSACryptoServiceProvider)cert.PrivateKey;
}
}
if (csp == null)
{
throw new Exception("Valid certificate was not found");
}

// Hash the data
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);

// Sign the hash
return csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
}


2. On your server/listener application, validate the digital signature if correct

private bool VerifyCommand(string text, byte[] signature, string certPath)
{
// Load the certificate file to use to verify the signature from a file
// If using web service or ASP.NET, use: X509Certificate2 cert = new X509Certificate2(Request.ClientCertificate.Certificate);
X509Certificate2 cert = new X509Certificate2(certPath);

// Get public key
RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;

// Hash the text, the text is the expected command by the client application.
// Remember hased data cannot be unhash. It is irreversable
SHA1Managed sha1 = new SHA1Managed();
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] data = encoding.GetBytes(text);
byte[] hash = sha1.ComputeHash(data);

// Verify the signature with the hash
return csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature);
}


Here a sample code on how to call VerifyCommand:

//Use the mycert.cer certificate to verify signature and validate it against the allowed commands
if (VerifyCommand("POST TRANSACTION", signature, @"C:\mycert.cer")) //POST TRANS
{
MessageBox.Show("POST command received from remote client....");
}
else if (VerifyCommand("CANCEL TRANSACTION", signature, @"C:\mycert.cer")) //CANCEL TRANS
{
MessageBox.Show("Cancel command received from remote client....");
}
else if (VerifyCommand("RETRIEVE TRANSACTION", signature, @"C:\mycert.cer")) //RETRIEVE TRANS
{
MessageBox.Show("RETRIEVE Transaction received from remote client....");
}
else
{
MessageBox.Show("Signature is not valid");
}



You can pass the signature to client using web service or FTP. You can download the complete sample source code of this article from here


Continue Reading...
5 comments Sunday, March 29, 2009

One way or another your are already using at least one Google Apps or web service. Today I will show you how easy to integrate Google Apps with your client application. In this article I will use Google Calendar Data to store all schedule event entries or migrate existing calendar events to Google Apps.

The Protocol
Google Calendar allows client applications to add, update and view scheduled events in the form of Google Data API feeds. Possible use of Google Calendar API is we can create a calendar front-end that uses Google Calendar as a database or backend. Another use is to synchonize it to your existing outlook calendar events.

.NET Client Libray
Before you can reference the Google Data APIs you need to download and install the latest MSI release of the client library from here. Take note that the MSI package contains samples that you can use as templates for your next application.

Developing your first Google Data application
1. From Visual Studio 2005 or 2008, Create a new project.
2. Right-click on the project then select Add Reference.
3. Click on the Browse tab and navigate to Redist directory in the SDK ("C:\Program Files\Google\Google Data API SDK\Redist")
4. Select the DLL files that will be used by your project such as Google.GData.Client.dll, Google.GData.Calendar and etc.
5. Cut and paste the following codes:

On Namespace include,


using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Calendar;


On your windows or web form, place two textboxes for username and password. Then cut & paste the following code to login to Google Apps:

private bool GoogleLogin()
{
bool lreturn = false;

try
{
CalendarService service = new CalendarService("CalendarSample");
if (userName != null && userName.Length > 0)
{
service.setUserCredentials(this.UserName.Text, this.Password.Text);
}
catch(Exception ex)
{
Console.WriteLine("Error encountered: " + ex.Message);
}
}


To retrieve all calendar events:

// Create a CalenderService and authenticate
CalendarService myService = new CalendarService("CalendarSample");
myService.setUserCredentials(this.UserName.Text, this.Password.Text);

CalendarQuery query = new CalendarQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/allcalendars/full");
CalendarFeed resultFeed = myService.Query(query);
Console.WriteLine("Calendars Entries:\n");
foreach (CalendarEntry entry in resultFeed.Entries)
{
Console.WriteLine(entry.Title.Text + "\n");
}


To create a new calendar entry just follow this code:

CalendarEntry calendar = new CalendarEntry();
calendar.Title.Text = "Sample Event";
calendar.Summary.Text = "This is a sample entry.";
calendar.TimeZone = "Philippines/Manila";
calendar.Hidden = false;
calendar.Color = "#2952A3";
calendar.Location = new Where("", "", "Manila");

Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
CalendarEntry createdCalendar = (CalendarEntry) myService.Insert(postUri, calendar);


Ofcourse you can also update any calendar event:

CalendarQuery query = new CalendarQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
CalendarFeed resultFeed = myService.Query(query);

//updates the first entry, you can change index
CalendarEntry calendar = (CalendarEntry) resultFeed.Entries[0];
calendar.Title.Text = "Sample Event Again";
calendar.Color = "#A32929";
calendar.Selected = true;
calendar.Update();


To delete an entry, jut call the Delete method.

//this code deletes all entries
CalendarQuery cq = new CalendarQuery();
cq.Uri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
CalendarFeed rf = myService.Query(query);

foreach (CalendarEntry entry in rf.Entries)
{
Console.WriteLine("Deleting calendar: " + entry.Title.Text + "\n");
try
{
entry.Delete();
}
catch (GDataRequestException)
{
Console.WriteLine("Unable to delete calendar.\n");
}
}


There you have it. These are just basic queries and there are a lot more you can do with Google Data APIs. Visit Google Labs for more details. Good Luck!


Continue Reading...