Hi,

When a try to validate a signed pdf file with  acrobat, the validation is not
ok.

The signatures  is been generated with iaik  pkcs11wrapper and embedded into de
pdf files using itext, (http://itextpdf.sourceforge.net/howtosign.html).

If i sing with a pkc12 keystore  there are not problems, it woeks fine.


How can i generate a valid signature with pkcs11wrapper???

Thanks in advance!!

Ana Vazquez


P.D. This is my code:


 public static String[] firmaPDF(Token token, byte[] contenido, String
numeroSerieCertFirma, String rutaSalida, int visible, String razon, String
location, Session session) throws ErrorAlFirmarException
    {

             try
         {
            String firmaStrB64="";

            String  pKcs7b64="";


         RSAPrivateKey privateSignatureKeyTemplate = new RSAPrivateKey();

privateSignatureKeyTemplate.getSign().setBooleanValue(Boolean.TRUE);

         KeyAndCertificate selectedSignatureKeyAndCertificate =

selectKeyAndCertificate(session,privateSignatureKeyTemplate,numeroSerieCertF
irma);

          X509PublicKeyCertificate pkcs11SignerCertificate =
selectedSignatureKeyAndCertificate.getCertificate();
         X509Certificate signerCertificate = (pkcs11SignerCertificate !=
null)
                                              ? new
X509Certificate(pkcs11SignerCertificate.getValue().getByteArrayValue())
                                              : null;



           if (signerCertificate!=null)
            {


               java.security.cert.X509Certificate []  certificatesX509=new
java.security.cert.X509Certificate[1];

               certificatesX509[0]=signerCertificate;


              PdfReader reader;
        try {
            System.out.println("Creamos el pdf");

         reader = new PdfReader(contenido);

         System.out.println("Numero de paginas  "+
reader.getNumberOfPages());

         ByteArrayOutputStream baos = new ByteArrayOutputStream();
               PdfStamper stp = PdfStamper.createSignature(reader, baos,
'\0');
               System.out.println("Creamos el PdfSignatureAppearance");
               PdfSignatureAppearance sap = stp.getSignatureAppearance();
               System.out.println("firmamos");

               // la firma es externa.
             sap.setCrypto(null, certificatesX509, null,
PdfSignatureAppearance.WINCER_SIGNED);

               sap.setSignDate(Calendar.getInstance());

               if (razon!=null)
                sap.setReason(razon);
               else
                   sap.setReason(ConstantesSIS.RAZON_FIRMA_PDF_DEFAULT);
               if (location!=null)
                sap.setLocation(ConstantesSIS.LOCATION_FIRMA_PDF_DEFAULT);
               if (visible>0)
                    sap.setVisibleSignature(new Rectangle(100, 100, 200,
200), 1, null);

              sap.setExternalDigest(new byte[128],new byte[20], "RSA");

              sap.preClose();


              PdfPKCS7 sig=sap.getSigStandard().getSigner();
              byte [] content=streamToByteArray(sap.getRangeStream());
              byte []
hash=MessageDigest.getInstance("SHA-1").digest(content);

              System.out.println("HASH: " + new String (hash));
              byte[]
signatureBytes=generarFirma(hash,session,selectedSignatureKeyAndCertificate.
getKey());
              System.out.println("firma del hash del pdf: " + new
String(Base64.normalABase64(signatureBytes)));
              sig.setExternalDigest(signatureBytes, hash, "RSA");
              PdfDictionary dic=new PdfDictionary();
              dic.put(PdfName.CONTENTS, new
PdfString(sig.getEncodedPKCS1()).setHexWriting(true));
              sap.close(dic);

            System.out.println("Cerramos sap" );

               //stp.close();


               byte [] firma=Base64.encode(baos.toByteArray());
         String pdfb64=new String ( firma);

         System.out.println("FIRMA:::>>> " + pdfb64);


         if (rutaSalida.equals(""))
         {
            String  args[] = { Resultado.CERTIFICADO_FOUND, pdfb64};

         return  args;
         }
         else
         {
            //Vamos a crear el fichero pdf
          System.out.println("SALVAMOS EL FICERO");
          metodosGenericos.salvarFichero(pdfb64,rutaSalida);

             String  args[] = { Resultado.CERTIFICADO_FOUND,
pdfb64,rutaSalida};
          return  args;
         }


        } catch (Exception e) {

         System.out.println("PROBLEMAS EN LA FIRMA");
            e.toString();
         String  args[] = { Resultado.CERTIFICADO_NOT_FOUND };
         return  args;

        }
       }

           else
           {
               String  args[] = { Resultado.CERTIFICADO_NOT_FOUND };
        return  args;
           }


         }
        catch(Throwable throwable)
     {
      System.out.println("No ha tirado");
     throwable.printStackTrace();
     throw new ErrorAlFirmarException(throwable.toString());
     }

    }


 private static byte[] generarFirma(byte[] hashToBeSigned, Session session,
Key selectedSignatureKey) throws ErrorAlFirmarException {
     try {
         //be sure that your token can process the specified mechanism
         Mechanism signatureMechanism = Mechanism.RSA_PKCS;
         // initialize for signing
         session.signInit(signatureMechanism, selectedSignatureKey);
         // according to PKCS#11 building the DigestInfo structure must be
done off-card
         DigestInfo digestInfoObject = new DigestInfo(AlgorithmID.sha1,
hashToBeSigned);

         byte[] digestInfo = digestInfoObject.toByteArray();

         byte[] firma = session.sign(digestInfo);


         return firma;
        } catch (TokenException e) {

            e.printStackTrace();
            throw new ErrorAlFirmarException("");
        }


    }


Ana Vázquez Núñez
Ingeniero de Consultoria y Desarrollo

C/ Condesa de Venadito, nº 5, 1ª planta
28027 Madrid
Tel.: 914057878* /7855 / 
Fax: 914057888
[EMAIL PROTECTED]
www.panel.es


--------------------------------------------------------------------------------

P Antes de imprimir este correo electrónico piense bien si es necesario 
hacerlo: El medioambiente es cosa de todos. 

Nota Legal: Este correo electrónico puede contener información estrictamente 
confidencial y es de uso exclusivo del destinatario, quedando prohibida a 
cualquier otra persona su revelación, copia, distribución, o el ejercicio de 
cualquier acción relativa a su contenido. Si ha recibido este correo 
electrónico por error, por favor, conteste al remitente, y posteriormente 
proceda a borrarlo de su sistema. Gracias por su colaboración.

Confidentiality notice: This e-mail message may contain confidential and/or 
legally privileged information and is solely for the attention and use of the 
intended recipient. Any disclosure, copying, distribution or the taking of any 
action with relation to the contents of this e-mail by any other person is 
strictly prohibited. If you believe that this e-mail has been mistakenly sent 
to you, please reply to the sender from whom you received the message in error 
and then delete the original e-mail from your system. Thank you for your 
co-operation. 

<<logo_panel_firma.gif>>

-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2005.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/
_______________________________________________
iText-questions mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/itext-questions
Buy the iText book: http://itext.ugent.be/itext-in-action/

Reply via email to