Menu

#4 Signing a PDF file using Delphi

2.0
closed
zyx
sign pdf (1)
2018-03-13
2018-03-11
No

Hello,

I am using Delphi 10.2.2. I would like to digitally sign an already existed pdf file. I receive no error, but document seems not signed. I believe I am doing something wrong and would like to ask in here.

PEM and KEY files are created using following command:

openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

Below is my code to sign document:

procedure TfrmReport.SignPdf(const FileName: string);
var
  Pdf: TLitePdf;
  SignatureIndex: Cardinal;
  Rect: TRect;
  Handle: HDC;
  PemBytes: TBytes;
  KeyBytes: TBytes;
begin
  Pdf := TLitePDF.Create();
  try
    Pdf.LoadFromFileW(FileName, AnsiString(EmptyStr), True, False);

    Rect.Top  := 100;
    Rect.Left := 100;
    Rect.Width := 50;
    Rect.Height := 50;

    signatureIndex := Pdf.CreateSignature('My Signature Text', 0, Rect, Cardinal(LitePDFAnnotationFlag_None));
    Handle := Pdf.AddResource(50, 50, 50, 50, Cardinal(LitePDFDrawFlag_None));
//    Pdf.SetSignatureAppearance(SignatureIndex, LitePDFAppearance_Normal, Handle, 0, 0);
// I fail to get above command running. So, I simply remark it

    PemBytes := TFile.ReadAllBytes('cert.pem');
    KeyBytes := TFile.ReadAllBytes('key.pem');
    Pdf.AddSignerPEM(Pointer(PemBytes), Length(PemBytes), Pointer(KeyBytes), Length(KeyBytes), 'abc');
    Pdf.SaveToFileW(ExtractFilePath(FileName) + 'signed.pdf');
    Pdf.Close();
  finally
    Pdf.Free();
  end;
end;

I receive no error, but final PDF document seems like a regular file. There is no "SigFlags" text in it as far as I can see, and size of signed.pdf is slightly smaller than the original.

I appreciate any help.

Discussion

  • zyx

    zyx - 2018-03-13

    Hello. Did you look into provided examples? The one for Delphi uses cyptoapi, but those for C++ use openssl. Looking into them you might notice there's used SaveToFileWithSign(), not SaveToFile(). Please, read the documentation and check the examples before filling questions for something what is already answered there. Thanks in advance.

    I tried hard to provide understandable documentation and the examples are there to show how it is supposed to work. Yes, there is no documentation for Pascal interface, but it's close enough to the C++ interface.

    https://litepdf.sourceforge.io/examples.html
    https://litepdf.sourceforge.io/api.html

     
  • zyx

    zyx - 2018-03-13
    • status: open --> closed
     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.