Digital signature for pdf document - digital-signature

I have pdf documents generated by our software.
Is there a way or program that I can call a program from our software and sent it the name of document and folder location and this program will digitally sign the document.
Thanks,
Sol

In case you want to add the digital signature to PDF documents programmatically, you can try GroupDocs.Signature for .NET/Java. You will have to provide the document's path and the digital signature options to sign the document, as described in the following code snippets.
C#:
SignatureConfig Config = new SignatureConfig();
//set the storage path - folder that contains the PDF document
Config.StoragePath = "D:\\storage\\";
// instantiating the signature handler
var Handler = new SignatureHandler(Config);
// setup digital signature options
var SignOptions = new PdfSignDigitalOptions("acer.pfx", "sign.png");
SignOptions.SignAllPages = true;
SignOptions.HorizontalAlignment = Domain.HorizontalAlignment.Center;
SignOptions.VerticalAlignment = Domain.VerticalAlignment.Top;
// sign document
var SignedFilePath = Handler.Sign<string>("Sample.pdf", SignOptions, new SaveOptions { OutputType = OutputType.String });
Java:
// setup Signature configuration
SignatureConfig signConfig = new SignatureConfig();
signConfig.setStoragePath("D:\\Storage\\");
// instantiate handler
SignatureHandler<String> handler = new SignatureHandler<String>(signConfig);
// setup digital signature options
PdfSignDigitalOptions signOptions = new PdfSignDigitalOptions("acer.pfx", "sign.png");
signOptions.setDocumentPageNumber(1);
// set options for the output
SaveOptions saveOptions = new SaveOptions();
saveOptions.setOutputType(OutputType.String);
saveOptions.setOutputFileName("signed_output.pdf");
// sign document
String signedPath = handler.<String>sign("Sample.pdf", signOptions, saveOptions);
Disclosure: I work as Developer Evangelist at GroupDocs.

Related

(Node.js) Create Egypt ITIDA CAdES-BES Signature with Automatic JSON Canonicalization

I am using an example (Node.js Create Egypt ITIDA CAdES-BES Signature with Automatic JSON Canonicalization) but I always get this error ( 4043 4043:message-digest attribute value does not match calculated value[message-digest attribute value does not match calculated value] ).
Can you help me with the solution?
Code Used:
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
var crypt = new chilkat.Crypt2();
crypt.VerboseLogging = true;
var cert = new chilkat.Cert();
cert.VerboseLogging = true;
// Set the smart card PIN, which will be needed for signing.
cert.SmartCardPin = "12345678";
// There are many ways to load the certificate.
// This example was created for a customer using an ePass2003 USB token.
// Assuming the USB token is the only source of a hardware-based private key..
var success = cert.LoadFromSmartcard("");
if (success !== true) {
console.log(cert.LastErrorText);
return;
}
// Tell the crypt class to use this cert.
success = crypt.SetSigningCert(cert);
if (success !== true) {
console.log(crypt.LastErrorText);
return;
}
var cmsOptions = new chilkat.JsonObject();
// Setting "DigestData" causes OID 1.2.840.113549.1.7.5 (digestData) to be used.
cmsOptions.UpdateBool("DigestData",true);
cmsOptions.UpdateBool("OmitAlgorithmIdNull",true);
// Indicate that we are passing normal JSON and we want Chilkat do automatically
// do the ITIDA JSON canonicalization:
cmsOptions.UpdateBool("CanonicalizeITIDA",true);
crypt.CmsOptions = cmsOptions.Emit();
// The CadesEnabled property applies to all methods that create CMS/PKCS7 signatures.
// To create a CAdES-BES signature, set this property equal to true.
crypt.CadesEnabled = true;
crypt.HashAlgorithm = "sha256";
var jsonSigningAttrs = new chilkat.JsonObject();
jsonSigningAttrs.UpdateInt("contentType",1);
jsonSigningAttrs.UpdateInt("signingTime",1);
jsonSigningAttrs.UpdateInt("messageDigest",1);
jsonSigningAttrs.UpdateInt("signingCertificateV2",1);
crypt.SigningAttributes = jsonSigningAttrs.Emit();
// By default, all the certs in the chain of authentication are included in the signature.
// If desired, we can choose to only include the signing certificate:
crypt.IncludeCertChain = false;
var jsonToSign = "{ ... }";
// Create the CAdES-BES signature.
crypt.EncodingMode = "base64";
// Make sure we sign the utf-8 byte representation of the JSON string
crypt.Charset = "utf-8";
var sigBase64 = crypt.SignStringENC(jsonToSign);
if (crypt.LastMethodSuccess == false) {
console.log(crypt.LastErrorText);
return;
}
console.log("Base64 signature:");
console.log(sigBase64);
Check to see if the information at this Chilkat blog post helps: https://cknotes.com/itida-4043message-digest-attribute-value-does-not-match-calculated-value/
See this example for details about debugging and what you can send to Chilkat: https://www.example-code.com/nodejs/itida_egypt_debug.asp
We were having this error, until we were advised of not using any null values in the json file. So, pls try to replace any null values in json file with "".

