Sei sulla pagina 1di 11

using System;

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using Utility;
using System.Configuration;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.security;
using Org.BouncyCastle.Pkcs;
using iTextSharp.text;
using System.Text;
using Org.BouncyCastle.X509;
using iTextSharp.text.log;
namespace webDigitalSignature
{
public partial class InitiateAutoSign : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["rt"] != null)
{
string RetParam = string.Empty;
string strRT = Convert.ToString(Request.QueryString["rt"]);
int checkedPDF = checkedPDFSign(strRT);

if (checkedPDF == 0)
{
RetParam = getFileName(strRT);
if (RetParam != string.Empty && checkedPDF == 0)
{
xmlSign(RetParam, strRT);
}
else
{
Response.Redirect("Failed.aspx");
}
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType()
, "Message", "alert('Given PDF is already Signed.');window.close();", true);
}
}
}
protected void xmlSign(string RetParam, string strRT)
{
try
{
DataSet ds = intialSign();
if (ds != null && ds.Tables.Count != 0 && ds.Tables[0].Rows.Coun
t != 0)
{
string[] arr = RetParam.Split('|');
string error = string.Empty;
string Token = Convert.ToString(arr[6]);
string AppID = Convert.ToString(arr[5]);
string RU = Convert.ToString(arr[7]);
string certPath = Server.MapPath(ds.Tables[0].Rows[0]["CertP
ath"].ToString());
string certPass = Utility.CryptorEngine.Decrypt(ds.Tables[0]
.Rows[0]["CertPWD"].ToString(), true);
int xPos = Convert.ToInt32(ds.Tables[0].Rows[0]["xPos"]);
int yPos = Convert.ToInt32(ds.Tables[0].Rows[0]["yPos"]);
int PageNo = Convert.ToInt32(ds.Tables[0].Rows[0]["PageNo"])
;
string SignReason = ds.Tables[0].Rows[0]["SignReason"].ToStr
ing();
string SignLocation = ds.Tables[0].Rows[0]["SignLocation"].T
oString();
var store = new X509Store(StoreName.My, StoreLocation.Curren
tUser);
string fileName = Server.MapPath("~/UnsignedPDF/") + Convert
.ToString(ds.Tables[0].Rows[0]["UnsignedFileName"]);
//fileName = CommonFunction.InsertImage(fileName, Token, yPo
s, xPos, PageNo);
string SignedFileName = Server.MapPath("~/SignedPDF/") + Con
vert.ToString(ds.Tables[0].Rows[0]["UnsignedFileName"]);
if (fileName != "")
{
//// Create a collection object and populate it using th
e PFX file
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection collection = new X509Certific
ate2Collection();
collection.Import(certPath, certPass, X509KeyStorageFlag
s.PersistKeySet);
X509Certificate2 cert = new X509Certificate2();
foreach (X509Certificate2 c in collection)
{
cert = c;
}
// Close the store.
store.Close();
string CertCont = Convert.ToBase64String(cert.RawData);
string SerialNo = cert.SerialNumber;
string IssuerDN = cert.Issuer;
string SubjectDN = cert.Subject;
string SignerName = cert.Subject;
string[] arrName = SignerName.Split(',');
SignerName = arrName[0].Replace("CN=", "");
DateTime CertDate = Convert.ToDateTime(cert.GetExpiratio
nDateString());
DateTime CurrentDate = DateTime.Now;
if (CurrentDate <= CertDate)
{
if (IssuerDN != SubjectDN)
{
insertIntialSign(strRT, AppID, CertCont, IssuerD
N, SerialNo, "", "", true, "");
signPdfFile(fileName, SignedFileName, certPath,
certPass, strRT, AppID, Token, yPos, xPos, PageNo, RU, SignReason, SignLocation,
SignerName);
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, th
is.GetType(), "Message", "alert('You do not have a Valid Certificate to Sign PDF
File, Please use Valid Certificate!');location.href='" + RU + "'", true);
return;
}
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, this.G
etType(), "Message", "alert('Certificate Expired. Please Provide Valid Certifica
te!!');window.close();", true);
}
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetTy
pe(), "Message", "alert('We did not find Page No. Where Signature has to be Plac
ed. Please Check the PDF File and Page No.!!');window.close();", true);
return;
}
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType()
, "Message", "alert('Certificate Details not Matched!!');window.close();", true)
;
return;
}
}
catch (Exception ex)
{
string error = Convert.ToString(ex.Message).Replace("\\r\\n", ""
);
if (error.Contains("The specified network password is not correc
t."))
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType()
, "Message", "alert('Certificate Password not Matched!!');window.close();", true
);
}
else
{
Response.Write(ex.Message);
}
}
}

