+1 vote
by (400 points)
edited

Iam rewriting old delphi aplication which using Chilkat lib for verifying signs in mails and external signs of mail attachments (two files ie. file.pdf and file.p7s). Is possible use Rebex.Security.Cryptography.Pkcs for it? This mens two things. First verify sign for specified file. Second verify sign certificates in p7s file.

Applies to: Rebex Secure Mail

1 Answer

+1 vote
by (147k points)
edited
 
Best answer

Yes, this is possible using the following code:

C#:

	// load the content of a file whose signature we wish to check
	byte[] content = File.ReadAllBytes(@"c:\temp\file.pdf");
	ContentInfo contentInfo = new ContentInfo(content);

	// create a PKCS #7 SignedData object base on this,
	// the second argument specifies "detached" style
	SignedData p7s = new SignedData(contentInfo, true);

	// load the detached signature file
	using (Stream input = File.OpenRead(@"c:\temp\file.p7s"))
	{
		p7s.Load(input);
	}

	// validate the signature and the certificates
	SignatureValidationResult result = p7s.Validate();

	// display the validation result
	if (result.Valid)
	{
		Console.WriteLine("Both signature and certificates are valid.");
	}
	else
	{
		Console.WriteLine("Signature or certificates are NOT valid.");
		Console.WriteLine("Signature problems: {0}", result.Status);
		Console.WriteLine("Certificate problems: {0}", result.CertificateValidationStatus);
	}

In addition to Rebex.Security.Cryptography.Pkcs namespace, this also needs Rebex.Security.Certificates from the same DLL.

For completeness, this is how you would create a detached signature (the file.p7s file) for file.pdf:

C#:

	// get a certificate with a private key
	Certificate certificate = ...

	// load the content of a file we need to sign
	byte[] content = File.ReadAllBytes(@"c:\temp\file.pdf");
	ContentInfo contentInfo = new ContentInfo(content);

	// create a PKCS #7 SignedDat object based on this,
	// the second argument specifies "detached" style
	SignedData p7s = new SignedData(contentInfo, true);

	// add signers
	SignerInfo signer = new SignerInfo(certificate);
	p7s.SignerInfos.Add(signer);

	// create the signature
	p7s.Sign();

	// save the signature into a detached signature file
	using (Stream output = File.Create(@"c:\temp\file.p7s"))
	{
		p7s.Save(output);
	}

If you would like a VB.NET version of this code, just let me know!

by (400 points)
Thank you for quick answer a will try it.
...