XAdES creation with manual signature entry

I am trying to create a digitally signed XML document using the signature from my ID card.
I have two parts of the program. The first one is getting the certificates and signature of the file from the ID.
For that I am using python PKCS11 library with something like this:
with open("input.xml", "rb") as f:
data = f.read()
lib = lib('path/to/pkcs11/lib.dylib')
token = lib.get_token('name of token')
with token.open(PIN) as session:
certificate = None
for obj in session.get_objects({Attribute.CLASS: ObjectClass.CERTIFICATE}):
certificate = obj
der_bytes = certificate[Attribute.VALUE]
with open('certificate.der', "wb") as f:
f.write(der_bytes)
# calculate SHA256 of data
digest = session.digest(data, mechanism=Mechanism.SHA256)
for obj in session.get_objects({Attribute.CLASS: ObjectClass.PRIVATE_KEY}):
private_key = obj
signature = private_key.sign(digest, mechanism=Mechanism.RSA_PKCS)
with open('signature', "wb") as f:
f.write(signature)
That generates the certificate.der and signature files and is working properly (at least I think)
For the XML generation part I am using Europe's DSS library in Java like this:
DSSDocument toSignDocument = new FileDocument("input.xml");
// Preparing parameters for the XAdES signature
XAdESSignatureParameters parameters = new XAdESSignatureParameters();
// We choose the level of the signature (-B, -T, -LT, -LTA).
parameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B);
// We choose the type of the signature packaging (ENVELOPED, ENVELOPING, DETACHED).
parameters.setSignaturePackaging(SignaturePackaging.ENVELOPED);
// We set the digest algorithm to use with the signature algorithm. You must use the
// same parameter when you invoke the method sign on the token. The default value is SHA256 parameters.setDigestAlgorithm(DigestAlgorithm.SHA256);
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
InputStream in = new FileInputStream("certificate.der");
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
// We set the signing certificate
parameters.setSigningCertificate(new CertificateToken(cert));
// Create common certificate verifier
CommonCertificateVerifier commonCertificateVerifier = new CommonCertificateVerifier();
// Create XAdES service for signature
XAdESService service = new XAdESService(commonCertificateVerifier);
// Get the SignedInfo XML segment that need to be signed.
ToBeSigned dataToSign = service.getDataToSign(toSignDocument, parameters);
File file = new File("signature");
SignatureValue signatureValue = new SignatureValue(SignatureAlgorithm.RSA_SHA256, Files.readAllBytes(file.toPath()));
// We invoke the service to sign the document with the signature value obtained in
// the previous step.
DSSDocument signedDocument = service.signDocument(toSignDocument, parameters, signatureValue);
File signedFile = new File("output.xml");
signedFile.createNewFile();
signedDocument.writeTo(new FileOutputStream(signedFile, false));
That creates XAdES file, but when I try to validate the signature (e.g. using this) it fails saying the signature is not intact.
What am I doing wrong?
You do not use dataToSign variable at all for signature value creation.
What you should do is by using the private key corresponding to the created certificate to actually sign the digested dataToSign. I.e., instead of:
File file = new File("signature");
SignatureValue signatureValue = new SignatureValue(SignatureAlgorithm.RSA_SHA256, Files.readAllBytes(file.toPath()));
you should do something like this (using your example above):
# calculate SHA256 of data
digest = session.digest(dataToSign, mechanism=Mechanism.SHA256)
for obj in session.get_objects({Attribute.CLASS: ObjectClass.PRIVATE_KEY}):
private_key = obj
signatureValue = private_key.sign(digest, mechanism=Mechanism.RSA_PKCS)
Please pay attention, that you shall sign not the original document, but the dataToSign, as it contains the reference to the original document (its digest), but also signed parameters, required to ensure compliance to AdES format.
I hope this will help you.
Best regards,
Aleksandr.

