Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Digitally sign data

4.00/5 (1 vote)
3 Sep 2013CPOL 10.7K  
Sign data using private key from a certificate

Introduction

This code digitally sign data using private key from a certificate which can be verified by the receiver.

Using the code

C#
X509Certificate2 cert = 
  new X509Certificate2("Some Certificate File (pfx, p12)", "Certiticate Password");
            
byte[] fileData = System.IO.File.ReadAllBytes("Some File To Be Signed");

//Compute hash using SHA1
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

  • 3rd September 2013.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)