问题
With signtool I can create a PKCS#7 file with the following command
signtool sign /p7 <output dir> /p7co 0 /tr <ts server> /td SHA256 /f <pfx file> /p <pass> /a myfile.zip
I get a slightly larger file signed file with .p7 appended. I can then verify it with
signtool verify /p7 myfile.zip.p7
But what is the recommended way to verify the signature with code and then extract the data? The WinVerifyTrustEx function works fine with PE files, but doesn't like P7 files. It returns 2148204800 ("No Signature was present in the subject"). signtool is not redistributable and it doesn't have an option to extract the data.
回答1:
Based on this other post, there is no out of the box support in .NET. But, I found that you can use the System.Security.Cryptography.Pkcs SignedData to validate but the content seems to be still encoded. So for extracting the actual message, use bouncycastle. I've tried the code below as a sample.
static void Main(string[] args)
{
var encodedFile = File.ReadAllBytes(InPath);
var signedData = new SignedCms();
signedData.Decode(encodedFile);
signedData.CheckSignature(true);
if (!Verify(signedData))
throw new Exception("No valid cert was found");
var trueContent = new CmsSignedData(File.ReadAllBytes(InPath)).SignedContent;
using (var str = new MemoryStream())
{
trueContent.Write(str);
var zip = new ZipArchive(str, ZipArchiveMode.Read);
zip.ExtractToDirectory(OutPath);
}
}
static bool Verify(SignedCms signedData)
{
var myCetificates = new X509Store(StoreName.My, StoreLocation.LocalMachine);
myCetificates.Open(OpenFlags.ReadOnly);
var certs = signedData.Certificates;
return (from X509Certificate2 cert in certs
select myCetificates.Certificates.Cast<X509Certificate2>()
.Any(crt => crt.Thumbprint == cert.Thumbprint))
.Any();
}
来源:https://stackoverflow.com/questions/32641809/how-to-validate-and-extract-pkcs7-file-content-on-windows-c-c