Docusign embedded signing request from template with nodejs

I am using the nodejs docusign api and am having trouble figuring out how do embedded signing request from template. I kinda want it working the way the example does for non template usage.
The main issue i am having is with the way the nodejs docusign library handles recipientIds when you are using a template, cant set the recipientIds directly when you use the template and doesnt seem to take the recipients set automatically by docusign
Most of my code wasfollowing the quickstart guide
Yes I have read, but found the answers unhelpful.
Docusign embedded signing request from template and Docusign Embedded Signing using template
function makeEnvelope(args){
// create the envelope definition
let env = new docusign.EnvelopeDefinition();
env.templateId = args.templateId;
// Create template role elements to connect the signer and cc recipients
// to the template
// We're setting the parameters via the object creation
let signer1 = docusign.TemplateRole.constructFromObject({
email: args.signerEmail,
name: args.signerName,
clientUserId: '1',
roleName: 'signer'});
// Add the TemplateRole objects to the envelope object
env.templateRoles = [signer1];
env.status = "sent"; // We want the envelope to be sent
return env;
}
{
let dsApiClient = new docusign.ApiClient();
dsApiClient.setBasePath(args.basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
let envelopesApi = new docusign.EnvelopesApi(dsApiClient);
// Step 1. Make the envelope request body (function above)
let envelope = makeEnvelope(args.envelopeArgs)
// Step 2. call Envelopes::create API method
// Exceptions will be caught by the calling function
let results = await envelopesApi.createEnvelope(
args.accountId, {envelopeDefinition: envelope});
return results;
}
function makeRecipientViewRequest(args) {
let viewRequest = new docusign.RecipientViewRequest();
viewRequest.returnUrl = args.dsReturnUrl + "?state=123";
viewRequest.authenticationMethod = 'none';
viewRequest.email = args.signerEmail;
viewRequest.userName = args.signerName;
viewRequest.clientUserId = args.signerClientId;
viewRequest.pingFrequency = 600; // seconds
viewRequest.pingUrl = args.dsPingUrl; // optional setting
return viewRequest
}

How to use Adaptive Cards on Teams Messaging Extension with thumbnail card preview?

I want to send a card to a teams channel using messaging extension. On messaging extension i need to show a preview thumbnail card and onclick of that thumbnail a adaptive card will be displayed.
I have tried the below code and while trying to use "MessagingExtensionResult" its giving error. Also i'm unable to add the dll for "MessagingExtensionResult" its giving incompatible version error. I'm using .Net framework 4.6.
var results = new ComposeExtensionResult()
{
AttachmentLayout = "list",
Type = "result",
Attachments = new List<ComposeExtensionAttachment>(),
};
var card = CardHelper.CreateCardForExperties(pos, true);
var composeExtensionAttachment = card.ToAttachment().ToComposeExtensionAttachment();
results.Attachments.Add(new ComposeExtensionAttachment
{
ContentType = "application/vnd.microsoft.teams.card.adaptive",
Content = JsonConvert.DeserializeObject(updatedJsonString),
Preview = composeExtensionAttachment
});
Using below code we can invoke adaptive card from thumbnail card preview.
ComposeExtensionResponse response = null;
1. var results = new ComposeExtensionResult()
{
AttachmentLayout = "list",
Type = "result",
Attachments = new List<ComposeExtensionAttachment>(),
};
Create a function that returns thumbnail card (preview card)
var previewThumbnailCard = CreateThumbnailCard();
Create a function that returns Adaptive card in form of attachment.
var adaptivecardattachment = CreateAdaptiveCardAsAttachment();
Cast that attachment card to composeextensionattachment and pass
thumbnail card to it as attachment.
var composeExtensionAttachmentAdaptive = adaptivecardattachment .ToComposeExtensionAttachment(previewThumbnailCard.ToAttachment());
Return the response
{
ComposeExtension = results
};
return response;

Signature is Invalid after attaching certificate to the processed pdf document. i am unable to get if there is an issue in code or certificate

I have a signed pdf I am attaching a certificate(.pfx) to the document through itextsharp. Everything in the code is tested and working fine but when I download and open the pdf in acrobat reader it says the signature is not valid I have changed preferences tried almost every setting since yesterday but there isn't any luck.
two things I noticed in certificate detail that for its "intended" property: the DIGITAL signature is not mentioned whereas encrypt document etc is mentioned is this the reason it is not validating the document for signature.
and the second thing it says: certificate has error: not valid for usage
code for attaching certificate;
var pathCert =
Server.MapPath("..../App_Data/Certificates/.....sdd.pfx");
string Password = "**************";
var pass = Password.ToCharArray();
System.Security.Cryptography.X509Certificates.X509Store store =
new System.Security.Cryptography.X509Certificates.X509Store
(Cryptography.X509Certificates.StoreLocation.CurrentUser);
store.Open(System.Security.
Cryptography.X509Certificates.OpenFlags.ReadOnly);
string PfxFileName = pathCert;
string PfxPassword = Password;
System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new
System.Security.Cryptography.X509Certificates.X509Certificate2
(PfxFileName, PfxPassword, Security.Cryptography.X509Certificates.
X509KeyStorageFlags.MachineKeySet);
string SourcePdfFileName = "(Directory)/Desktop/tetsing/test.pdf";
string DestPdfFileName = "(Directory)/Desktop/tetsing/test_Signed.pdf";
Org.BouncyCastle.X509.X509CertificateParser cp = new
Org.BouncyCastle.X509.X509CertificateParser();
Org.BouncyCastle.X509.X509Certificate[] chain = new
Org.BouncyCastle.X509.X509Certificate[] {
cp.ReadCertificate(cert.RawData) };
iTextSharp.text.pdf.security.IExternalSignature externalSignature = new
iTextSharp.text.pdf.security.X509Certificate2Signature(cert, "SHA-1");
PdfReader pdfReader = new PdfReader(SourcePdfFileName);
FileStream signedPdf = new FileStream(DestPdfFileName, FileMode.Create);
//the output pdf file
PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf,
'\0');
PdfSignatureAppearance signatureAppearance =
pdfStamper.SignatureAppearance;
signatureAppearance.Reason = "Signed Document";
signatureAppearance.Location = "Unknown";
signatureAppearance.SignatureRenderingMode =
PdfSignatureAppearance.RenderingMode.DESCRIPTION;
MakeSignature.SignDetached(signatureAppearance, externalSignature,
chain,
null, null, null, 0, CryptoStandard.CMS);
pdfReader.Close();
Adobe acrobat reader is very picky on the certificate key usage and intended purpose (Key Usage and Enhanced Key Usage) and other details of the certificate. Have you tried a certificate with Digital Signature as key usage and Code Signing as intended purpose?
Here is a blog post that shows how to self sign a certificate with that properties for doing signatures if you do not have access to a real publicly trusted signing certificate.
certificate has error: not valid for usage
According to the Adobe Digital Signatures Guide for IT, Adobe Acrobat accepts only
one or more of the following Key usage values (if any)
nonRepudiation
signTransaction (11.0.09 only)
digitalSignature (11.0.10 and later)
and one or more of the following Extended key usage values (if any)
emailProtection
codeSigning
anyExtendedKeyUsage
1.2.840.113583.1.1.5 (Adobe Authentic Documents Trust)
Please check your certificate accordingly and replace it if it does not fulfill this condition.

Resources