Introduction
This code digitally sign data using private key from a certificate which can be verified by the receiver.
Using the code
X509Certificate2 cert =
new X509Certificate2("Some Certificate File (pfx, p12)", "Certiticate Password");
byte[] fileData = System.IO.File.ReadAllBytes("Some File To Be Signed");
SHA1Managed sha1 = new SHA1Managed();
byte[] dataHash = sha1.ComputeHash(fileData);
ContentInfo ci = new ContentInfo(dataHash);
SignedCms cms = new SignedCms(ci);
CmsSigner signer = new CmsSigner(cert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.Build(cert);
if (chain != null)
{
signer.IncludeOption = X509IncludeOption.None;
X509ChainElementEnumerator enumerator = chain.ChainElements.GetEnumerator();
while (enumerator.MoveNext())
{
X509ChainElement current = enumerator.Current;
signer.Certificates.Add(current.Certificate);
}
}
signer.DigestAlgorithm = new Oid("SHA1");
cms.ComputeSignature(signer);
byte[] signedData = cms.Encode();
History