Click here to Skip to main content
15,908,445 members
Articles / Programming Languages / C#
Tip/Trick

Digitally sign data

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
3 Sep 2013CPOL 10.5K   6   3
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)


Written By
Technical Lead
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionsign and verify Pin
HassanSabryabdulbary6-Oct-15 0:29
HassanSabryabdulbary6-Oct-15 0:29 
Hi Sanjay

I got some image files to transfer (jpg,bmp,tiff) and also got certificate with sha256 and 2048 block. can you please let me know how can i sign this file using the certificate and verify on the recievers end. my mail is hsabry2605@gmail.com

thanks

hassan
QuestionThank you Pin
faranx4-Sep-13 1:33
professionalfaranx4-Sep-13 1:33 
AnswerRe: Thank you Pin
Sanjay H Modi4-Sep-13 18:23
professionalSanjay H Modi4-Sep-13 18:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.