private int checkedPDFSign(string id)


{
using (SqlConnection conn = SQLHelper.OpenConnection())
{
int RetValidParam = 0;
try
{
string[] strobj = Utility.CryptorEngine.Decrypt(id, true).Sp
lit('|');
if (strobj.Length == 2)
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@RowID", SqlDbType.NVarChar
);
param[0].Value = Convert.ToString(strobj[0]);
param[1] = new SqlParameter("@Token", SqlDbType.NVarChar
);
param[1].Value = Convert.ToString(strobj[1]);
string StrQuery = "Select count(rowID) as retParam from
SignedPDF where SignLogID=@RowID and Token=@Token and sign='1'";
RetValidParam = (int)SQLHelper.ExecuteScalar(conn, null,
CommandType.Text, StrQuery, param);
}
}
catch (Exception ee)
{
Utility.ErrorLog.WriteErrorLog(Convert.ToString(Configuratio
nManager.AppSettings["ErrorLogPath"]), "Varify Duplicate Request", ee);
return 0;
}
return RetValidParam;
}
}
private string getFileName(string Id)
{
using (SqlConnection conn = SQLHelper.OpenConnection())
{
string RetParam = string.Empty;
try
{
string[] strobj = Utility.CryptorEngine.Decrypt(Id, true).Sp
lit('|');
if (strobj.Length == 2)
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@RowID", SqlDbType.NVarChar
);
param[0].Value = Convert.ToString(strobj[0]);
param[1] = new SqlParameter("@Token", SqlDbType.NVarChar
);
param[1].Value = Convert.ToString(strobj[1]);
string StrQuery = "Select UnSignedFileName+'|'+RU+'|'+co
nvert(varchar(10), PosX)+'|'+convert(varchar(10), PosY)+'|'+convert(varchar(10),
PageNo)+'|'+AppID+'|'+Token+'|'+RU as RetParam from SignatureLogs where RowID=@
RowID and Token=@Token";
RetParam = (string)SQLHelper.ExecuteScalar(conn, null, C
ommandType.Text, StrQuery, param);
}
}
catch (Exception ee)
{
Utility.ErrorLog.WriteErrorLog(Convert.ToString(Configuratio
nManager.AppSettings["ErrorLogPath"]), "Select File Name", ee);
return string.Empty;
}
return RetParam;
}
}
public void insertIntialSign(string Token, string AppID, string certCont
ent, string issuerDN, string serialNo, string toBeSignedData, string interimPDF,
bool ret, string error)
{
string[] v_Token = Utility.CryptorEngine.Decrypt(Token, true).Split(
'|');
if (v_Token.Length == 2)
{
using (SqlConnection conn = SQLHelper.OpenConnection())
{
int RetParam = 0;
RetParam = getValidRequest(Token);
if (RetParam == 0)
{
using (SqlTransaction objTran = conn.BeginTransaction())
{
//objTran = conn.BeginTransaction();
SqlParameter[] param = new SqlParameter[10];
param[0] = new SqlParameter("@certContent", SqlDbTyp
e.NVarChar);
param[0].Value = certContent;
param[1] = new SqlParameter("@issuerDN", SqlDbType.N
VarChar);
param[1].Value = issuerDN;
param[2] = new SqlParameter("@serialNo", SqlDbType.N
VarChar);
param[2].Value = serialNo;
param[3] = new SqlParameter("@toBeSignedData", SqlDb
Type.NVarChar);
param[3].Value = toBeSignedData;
param[4] = new SqlParameter("@interimPDF", SqlDbType
.NVarChar);
param[4].Value = interimPDF;
param[5] = new SqlParameter("@ret", SqlDbType.Bit);
param[5].Value = (ret == true ? 1 : 0);
param[6] = new SqlParameter("@error", SqlDbType.NVar
Char);
param[6].Value = error;
param[7] = new SqlParameter("@Token", SqlDbType.NVar
Char);
param[7].Value = Convert.ToString(v_Token[1]);
param[8] = new SqlParameter("@SignLogID", SqlDbType.
Int);
param[8].Value = Convert.ToString(v_Token[0]);
param[9] = new SqlParameter("@AppID", SqlDbType.NVar
Char);
param[9].Value = AppID;
try
{
DataSet ds = SQLHelper.ExecuteDataset(conn, objT
ran, CommandType.StoredProcedure, "SP_insertIntialSign", param);
objTran.Commit();
}
catch (Exception ee)
{
objTran.Rollback();
Utility.ErrorLog.WriteErrorLog(Convert.ToString(
ConfigurationManager.AppSettings["ErrorLogPath"]), "insertIntialSign", ee);
}
}
}
else
{
//Records Already Exist.
}
}
}
}
private int getValidRequest(string id)
{
using (SqlConnection conn = SQLHelper.OpenConnection())
{
int RetValidParam = 0;
try
{
string[] strobj = Utility.CryptorEngine.Decrypt(id, true).Sp
lit('|');
if (strobj.Length == 2)
{
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@RowID", SqlDbType.NVarChar
);
param[0].Value = Convert.ToString(strobj[0]);
param[1] = new SqlParameter("@Token", SqlDbType.NVarChar
);
param[1].Value = Convert.ToString(strobj[1]);
string StrQuery = "Select count(rowID) as retParam from
IntialSignDetails where SignLogID=@RowID and Token=@Token";
RetValidParam = (int)SQLHelper.ExecuteScalar(conn, null,
CommandType.Text, StrQuery, param);
}
}
catch (Exception ee)
{
Utility.ErrorLog.WriteErrorLog(Convert.ToString(Configuratio
nManager.AppSettings["ErrorLogPath"]), "Varify Duplicate Request", ee);
return 0;
}
return RetValidParam;
}
}
public DataSet intialSign()
{
if (Request.QueryString["rt"] != null)
{
string RetParam = string.Empty;
RetParam = Convert.ToString(Request.QueryString["rt"]);
using (SqlConnection conn = SQLHelper.OpenConnection())
{
try
{
DataSet ds = null;
string[] strobj = Utility.CryptorEngine.Decrypt(RetParam
, true).Split('|');
if (strobj.Length == 2)
{
using (SqlTransaction objTran = conn.BeginTransactio
n())
{
//objTran = conn.BeginTransaction();
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("@RowID", SqlDbType.
NVarChar);
param[0].Value = Convert.ToString(strobj[0]);
param[1] = new SqlParameter("@Token", SqlDbType.
NVarChar);
param[1].Value = Convert.ToString(strobj[1]);
ds = SQLHelper.ExecuteDataset(conn, objTran, Com
mandType.StoredProcedure, "spGetAutoSignDetails", param);
objTran.Commit();
}
}
return ds;

}
catch (Exception ee)
{
Utility.ErrorLog.WriteErrorLog(Convert.ToString(Configur
ationManager.AppSettings["ErrorLogPath"]), "Fetching Data for Signing", ee);
return null;
}
}
}
else
{
return null;
}
//protected void Page_Unload(object sender, EventArgs e)
//{
// Session.Remove("MyCollections");
//}
}
public void signPdfFile(string filePath, string signedFilePath, string C
ertPath, string keyPassword, string strRT, string AppID, string Token, int yPos,
int xPos, int PageNo, string RU, string SignReason, string SignLocation, string
SignerName)
{
Pkcs12Store pk12 = new Pkcs12Store(new FileStream(CertPath, FileMode
.Open,
FileAccess.Read), keyPassword.ToCharArray
());
//then Iterate throught certificate entries to find the private key
entry
string alias = null;
string SignatureImg = Server.MapPath("~/Images/") + "Signature.png";
foreach (string tAlias in pk12.Aliases)
{
if (pk12.IsKeyEntry(tAlias))
{
alias = tAlias;
break;
}
}
var pk = pk12.GetKey(alias).Key;
// reader and stamper
PdfReader reader = new PdfReader(filePath);
using (FileStream fout = new FileStream(signedFilePath, FileMode.Cre
ate, FileAccess.ReadWrite))
{
Random rnd = new Random();
string signValue = "Signature" + Convert.ToString(rnd.Next(1, 10
0));
// appearance
//PdfStamper stamper = PdfStamper.CreateSignature(reader, fout,
'\0');
PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\
0', null, true);
PdfSignatureAppearance appearance = stamper.SignatureAppearance;
//appearance.Reason = SignReason;
//appearance.Location = SignLocation;
appearance.SignDate = DateTime.Now.Date;
// appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(
xPos, yPos, xPos + 200, yPos + 100), PageNo, "Signature1");//.IsInvisible
appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(xPo
s, yPos, xPos + 200, yPos + 100), PageNo, signValue);//.IsInvisible
// Custom text and background image
appearance.Image = iTextSharp.text.Image.GetInstance(SignatureIm
g);
appearance.ImageScale = 0.6f;
appearance.Image.Alignment = 300;
appearance.Acro6Layers = true;
StringBuilder buf = new StringBuilder();
buf.Append("Digitally Signed by ");
String name = SignerName;
buf.Append(name).Append('\n');
buf.Append("Date: ").Append(DateTime.Now.ToString("dd-MM-yyyy HH
:mm:ss zzz"));
string text = buf.ToString();
appearance.Layer2Text = text;
//digital signature
IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
MakeSignature.SignDetached(appearance, es, new Org.BouncyCastle.
X509.X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, n
ull, 0, CryptoStandard.CMS);
stamper.Close();
}
//string SignedFileName = Server.MapPath("~/SignedPDF/123.pdf");
VerifySignatures(signedFilePath);
//if (VerifySignatures(signedFilePath))
//{
byte[] byt = Utility.CommonFunction.ConvertPDFtoByte(signedFileP
ath);
string signedData = Convert.ToBase64String(byt);
CommonFunction objcomm = new CommonFunction();
try
{
objcomm.insertSignData(strRT, AppID, signedData, "1", "");
}
catch (Exception ee)
{
Utility.ErrorLog.WriteErrorLog(Convert.ToString(Configuratio
nManager.AppSettings["ErrorLogPath"]), "Insert signed pdf and file delete", ee);
}
System.Web.HttpContext.Current.Response.Write("<!DOCTYPE html PU
BLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/x
html1-transitional.dtd'>");
System.Web.HttpContext.Current.Response.Write("<html xmlns='http
://www.w3.org/1999/xhtml'>");
System.Web.HttpContext.Current.Response.Write("<head>");
System.Web.HttpContext.Current.Response.Write("<title>Request</t
itle>");
System.Web.HttpContext.Current.Response.Write("</head>");
System.Web.HttpContext.Current.Response.Write("<body>");
System.Web.HttpContext.Current.Response.Write("<form name='newFo
rm' target='_parent' method='post' action='" + RU + "'>");
System.Web.HttpContext.Current.Response.Write(string.Format("<in
put type=hidden name=\"SignedPdf\" id=\"SignedPdf\" value=\"{0}\">", signedData)
);
System.Web.HttpContext.Current.Response.Write(string.Format("<in
put type=hidden name=\"AppID\" id=\"AppID\" value=\"{0}\">", AppID));
System.Web.HttpContext.Current.Response.Write(string.Format("<in
put type=hidden name=\"Token\" id=\"Token\" value=\"{0}\">", Token));
System.Web.HttpContext.Current.Response.Write("</form>");
System.Web.HttpContext.Current.Response.Write("</body>");
System.Web.HttpContext.Current.Response.Write("</html>");
Response.Write("<SCRIPT LANGUAGE='JavaScript'>document.forms[0].
submit();</SCRIPT>");
File.Delete(filePath);
//File.Delete(signedFilePath);
//}
//else
//{
// ScriptManager.RegisterClientScriptBlock(Page, this.GetType(),
"Message", "alert('Certificate Password not Matched!!');window.close();", true);
//}
}
virtual public PdfPKCS7 VerifySignature(AcroFields fields, String name)
{
Console.WriteLine("Signature covers whole document: " + fields.Signa
tureCoversWholeDocument(name));
Console.WriteLine("Document revision: " + fields.GetRevision(name) +
" of " + fields.TotalRevisions);
PdfPKCS7 pkcs7 = fields.VerifySignature(name);
Console.WriteLine("Integrity check OK? " + pkcs7.Verify());
return pkcs7;
}
public void VerifySignatures(String path)
{
Console.WriteLine(path);
PdfReader reader = new PdfReader(path);
AcroFields fields = reader.AcroFields;
List<String> names = fields.GetSignatureNames();
foreach (string name in names)
{
Console.WriteLine("===== " + name + " =====");
VerifySignature(fields, name);
}
Console.WriteLine();
}
}
}

Potrebbero piacerti anche