title: Using eid-commons and itext - programmatically sign a pdf with a valid signature
body: <p>I see some similar questions on stackoverflow, but I sadly have been unable to come to a solution. I believe I'm quite close but just missing the right steps.</p>
  
  <p>I am using my Belgian EID card, which has signing certificates on it that I can use to sign a PDF.</p>
  
  <p>Maven Libraries used:</p>
  
  <pre><code>be.fedict.commons-eid - 0.6.5
  com.itextpdf - 5.5.10
  org.bouncycastle - 1.55
  </code></pre>
  
  <p>Code is as follows:</p>
  
  <pre><code> BeIDCardManager manager = new BeIDCardManager();
  
          manager.addBeIDCardEventListener(new BeIDCardEventsListener() {
  
         public void eIDCardInserted(CardTerminal arg0, BeIDCard arg1) {
              log.info("Inserted");
              try {
                  dostuffwithmycard(arg1);
              } catch (Exception e) {
                  e.printStackTrace();
              }
            }
         }
  </code></pre>
  
  <p>...</p>
  
  <pre><code>protected static void dostuffwithmycard(BeIDCard card) throws IOException, DocumentException, GeneralSecurityException {
          Security.addProvider(new BeIDProvider());
          KeyStore keyStore = KeyStore.getInstance("BeID");
          keyStore.load(null, null);
          PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
          Signature signature = Signature.getInstance("SHA1withRSA");
          signature.initSign(authnPrivateKey);
  
          PdfReader reader = new PdfReader("C:\\Untitled.pdf");
          FileOutputStream os = new FileOutputStream( "C:\\temp\\Signed.pdf");
          PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
          PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
          appearance.setReason("Okay");
          appearance.setLocation("Home");
          appearance.setVisibleSignature(new Rectangle(36,748,144,780), 1, "sig");
  
          ExternalDigest digest = new BouncyCastleDigest();
          ExternalSignature sig = new PrivateKeySignature(authnPrivateKey,  "SHA1", "BeIDProvider");
  
          MakeSignature.signDetached(appearance, digest, sig, keyStore.getCertificateChain("Signature"), null, null, null, 0, CryptoStandard.CMS);
      }
  </code></pre>
  
  <p>I have basically constructed this code together using trial and error. I have gotten it so that I can actually put my signature on the PDF (after unlocking my signing certificate by inputting the PIN), but when I open the PDF, it tells me the signature is invalid. I can see my name on the signature, but when I try to validate it in Adobe Reader, I am greeted with the error <strong>0x2726</strong></p>
  
  <p>There must be something I am doing wrong, but I have not been able to find the definitive reason.</p>