Tuesday 19 March 2013

How To Use Digital Signature in Asp.net


How To Use Digital Signature in Asp.net 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Text;

public partial class FMS_x509test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        test();
        
    }
    public void test()
    {

        X509Store store = new X509Store("MY", StoreLocation.CurrentUser);
        store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
        //Put certificates from the store into a collection so user can select one.
        X509Certificate2Collection fcollection = (X509Certificate2Collection)store.Certificates;
        X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(fcollection, "Select an X509 Certificate", "Choose a certificate to examine.", X509SelectionFlag.SingleSelection);
        
        X509Certificate2 certificate = collection[0];
       // X509Certificate2UI.DisplayCertificate(certificate);
        RSACryptoServiceProvider csp = null;
        csp = (RSACryptoServiceProvider)certificate.PrivateKey;
        // Hash the data
        SHA1Managed sha1 = new SHA1Managed();
        UnicodeEncoding encoding = new UnicodeEncoding();
        byte[] data = encoding.GetBytes("Lokesh");
        byte[] hash = sha1.ComputeHash(data);
        byte[] signature = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));

       //Verification Code
        
        
        RSACryptoServiceProvider csp1 = (RSACryptoServiceProvider)certificate.PublicKey.Key;

        // Hash the data
        SHA1Managed sha11 = new SHA1Managed();
        UnicodeEncoding encoding1 = new UnicodeEncoding();
        byte[] data1 = encoding.GetBytes("Lokesh");
        byte[] hash1 = sha1.ComputeHash(data1);

        // Verify the signature with the hash
        if (csp1.VerifyHash(hash1, CryptoConfig.MapNameToOID("SHA1"), signature))
        {
            Response.Write("<script language=javascript> alert('correct');</script/>");
        }
        else
        {
            Response.Write("<script language=javascript> alert('No correct');</script/>");
        }


        // Sign text


        // byte[] signature = Sign("Test", "cn=Dashputre Jaideep JYD");
    }
}

2 comments:

  1. tHis support only local not iis ... can u know how to support it on IIS

    ReplyDelete
    Replies
    1. Please refer to complete working solution at http://help.signer.digital/digital_signing_and_authentication_from_web_browser.htm

      Delete