martes, 8 de septiembre de 2009

Digital Signature: Digital Signature for Office 2007

Digital Signature: Digital Signature for Office 2007
I HAVE MISSING CLASSES (words in color RED)

namespace TestSignature
{
using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Extensibility;
using Microsoft.Office.Core;
using stdole;
using System.Runtime.InteropServices;
//using System.IO.Packaging;
//using TestSignature.Utils;
//using TestSignature;
using XmlDataObject = System.Security.Cryptography.Xml.DataObject;
#region Read me for Add-in installation and setup information.
// When run, the Add-in wizard prepared the registry for the Add-in.
// At a later time, if the Add-in becomes unavailable for reasons such as:
// 1) You moved this project to a computer other than which is was originally created on.
// 2) You chose 'Yes' when presented with a message asking if you wish to remove the Add-in.
// 3) Registry corruption.
// you will need to re-register the Add-in by building the MyAddin21Setup project
// by right clicking the project in the Solution Explorer, then choosing install.
#endregion
///
/// The object for implementing an Add-in.
///

///
///
[
System.Runtime.InteropServices.ComVisible(true),
System.Runtime.InteropServices.GuidAttribute("AD2CACB9-286D-43a8-BE75-7FB2A86A67A0"),
System.Runtime.InteropServices.ProgId("TestSignature.TestSignatureProvider")
]
public class TestSignatureProvider : Extensibility.IDTExtensibility2,
Microsoft.Office.Core.SignatureProvider
{
#region Constructors
///
/// Implements the constructor for the Add-in object.
/// Place your initialization code within this method.
///

public TestSignatureProvider()
{
}
#endregion Constructors
#region IDTExtensibility2
///
/// Implements the OnConnection method of the IDTExtensibility2 interface.
/// Receives notification that the Add-in is being loaded.
///

///
/// Root object of the host application.
///
///
/// Describes how the Add-in is being loaded.
///
///
/// Object representing this Add-in.
///
///
public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode,
object addInInst, ref System.Array custom)
{
}
///
/// Implements the OnDisconnection method of the IDTExtensibility2 interface.
/// Receives notification that the Add-in is being unloaded.
///

///
/// Describes how the Add-in is being unloaded.
///
///
/// Array of parameters that are host application specific.
///
///
public void OnDisconnection(Extensibility.ext_DisconnectMode disconnectMode, ref System.Array custom)
{
}
///
/// Implements the OnAddInsUpdate method of the IDTExtensibility2 interface.
/// Receives notification that the collection of Add-ins has changed.
///

///
/// Array of parameters that are host application specific.
///
///
public void OnAddInsUpdate(ref System.Array custom)
{
}
///
/// Implements the OnStartupComplete method of the IDTExtensibility2 interface.
/// Receives notification that the host application has completed loading.
///

///
/// Array of parameters that are host application specific.
///
///
public void OnStartupComplete(ref System.Array custom)
{
}
///
/// Implements the OnBeginShutdown method of the IDTExtensibility2 interface.
/// Receives notification that the host application is being unloaded.
///

///
/// Array of parameters that are host application specific.
///
///
///
public void OnBeginShutdown(ref System.Array custom)
{
}
#endregion IDTExtensibility2
#region SignatureProvider
//===================================
// Signature provider implementation
//===================================
public IPictureDisp GenerateSignatureLineImage(SignatureLineImage siglnimg, SignatureSetup sigsetup,
SignatureInfo siginfo, object xmldsigStream)
{
IPictureDisp sigline = null;
System.Drawing.Bitmap draw = new System.Drawing.Bitmap(200, 100);
Graphics g = Graphics.FromImage(draw);
g.DrawRectangle(new Pen(Color.Gray, 2), 0, 0, 200, 100);
if (siglnimg == SignatureLineImage.siglnimgUnsigned)
{
g.FillRectangle(new SolidBrush(Color.LightSlateGray), 2, 2, 196, 96);
g.DrawString("Requested Signature", new System.Drawing.Font("Verdana", 10), new
SolidBrush(Color.Yellow), new PointF(20, 20));
g.DrawString(sigsetup.SuggestedSigner, new System.Drawing.Font("Courier", 8), new
SolidBrush(Color.Yellow), new PointF(20, 50));
}
else if (siglnimg == SignatureLineImage.siglnimgSignedValid)
{
g.FillRectangle(new SolidBrush(Color.LightSlateGray), 2, 2, 196, 96);
g.DrawString("Valid Signature", new System.Drawing.Font("Verdana", 10), new
SolidBrush(Color.LimeGreen), new PointF(20, 20));
g.DrawString(sigsetup.SuggestedSigner, new System.Drawing.Font("Courier", 8), new
SolidBrush(Color.LimeGreen), new PointF(20, 50));
}
else if (siglnimg == SignatureLineImage.siglnimgSignedInvalid)
{
g.FillRectangle(new SolidBrush(Color.LightSlateGray), 2, 2, 196, 96);
g.DrawString("Invalid Signature", new System.Drawing.Font("Verdana", 10), new
SolidBrush(Color.Red), new PointF(20, 20));
g.DrawString(sigsetup.SuggestedSigner, new System.Drawing.Font("Courier", 8), new
SolidBrush(Color.Red), new PointF(20, 50));
}
else
{
g.FillRectangle(new SolidBrush(Color.LightSlateGray), 2, 2, 196, 96);
g.DrawString("Software Required", new System.Drawing.Font("Verdana", 10), new
SolidBrush(Color.AliceBlue), new PointF(20, 20));
}
System.IntPtr hbitmap = draw.GetHbitmap(Color.Green);
Image img = Image.FromHbitmap(hbitmap);
sigline = (IPictureDisp)AxHost2.GetIPictureDispFromPicture(img);
return sigline;
}
public void ShowSignatureSetup(object parentWindow, SignatureSetup sigsetup)
{
bool firstInit = string.IsNullOrEmpty(sigsetup.AdditionalXml);
if (sigsetup != null && !sigsetup.ReadOnly && firstInit)
{
sigsetup.SigningInstructions = "Please sign this document.";
sigsetup.ShowSignDate = true;
sigsetup.AdditionalXml = "";
}
using (Win32WindowFromOleWindow window = new Win32WindowFromOleWindow(parentWindow))
{
using (SignatureSetupForm sigsetupForm = new SignatureSetupForm(sigsetup))
{
sigsetupForm.ShowDialog(window);
if (!sigsetupForm.success && firstInit)
throw new System.Runtime.InteropServices.COMException("Cancelled",
-2147467260 /*E_ABORT*/);
}
}
}
public void ShowSigningCeremony(object parentWindow, SignatureSetup sigsetup, SignatureInfo siginfo)
{
using (Win32WindowFromOleWindow window = new Win32WindowFromOleWindow(parentWindow))
{
if (!((bool)siginfo.GetCertificateDetail(CertificateDetail.certdetAvailable)))
{
MessageBox.Show(window, "You need a digital certificate to sign this document",
"Signing Ceremony", MessageBoxButtons.OK);
throw new System.Runtime.InteropServices.COMException("Cancelled", -2147467260 /*E_ABORT*/);
}
using (SigningCeremonyForm signForm = new SigningCeremonyForm(sigsetup, siginfo))
{
signForm.ShowDialog(window);
if (!signForm.success)
throw new System.Runtime.InteropServices.COMException("Cancelled",
-2147467260 /*E_ABORT*/);
}
}
}
public void SignXmlDsig(object queryContinue, SignatureSetup sigsetup, SignatureInfo siginfo,
object xmldsigStream)
{
using (ComStream comstream = new ComStream(xmldsigStream))
{
XmlDocument xmldsig = new XmlDocument();
xmldsig.PreserveWhitespace = true;
xmldsig.Load(comstream);
XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmldsig.NameTable);
nsmgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
XmlElement signature = xmldsig.DocumentElement;
SignedXml signedXml = new SignedXml();
signedXml.LoadXml(signature);
// Cert
X509Certificate2 cert = TestSignatureProvider.GetSigningCertificate(siginfo);
KeyInfo keyInfo = new KeyInfo();
if (cert.PrivateKey is RSA)
keyInfo.AddClause(new RSAKeyValue((RSA)cert.PrivateKey));
else if (cert.PrivateKey is DSA)
keyInfo.AddClause(new DSAKeyValue((DSA)cert.PrivateKey));
keyInfo.AddClause(new KeyInfoX509Data(cert));
signedXml.SigningKey = cert.PrivateKey;
signedXml.KeyInfo = keyInfo;
// Compute signature
signedXml.ComputeSignature();
// Copy data from signed signature
string[] xpathsToCopy = new string[]
{
"./ds:SignedInfo",
"./ds:SignatureValue",
"./ds:KeyInfo",
};
XmlElement signedSignature = signedXml.GetXml();
foreach (string xpathToCopy in xpathsToCopy)
{
signature.ReplaceChild(
xmldsig.ImportNode(signedSignature.SelectSingleNode(xpathToCopy, nsmgr), true),
signature.SelectSingleNode(xpathToCopy, nsmgr));
}
// Save signature back to stream
comstream.SetLength(0);
comstream.Position = 0;
xmldsig.Save(new XmlTextWriter(comstream, new UTF8Encoding(false)));
}
}
public void NotifySignatureAdded(object parentWindow, SignatureSetup sigsetup, SignatureInfo siginfo)
{
using (Win32WindowFromOleWindow window = new Win32WindowFromOleWindow(parentWindow))
{
MessageBox.Show(window, "Signature has been applied", "Signing Ceremony", MessageBoxButtons.OK);
}
}
public void VerifyXmlDsig(object queryContinue, SignatureSetup sigsetup, SignatureInfo siginfo,
object xmldsigStream, ref ContentVerificationResults contverresults,
ref CertificateVerificationResults certverresults)
{
using (ComStream comstream = new ComStream(xmldsigStream))
{
XmlDocument xmldsig = new XmlDocument();
xmldsig.PreserveWhitespace = true;
xmldsig.Load(comstream);
XmlElement signature = xmldsig.DocumentElement;
SignedXml signedXml = new SignedXml();
signedXml.LoadXml(signature);
contverresults = signedXml.CheckSignature() ?
Microsoft.Office.Core.ContentVerificationResults.contverresValid :
Microsoft.Office.Core.ContentVerificationResults.contverresModified;
}
}
public void ShowSignatureDetails(object parentWindow, SignatureSetup sigsetup, SignatureInfo siginfo,
object xmldsigStream, ref ContentVerificationResults contverresults,
ref CertificateVerificationResults certverresults)
{
Microsoft.Office.Core.COMAddIn
using (Win32WindowFromOleWindow window = new Win32WindowFromOleWindow(parentWindow))
{
using (SigningCeremonyForm signForm = new SigningCeremonyForm(sigsetup, siginfo))
{
signForm.ShowDialog(window);
}
}
}
public object GetProviderDetail(SignatureProviderDetail sigProvDetail)
{
switch (sigProvDetail)
{
case Microsoft.Office.Core.SignatureProviderDetail.sigprovdetHashAlgorithm:
return this.HashAlgorithmIdentifier;
case Microsoft.Office.Core.SignatureProviderDetail.sigprovdetUIOnly:
return false;
case Microsoft.Office.Core.SignatureProviderDetail.sigprovdetUrl:
return this.ProviderUrl;
default:
return null;
}
}
public Array HashStream(object queryContinue, object stream)
{
using (ComStream comstream = new ComStream(stream))
{
using (HashAlgorithm hashalg = HashAlgorithm.Create(this.HashAlgorithmName))
{
return hashalg.ComputeHash(comstream);
}
}
}
protected static X509Certificate2 GetSigningCertificate(SignatureInfo siginfo)
{
X509Store certstore = new X509Store(StoreLocation.CurrentUser);
certstore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = certstore.Certificates.Find(
X509FindType.FindByThumbprint,
siginfo.GetCertificateDetail(Microsoft.Office.Core.CertificateDetail.certdetThumbprint),
false);
if (certs.Count == 1)
return certs[0];
else
return null;
}
#endregion SignatureProvider
#region Properties
public virtual string HashAlgorithmName { get { return "SHA1"; } }
public virtual string HashAlgorithmIdentifier { get { return SignedXml.XmlDsigSHA1Url; } }
public virtual string ProviderUrl { get { return "http://www.microsoft.com"; } }
#endregion Properties
}
}

1 comentario:

Unknown dijo...

You just have posted the complete source code. Its difficult for everyone to make use of this program in proper way.
digital signature Microsoft