-
Notifications
You must be signed in to change notification settings - Fork 60
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
how to use CustomSignHash delegate #59
Comments
I want to use this class to implement the server signature, but I also need a certificate file, does anyone know how to use this class? |
Hello, @haizzh Let me describe CustomSignHash for you. The CustomSignHash delegate is assigned to the CustomSignHash property of the PKCS7 object. Usual steps in CustomSignHash, cou can implement:
var inputPdf = "test.pdf";
var inputP12 = "test.p12";
var inputPfxPassword = "123456";
var outputPdf = "signed.pdf";
SignHash customSignHash = delegate (byte[] signableHash)
{
X509Certificate2 signerCert = new X509Certificate2(inputP12, inputPfxPassword, X509KeyStorageFlags.Exportable);
using (RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider())
{
// Extract the private key from the certificate
byte[] privateKeyBytes = signerCert.GetRSAPrivateKey().ExportPkcs8PrivateKey();
// Import the private key into the RSACryptoServiceProvider
rsaCSP.ImportPkcs8PrivateKey(privateKeyBytes, out _);
// Sign the hash with the private key
byte[] signedData = rsaCSP.SignData(signableHash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
return signedData;
}
};
using (var sign = new PdfFileSignature())
{
sign.BindPdf(inputPdf);
var pkcs7 = new PKCS7(inputP12, inputPfxPassword);
pkcs7.CustomSignHash = customSignHash;
sign.Sign(1, "reason", "cont", "loc", false, new System.Drawing.Rectangle(0, 0, 500, 500), pkcs7);
sign.Save(outputPdf);
}
using (var sign = new PdfFileSignature())
{
sign.BindPdf(outputPdf);
Assert.IsTrue(sign.VerifySignature("Signature1"));
} Here is another example that helps to find server cert in HSM to sign with: SignHash customSignHash = delegate (byte[] signableHash)
{
using (RSACryptoServiceProvider rsaCsp = new RSACryptoServiceProvider(cspParameters))
{
// Find the private key in the HSM by its thumbprint
rsaCsp.ImportCspBlob(FindPrivateKeyByThumbprint(certificateThumbprint, providerName));
// Sign the hash with the private key
byte[] signedHash = rsaCsp.SignHash(signableHash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return signedHash;
}
}; FindPrivateKeyByThumbprint method should be implemented according to the specifics of the HSM and CSP provider you are using. |
No description provided.
The text was updated successfully, but these errors were encountered: