Changeset 276a8db in murachi


Ignore:
Timestamp:
Aug 24, 2015, 5:44:09 PM (9 years ago)
Author:
antonioaraujob <aaraujo@…>
Branches:
master
Children:
c4dd8d1
Parents:
6837e71
Message:

Se organizan funciones en el código.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • murachi/src/main/java/ve/gob/cenditel/murachi/MurachiRESTWS.java

    r99d1e61 r276a8db  
    33import static java.util.Arrays.asList;
    44
    5 import java.io.BufferedReader;
    65import java.io.ByteArrayInputStream;
    76import java.io.ByteArrayOutputStream;
    87import java.io.File;
    98import java.io.FileInputStream;
    10 import java.io.FileNotFoundException;
    119import java.io.FileOutputStream;
    1210import java.io.IOException;
    1311import java.io.InputStream;
    14 import java.io.InputStreamReader;
    1512import java.io.ObjectInputStream;
    1613import java.io.ObjectOutputStream;
    1714import java.io.OutputStream;
    1815import java.net.URISyntaxException;
    19 import java.net.URL;
    2016import java.nio.file.Files;
    2117import java.nio.file.Paths;
     
    39703966       
    39713967       
    3972        
    3973         // ************************************************************************
    3974         // ************************************************************************
    3975         // ************************************************************************
    3976 
    3977         // pruebas de funciones para gestionar un contenedor BDOC
    3978        
    3979         @GET
    3980         @Path("/pruebaBDOC")
    3981         @Produces("text/plain")
    3982         public String testBDOCFunctions()  {
    3983                
    3984                 Security.addProvider(new BouncyCastleProvider());
    3985                
    3986                 Container c = createBDOCContainer();
    3987                
    3988                 String containerId = UUID.randomUUID().toString();
    3989                 System.out.println(containerId);
    3990                
    3991                 if (c==null)
    3992                 {
    3993                         System.out.println("container == null");
    3994                 }
    3995                 else
    3996                 {
    3997                         System.out.println("container != null");
    3998                 }
    3999                
    4000                 addFileToBDOCContainer("/tmp/slides-93-cfrg-9.pdf", c);
    4001                
    4002                 System.out.println("numero de archivos en el contenedor: " + Integer.toString(c.getDataFiles().size()));
    4003                
    4004                 PKCS12Signer PKCS12_SIGNER = new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray());
    4005                
    4006                 SignatureParameters signatureParameters = new SignatureParameters();
    4007                 SignatureProductionPlace productionPlace = new SignatureProductionPlace();
    4008                 productionPlace.setCity("Merida");
    4009                 productionPlace.setStateOrProvince("Merida");
    4010                 productionPlace.setPostalCode("5101");
    4011                 productionPlace.setCountry("Venezuela");
    4012                 signatureParameters.setProductionPlace(productionPlace);
    4013                 logger.debug("container setProductionPlace");
    4014                 signatureParameters.setRoles(asList("Desarrollador"));
    4015                 c.setSignatureParameters(signatureParameters);
    4016                 c.setSignatureProfile(SignatureProfile.B_BES);
    4017                
    4018                 c.sign(PKCS12_SIGNER);
    4019                
    4020                
    4021                 if (deleteDataFileFromBDOCContainer("/tmp/slides-93-cfrg-9.pdf", c))
    4022                 {
    4023                         System.out.println("eliminado archivo del contenedor");
    4024                 }
    4025                 else
    4026                 {
    4027                         System.out.println("NO se eliminó el archivo del contenedor");
    4028                 }
    4029                        
    4030                 if (deleteSignatureFromBDOCContainer(0, c))
    4031                 {
    4032                         System.out.println("SE ELIMINO la firma 2");
    4033                 }
    4034                 else
    4035                 {
    4036                         System.out.println("no se pudo eliminar la firma 0");
    4037                 }
    4038                
    4039                 System.out.println("numero de firmas restantes: "+ Integer.toString(c.getSignatures().size()));
    4040                
    4041                 c.save("/tmp/prueba.bdoc");
    4042                
    4043                 return "prueba exitosa";
    4044         }
    4045        
    4046         @GET
    4047         @Path("/serializar")
    4048         @Produces("text/plain")
    4049         public String serialize()  {
    4050                
    4051                 logger.debug("recurso /serializar");
    4052                
    4053                 Security.addProvider(new BouncyCastleProvider());
    4054                
    4055                 Container c;
    4056                 try {
    4057                         c = deserialize("/tmp/container.bin");
    4058                         logger.debug("deserializado contenedor");
    4059                        
    4060                         logger.debug("numero de firmas: "+ Integer.toString(c.getSignatures().size()));
    4061                        
    4062                         Security.addProvider(new BouncyCastleProvider());
    4063                        
    4064                         //c.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray()));
    4065                                                
    4066                         //c.save("/tmp/deserializado.bdoc");
    4067                        
    4068                         if (c.getSignatures().size() > 0) {
    4069                         ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    4070                         c.save(byteOut);
    4071                         ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
    4072                        
    4073                         //Configuration configuration = initConfig(); // also need to re-initialize configuration settings
    4074                        
    4075                         Configuration configuration = new Configuration(Configuration.Mode.PROD);               
    4076                         configuration.loadConfiguration("/tmp/digidoc4j.yaml");
    4077                         configuration.setTslLocation("file:///tmp/venezuela-tsl.xml");       
    4078                        
    4079                         Container container2 = Container.open(byteIn, configuration);
    4080                         container2.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray()));
    4081                        
    4082                         System.out.println("********numero de firmas deserialize : "+ Integer.toString(container2.getSignatures().size()));
    4083                         container2.save("/tmp/deserializado2.bdoc");
    4084 
    4085                     }
    4086                        
    4087                        
    4088                        
    4089                 } catch (ClassNotFoundException | IOException e) {
    4090                         e.printStackTrace();
    4091                        
    4092                         logger.error("ClassNotFoundException | IOException e");
    4093                         return "error ClassNotFoundException | IOException e";
    4094                        
    4095                 }
    4096                
    4097                        
    4098                 return "prueba exitosa";
    4099         }
    4100        
     3968
    41013969       
    41023970        /**
     
    42694137       
    42704138       
    4271         // ************************************************************************
    4272         // ************************************************************************
    4273         // ************************************************************************
     4139       
    42744140       
    42754141        private static void verifyBdocContainer(Container container) {
     
    43584224
    43594225       
    4360        
    4361         /**
    4362          * Verifica si un archivo posee firmas electronicas y retorna informacion
    4363          * de las mismas en un json
    4364          * @param idFile
    4365          * @return
    4366          */
    4367         @GET
    4368         @Path("/verificar/{idFile}")
    4369         //@Produces("application/json")
    4370         @Produces("text/plain")
    4371         public String verifyFile(@PathParam("idFile") String idFile) {
    4372                
    4373                 String file = SERVER_UPLOAD_LOCATION_FOLDER + idFile;
    4374        
    4375                 //return getMimeType(file);
    4376                
    4377                                
    4378                 File tmpFile = new File(file);
    4379                 String result = "";
    4380 
    4381                
    4382                
    4383                
    4384                 if (tmpFile.exists()) {
    4385                         result = "El archivo existe.";
    4386                        
    4387                         try {
    4388                                 PdfReader reader = new PdfReader(file);
    4389                                 AcroFields af = reader.getAcroFields();
    4390                                 ArrayList<String> names = af.getSignatureNames();
    4391                                 if (names.size() > 0) {
    4392                                         result = "el archivo PDF posee "+ names.size() +" firma(s).\n";
    4393                                        
    4394                                         // sin esto explota: se debe agregar una implementacion del provider en tiempo de ejecucion
    4395                                         //http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/jce/provider/BouncyCastleProvider.html
    4396                                         Security.addProvider(new BouncyCastleProvider());
    4397                                        
    4398                                         for (String name: names) {
    4399                                                 result = result +"Nombre de la firma: "+ name + "\n";
    4400                                                 System.out.println("Nombre de la firma: "+ name);
    4401                                                
    4402                                                 PdfPKCS7 pk = af.verifySignature(name);
    4403                                                
    4404                                                 Certificate[] pkc = pk.getCertificates();
    4405                                                
    4406                                                 String tmpSignerName = pk.getSigningCertificate().getSubjectX500Principal().toString();
    4407                                                
    4408                                                
    4409                                                 result = result + "Sujeto del certificado firmante: " + tmpSignerName + "\n";
    4410                                                 //pk.getSigningCertificate().getSubjectX500Principal().getName() + "\n";
    4411                                                 System.out.println("Sujeto del certificado firmante: " +
    4412                                                                 pk.getSigningCertificate().getSubjectX500Principal().toString());
    4413                                                  
    4414                                                 Calendar cal = pk.getSignDate();
    4415                                                
    4416                                                 SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    4417                                                
    4418                                                 //result = result + "Fecha de la firma: " + cal.toString() + "\n";
    4419                                                 result = result + "Fecha de la firma: " + date_format.format(cal.getTime()) + "\n";
    4420                                                
    4421                                                 /*
    4422                                                 System.out.println("año: "+ cal.get(Calendar.YEAR));
    4423                                                 System.out.println("mes: "+ (cal.get(Calendar.MONTH) + 1));
    4424                                                 System.out.println("día: "+ cal.get(Calendar.DAY_OF_MONTH));
    4425                                                 System.out.println("hora: "+ cal.get(Calendar.HOUR));
    4426                                                 System.out.println("minuto: "+ cal.get(Calendar.MINUTE));
    4427                                                 System.out.println("segundo: "+ cal.get(Calendar.SECOND));
    4428                                                 */
    4429                                                 //SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
    4430                                             System.out.println(date_format.format(cal.getTime()));
    4431 
    4432                                         }
    4433                                        
    4434                                        
    4435                                 }else{
    4436                                         result = "el archivo PDF no posee firmas";
    4437                                 }
    4438                                
    4439                                
    4440                                
    4441                         } catch (IOException e) {
    4442 
    4443                                 e.printStackTrace();
    4444                         }
    4445                        
    4446                        
    4447                 }else {
    4448                         result = "El archivo NO existe.";
    4449                 }
    4450                
    4451                
    4452                 return result;
    4453                
    4454                
    4455         }
    4456        
    4457         /**
    4458          * Ejecuta el proceso de presign o preparacion de firma de documento pdf
    4459          * @param presignPar
    4460          * @param req objeto request para crear una sesion y mantener elementos del
    4461          * pdf en la misma
    4462          * @param resp
    4463          */
    4464         @POST
    4465         @Path("/prepararfirmapdf")
    4466         @Consumes(MediaType.APPLICATION_JSON)
    4467         @Produces(MediaType.APPLICATION_JSON)
    4468         //public Response presign(PresignParameters presignPar, @Context HttpServletRequest req) {
    4469         public PresignHash presign(PresignParameters presignPar, @Context HttpServletRequest req) {
    4470                
    4471 
    4472                 // cadena resultado de la funcion
    4473                 String result = "";
    4474                
    4475                 PresignHash presignHash = new PresignHash();
    4476                
    4477                
    4478                 // cadena con el certificado
    4479                 String certHex = presignPar.getCertificate();
    4480                 System.out.println("certificado en Hex: " + certHex);
    4481                
    4482                 // obtener el id del archivo
    4483                 String fileId = presignPar.getFileId();
    4484                                
    4485                 try {
    4486                         CertificateFactory factory = CertificateFactory.getInstance("X.509");
    4487                         Certificate[] chain = new Certificate[1];
    4488                        
    4489                         InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
    4490                         chain[0] = factory.generateCertificate(in);
    4491                        
    4492                         if (chain[0] == null) {
    4493                                 System.out.println("error chain[0] == null");
    4494                         }else {
    4495                                
    4496                                 System.out.println("se cargo el certificado correctamente");
    4497                                 System.out.println(chain[0].toString());
    4498                         }
    4499                        
    4500                         //String pdf = SERVER_UPLOAD_LOCATION_FOLDER + "e27a6a90-f955-4191-8e54-580e316a999d";
    4501                         String pdf = SERVER_UPLOAD_LOCATION_FOLDER + fileId;
    4502                         System.out.println("archivo a firmar: " + pdf);
    4503                        
    4504                         PdfReader reader = new PdfReader(pdf);
    4505                        
    4506                         ByteArrayOutputStream baos = new ByteArrayOutputStream();
    4507                        
    4508                         //FileOutputStream baos = new FileOutputStream(pdf+"-signed.pdf");
    4509                        
    4510                         PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
    4511                        
    4512                         // crear la apariencia de la firma
    4513                 PdfSignatureAppearance sap = stamper.getSignatureAppearance();
    4514                 sap.setReason("Prueba de firma en dos partes");
    4515                 sap.setLocation("Merida, Venezuela");
    4516                 sap.setVisibleSignature(new Rectangle(36, 748, 144,780),1, "sig");
    4517                 sap.setCertificate(chain[0]);
    4518                
    4519                 // crear la estructura de la firma
    4520                 PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
    4521                 dic.setReason(sap.getReason());
    4522                 dic.setLocation(sap.getLocation());
    4523                 dic.setContact(sap.getContact());
    4524                 dic.setDate(new PdfDate(sap.getSignDate()));
    4525                
    4526                 sap.setCryptoDictionary(dic);
    4527                
    4528                 HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer> ();
    4529                 exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
    4530                 sap.preClose(exc);
    4531                
    4532                 ExternalDigest externalDigest = new ExternalDigest() {
    4533                         public MessageDigest getMessageDigest(String hashAlgorithm)
    4534                         throws GeneralSecurityException {
    4535                                 return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
    4536                         }
    4537                 };
    4538                        
    4539                        
    4540                 PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
    4541                
    4542                 InputStream data = sap.getRangeStream();
    4543                
    4544                 byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
    4545                
    4546                 Calendar cal = Calendar.getInstance();
    4547                 byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
    4548                
    4549                 sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
    4550                
    4551                 System.out.println("sh length: "+ sh.length);
    4552                        
    4553                 String hashToSign = byteArrayToHexString(sh);
    4554                 System.out.println("***************************************************************");
    4555                 System.out.println("HASH EN HEXADECIMAL:");
    4556                 System.out.println(hashToSign);
    4557                 System.out.println("length: " +hashToSign.length());   
    4558                 System.out.println("***************************************************************");
    4559                        
    4560                 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    4561                         Date date = new Date();
    4562                         System.out.println(dateFormat.format(date));
    4563                         //String d = dateFormat.format(date);
    4564                        
    4565                        
    4566                         // almacenar los objetos necesarios para realizar el postsign en una sesion
    4567                         HttpSession session = req.getSession(true);
    4568                         session.setAttribute("hashToSign", hashToSign);
    4569                        
    4570                         session.setAttribute("stamper", stamper);
    4571                         session.setAttribute("sgn", sgn);
    4572                         session.setAttribute("hash", hash);
    4573                         session.setAttribute("cal", cal);
    4574                         session.setAttribute("sap", sap);
    4575                         session.setAttribute("baos", baos);
    4576                         session.setAttribute("fileId", fileId);
    4577                        
    4578                         // creacion del json
    4579                         JSONObject jsonHash = new JSONObject();
    4580                         jsonHash.put("hashToSign", hashToSign);
    4581                        
    4582                         result = jsonHash.toString();
    4583                        
    4584                         presignHash.setHash(hashToSign);
    4585                                
    4586                        
    4587                 } catch (CertificateException e1) {
    4588                         // TODO Auto-generated catch block
    4589                         e1.printStackTrace();
    4590                 } catch (IOException e) {
    4591                         // TODO Auto-generated catch block
    4592                         e.printStackTrace();
    4593                 } catch (DocumentException e) {
    4594                         // TODO Auto-generated catch block
    4595                         e.printStackTrace();
    4596                 } catch (InvalidKeyException e) {
    4597                         // TODO Auto-generated catch block
    4598                         e.printStackTrace();
    4599                 } catch (NoSuchProviderException e) {
    4600                         // TODO Auto-generated catch block
    4601                         e.printStackTrace();
    4602                 } catch (NoSuchAlgorithmException e) {
    4603                         // TODO Auto-generated catch block
    4604                         e.printStackTrace();
    4605                 } catch (GeneralSecurityException e) {
    4606                         // TODO Auto-generated catch block
    4607                         e.printStackTrace();
    4608                 }
    4609                
    4610                 //return Response.status(200).entity(result).build();
    4611                 return presignHash;
    4612                        
    4613         }
    4614        
    4615        
    4616         /**
    4617          * Ejecuta el proceso de postsign o completacion de firma de documento pdf
    4618          * @param postsignPar
    4619          * @param req objeto request para crear una sesion y mantener elementos del
    4620          * pdf en la misma
    4621          * @param resp
    4622          * @throws IOException
    4623          */
    4624         @POST
    4625         @Path("/completarfirmapdf")
    4626         @Consumes(MediaType.APPLICATION_JSON)
    4627         @Produces(MediaType.APPLICATION_JSON)
    4628         public Response postsign(PostsignParameters postsignPar, @Context HttpServletRequest req) throws IOException {
    4629                
    4630                
    4631                 // cadena resultado de la funcion
    4632                 String result = "";
    4633                                
    4634                 // cadena con la firma
    4635                 String signature = postsignPar.getSignature();
    4636                 System.out.println("firma en Hex: " + signature);
    4637                
    4638                 HttpSession session = req.getSession(false);
    4639                
    4640                 String fileId = (String) session.getAttribute("fileId");
    4641                 System.out.println("fileId: " + fileId);
    4642                
    4643                 PdfStamper stamper = (PdfStamper) session.getAttribute("stamper");
    4644                
    4645                 PdfPKCS7 sgn = (PdfPKCS7) session.getAttribute("sgn");
    4646                
    4647                 byte[] hash = (byte[]) session.getAttribute("hash");
    4648                
    4649                 Calendar cal = (Calendar) session.getAttribute("cal");
    4650                
    4651                 PdfSignatureAppearance sap = (PdfSignatureAppearance) session.getAttribute("sap");
    4652                
    4653                 ByteArrayOutputStream os = (ByteArrayOutputStream) session.getAttribute("baos");
    4654                
    4655                 if (sgn == null) {
    4656                         System.out.println("sgn == null");
    4657                 }
    4658                 if (hash == null) {
    4659                         System.out.println("hash == null");
    4660                 }
    4661                 if (cal == null) {
    4662                         System.out.println("cal == null");
    4663                 }
    4664                 if (sap == null) {
    4665                         System.out.println("sap == null");
    4666                 }
    4667                 if (os == null) {
    4668                         System.out.println("os == null");
    4669                 }
    4670                
    4671                
    4672                
    4673                 // convertir signature en bytes         
    4674                 byte[] signatureInBytes = hexStringToByteArray(signature);
    4675                                
    4676                 // completar el proceso de firma
    4677                 sgn.setExternalDigest(signatureInBytes, null, RSA_DIGEST_ENCRYPTION_ALGORITHM);
    4678                 byte[] encodeSig = sgn.getEncodedPKCS7(hash, cal, null, null, null, CryptoStandard.CMS);
    4679                 byte[] paddedSig = new byte[8192];
    4680                 System.arraycopy(encodeSig, 0, paddedSig, 0, encodeSig.length);
    4681                 PdfDictionary dic2 = new PdfDictionary();
    4682                 dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
    4683                 try {
    4684                         sap.close(dic2);
    4685                        
    4686                         stamper.close();
    4687                         System.out.println("stamper.close");
    4688                        
    4689                 }catch(DocumentException e) {
    4690                        
    4691                         System.out.println("throw new IOException");
    4692                         throw new IOException(e);
    4693                        
    4694                 } catch (IOException e) {
    4695                         // TODO Auto-generated catch block
    4696                         System.out.println("IOException e");
    4697                         e.printStackTrace();
    4698                        
    4699                 }
    4700                
    4701                 String signedPdf = SERVER_UPLOAD_LOCATION_FOLDER + fileId + "-signed.pdf";
    4702                
    4703                 FileOutputStream signedFile = new FileOutputStream(signedPdf);
    4704                
    4705                 os.writeTo(signedFile);
    4706                 os.flush();
    4707                
    4708                
    4709                
    4710                 // en este punto el archivo pdf debe estar disponible en la ruta
    4711                 // SERVER_UPLOAD_LOCATION_FOLDER + fileId;
    4712                
    4713                 // llamar a una funcion que permita descargar el archivo
    4714                
    4715                 result = "Archivo firmado correctamente";
    4716                 System.out.println("Archivo firmado correctamente");
    4717                
    4718                 return Response.status(200).entity(result).build();
    4719         }
    4720        
    4721         /**
    4722          * Ejecuta el proceso de presign o preparacion de firma de documento en formato BDOC
    4723          *
    4724          * @param presignPar
    4725          * @param req
    4726          * @return
    4727          */
    4728         @POST
    4729         @Path("/bdoc/")
    4730         @Consumes(MediaType.APPLICATION_JSON)
    4731         @Produces(MediaType.APPLICATION_JSON)
    4732         public PresignHash presignBdoc2(PresignParameters presignPar, @Context HttpServletRequest req) {
    4733                
    4734                 System.out.println("presignBdoc2: ");
    4735                
    4736                
    4737                 String fileId;
    4738                 String certHex;
    4739                
    4740                 CertificateFactory cf;
    4741                 X509Certificate signerCert;
    4742                
    4743                 // cadena resultado de la funcion
    4744                 String result = "";
    4745                                
    4746                 PresignHash presignHash = new PresignHash();
    4747                
    4748                 SignedInfo signedInfo;
    4749                
    4750                 fileId = presignPar.getFileId();
    4751                 String sourceFile = SERVER_UPLOAD_LOCATION_FOLDER + fileId;
    4752                
    4753                 certHex = presignPar.getCertificate();
    4754                 System.out.println("certificado en Hex: " + certHex);
    4755                
    4756 //              try {
    4757                         /*             
    4758                         Configuration configuration = new Configuration(Configuration.Mode.TEST);
    4759                        
    4760                         configuration.loadConfiguration("/home/aaraujo/desarrollo/2015/workspace-luna/JAXRS-Murachi/WebContent/WEB-INF/lib/digidoc4j.yaml");
    4761                         configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
    4762                    
    4763                         Container container = Container.create(configuration);
    4764                     SignatureParameters signatureParameters = new SignatureParameters();
    4765                     SignatureProductionPlace productionPlace = new SignatureProductionPlace();
    4766                     productionPlace.setCity("Merida");
    4767                     signatureParameters.setProductionPlace(productionPlace);
    4768                     signatureParameters.setRoles(asList("Desarrollador"));
    4769                     container.setSignatureParameters(signatureParameters);
    4770                     container.setSignatureProfile(SignatureProfile.B_BES);
    4771                     container.addDataFile("/tmp/215d6ef7-d639-4191-87a1-ef68a91b2b27", "text/plain");
    4772                     container.sign(new PKCS12Signer("/tmp/JuanHilario.p12", "123456".toCharArray()));
    4773 //                  Container container = Container.open("util/faulty/bdoc21-bad-nonce-content.bdoc");
    4774                     container.save("/tmp/signed.bdoc");
    4775                     ValidationResult results = container.validate();
    4776                     System.out.println(results.getReport());
    4777                         */
    4778 
    4779                        
    4780                 Security.addProvider(new BouncyCastleProvider());
    4781                         System.setProperty("digidoc4j.mode", "TEST");
    4782                        
    4783                         Configuration configuration;
    4784                         configuration = new Configuration(Configuration.Mode.TEST);
    4785                         //configuration.loadConfiguration("/home/aaraujo/desarrollo/2015/workspace-luna/JAXRS-Murachi/WebContent/WEB-INF/lib/digidoc4j.yaml");
    4786                        
    4787                         //configuration.setTslLocation("https://tibisay.cenditel.gob.ve/murachi/raw-attachment/wiki/WikiStart/trusted-test-mp.xml");
    4788                         configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
    4789                        
    4790                         Container container;
    4791                        
    4792                         container = Container.create(Container.DocumentType.BDOC, configuration);
    4793                        
    4794                         SignatureParameters signatureParameters = new SignatureParameters();
    4795                     SignatureProductionPlace productionPlace = new SignatureProductionPlace();
    4796                     productionPlace.setCity("Merida");
    4797                     signatureParameters.setProductionPlace(productionPlace);
    4798                     signatureParameters.setRoles(asList("Desarrollador"));
    4799                     container.setSignatureParameters(signatureParameters);
    4800                     container.setSignatureProfile(SignatureProfile.B_BES);
    4801                        
    4802                         container.addDataFile(sourceFile, "text/plain");
    4803                        
    4804                         container.sign(new PKCS12Signer("/tmp/JuanHilario.p12", "123456".toCharArray()));
    4805                     container.save("/tmp/signed.bdoc");
    4806                     ValidationResult results = container.validate();
    4807                     System.out.println(results.getReport());
    4808                        
    4809                         /*
    4810                         cf = CertificateFactory.getInstance("X.509");
    4811                
    4812                         InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
    4813                        
    4814                         signerCert = (X509Certificate) cf.generateCertificate(in);
    4815                        
    4816                         signedInfo = container.prepareSigning(signerCert);
    4817                        
    4818                         String hashToSign = byteArrayToHexString(signedInfo.getDigest());
    4819                         //System.out.println("presignBdoc - hash: " + byteArrayToHexString(signedInfo.getDigest()));
    4820                         System.out.println("presignBdoc - hash: " + hashToSign);
    4821                        
    4822                        
    4823                         //container.save("/tmp/containerTmp.bdoc");
    4824                         serialize(container, "/tmp/containerSerialized");
    4825                         */
    4826                        
    4827                         String hashToSign = "firma exitosa";
    4828                        
    4829                         // creacion del json
    4830                         JSONObject jsonHash = new JSONObject();
    4831                         jsonHash.put("hashToSign", hashToSign);
    4832                                                
    4833                         result = jsonHash.toString();
    4834                                                
    4835                         presignHash.setHash(hashToSign);
    4836                        
    4837                        
    4838 /*                     
    4839                 } catch (CertificateException e1) {
    4840                         // TODO Auto-generated catch block
    4841                         e1.printStackTrace();
    4842                 } catch (IOException e) {
    4843                         // TODO Auto-generated catch block
    4844                         e.printStackTrace();
    4845                 }
    4846 */             
    4847                
    4848                 return presignHash;
    4849                
    4850         }
    4851        
    4852        
    4853         @GET
    4854         @Path("/testbdoc/")
    4855         public String testBdoc() {
    4856                
    4857                 Security.addProvider(new BouncyCastleProvider());
    4858                
    4859                 Configuration configuration = new Configuration(Configuration.Mode.PROD);
    4860                
    4861                 configuration.loadConfiguration("/tmp/digidoc4j.yaml");
    4862                 //configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
    4863                 configuration.setTslLocation("file:///tmp/venezuela-tsl.xml");
    4864                
    4865             Container container = Container.create(configuration);
    4866             SignatureParameters signatureParameters = new SignatureParameters();
    4867             SignatureProductionPlace productionPlace = new SignatureProductionPlace();
    4868             productionPlace.setCity("Merida");
    4869             signatureParameters.setProductionPlace(productionPlace);
    4870             signatureParameters.setRoles(asList("Desarrollador"));
    4871             container.setSignatureParameters(signatureParameters);
    4872             container.setSignatureProfile(SignatureProfile.B_BES);
    4873             container.addDataFile("/tmp/salida.txt", "text/plain");
    4874             container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
    4875 //          Container container = Container.open("util/faulty/bdoc21-bad-nonce-content.bdoc");
    4876             container.save("/tmp/signed.bdoc");
    4877             ValidationResult result = container.validate();
    4878             System.out.println(result.getReport());
    4879                
    4880                 return "test";
    4881         }
    4882        
    4883         /**
    4884          * Prueba de agregar una firma electrónica a un contenedor existente.
    4885          *
    4886          * NOTA: A un contenedor que posee una firma no se le pueden agregar nuevos DataFiles.
    4887          * @return
    4888          */
    4889         @GET
    4890         @Path("/addsignaturebdoc/")
    4891         public String addSignatureBdoc() {
    4892                 logger.debug("/addsignaturebdoc/");
    4893                
    4894                 Security.addProvider(new BouncyCastleProvider());
    4895                
    4896                 Configuration configuration = new Configuration(Configuration.Mode.PROD);
    4897                
    4898                 configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION);
    4899                
    4900                 configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION);
    4901                                
    4902                 //String bdocFile = "/tmp/c1d099ad-44b3-4227-82fa-8c8f03746787.bdoc";
    4903                 String bdocFile = "/tmp/twoSignatures.bdoc";
    4904                
    4905                 Container container = Container.open(bdocFile, configuration);
    4906                 logger.debug("open container: "+ bdocFile);
    4907                
    4908             SignatureParameters signatureParameters = new SignatureParameters();
    4909            
    4910             SignatureProductionPlace productionPlace = new SignatureProductionPlace();
    4911             productionPlace.setCity("Merida");
    4912             productionPlace.setStateOrProvince("Merida");
    4913             productionPlace.setPostalCode("5101");
    4914             productionPlace.setCountry("Venezuela");
    4915            
    4916             signatureParameters.setProductionPlace(productionPlace);
    4917            
    4918             signatureParameters.setRoles(asList("Desarrollador"));
    4919            
    4920             container.setSignatureParameters(signatureParameters);
    4921            
    4922             container.setSignatureProfile(SignatureProfile.B_BES);
    4923                    
    4924             logger.debug("signing: "+ bdocFile);
    4925             container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
    4926 
    4927             String outputFile = "/tmp/threeSignatures.bdoc";
    4928             container.save(outputFile);
    4929             logger.debug("saved file in : "+ outputFile);
    4930            
    4931             ValidationResult result = container.validate();
    4932             System.out.println(result.getReport());
    4933                
    4934                 return "success";
    4935         }
    4936        
    4937        
    4938        
    4939         /**
    4940          * Prueba de ejecucion de programa desde consola. Incompleta
    4941          * @return
    4942          * @throws InterruptedException
    4943          */
    4944         @GET
    4945         @Path("/ejecutar")
    4946         @Produces("text/plain")
    4947         public String executeProcess() throws InterruptedException {
    4948                
    4949                 String s = "9712f235-4dd4-4b09-957d-b06c33af482b-serialized.bin";
    4950                 String[] array = s.split("-serialized\\.bin");
    4951                
    4952                 return array[0];
    4953                
    4954                
    4955                
    4956                 /*
    4957                 String line = "";
    4958                 OutputStream stdin = null;
    4959                 InputStream stderr = null;
    4960                 InputStream stdout = null;
    4961                
    4962                 try {
    4963                         System.out.print("...a crear el proceso");
    4964                         Process process = Runtime.getRuntime().exec("/usr/java/jdk1.7.0_21/bin/java -jar /home/aaraujo/desarrollo/2015/servicioVerificacion/testsigningpdf/holamundopdf.jar /tmp/589750.pdf /tmp/simonDiaz.pem /tmp/firmadoconsola.pdf");
    4965                         //Process process = Runtime.getRuntime().exec("ls -l");
    4966                         stdin = process.getOutputStream();
    4967                         stderr = process.getErrorStream();
    4968                         stdout = process.getInputStream();
    4969                        
    4970                         InputStreamReader isr = new InputStreamReader(stdout);
    4971                         BufferedReader buff = new BufferedReader (isr);
    4972 
    4973                        
    4974                         while((line = buff.readLine()) != null)
    4975                                 System.out.print(line+"\n");
    4976                         int exitValue = process.waitFor();
    4977                         if (exitValue != 0) {
    4978                             System.out.println("Abnormal process termination");
    4979                         }       
    4980                        
    4981                 } catch (IOException e) {
    4982                         // TODO Auto-generated catch block
    4983                         e.printStackTrace();
    4984                 }
    4985                 System.out.print("...saliendo");
    4986                 return line;
    4987                 */
    4988         }
    4989        
    4990        
    4991        
    4992        
    4993        
    4994         /**
    4995          *
    4996          * @param certHex
    4997          * @param httpHeaders
    4998          * @param req
    4999          * @param resp
    5000          */
    5001         @POST
    5002         @Path("/presignOld")
    5003         @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    5004         public void presignOld(
    5005                         @FormParam("certHexInForm") String certHex,
    5006                         @Context HttpHeaders httpHeaders,
    5007                         @Context HttpServletRequest req,
    5008                         @Context HttpServletResponse resp) {
    5009                
    5010 
    5011                 String host = httpHeaders.getRequestHeader("host").get(0);
    5012                
    5013                 String agent = httpHeaders.getRequestHeader("user-agent").get(0);
    5014                 String salida = "User agent :"+ agent +" from host : "+host;
    5015                 System.out.println(host);
    5016                 System.out.println(agent);
    5017                 System.out.println(salida);
    5018                
    5019                 System.out.println("certificado en Hex: " + certHex);
    5020                
    5021                 try {
    5022                         CertificateFactory factory = CertificateFactory.getInstance("X.509");
    5023                         Certificate[] chain = new Certificate[1];
    5024                        
    5025                         InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
    5026                         chain[0] = factory.generateCertificate(in);
    5027                        
    5028                         if (chain[0] == null) {
    5029                                 System.out.println("error chain[0] == null");
    5030                         }else {
    5031                                
    5032                                 System.out.println("se cargo el certificado correctamente");
    5033                                 System.out.println(chain[0].toString());
    5034                         }
    5035                        
    5036                         String pdf = SERVER_UPLOAD_LOCATION_FOLDER + "e27a6a90-f955-4191-8e54-580e316a999d";
    5037                        
    5038                         PdfReader reader = new PdfReader(pdf);
    5039                         ByteArrayOutputStream baos = new ByteArrayOutputStream();
    5040                         PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
    5041                        
    5042                         // crear la apariencia de la firma
    5043                 PdfSignatureAppearance sap = stamper.getSignatureAppearance();
    5044                 sap.setReason("Prueba de firma en dos partes");
    5045                 sap.setLocation("Merida, Venezuela");
    5046                 sap.setVisibleSignature(new Rectangle(36, 748, 144,780),1, "sig");
    5047                 sap.setCertificate(chain[0]);
    5048                
    5049                 // crear la estructura de la firma
    5050                 PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
    5051                 dic.setReason(sap.getReason());
    5052                 dic.setLocation(sap.getLocation());
    5053                 dic.setContact(sap.getContact());
    5054                 dic.setDate(new PdfDate(sap.getSignDate()));
    5055                
    5056                 sap.setCryptoDictionary(dic);
    5057                
    5058                 HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer> ();
    5059                 exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
    5060                 sap.preClose(exc);
    5061                
    5062                 ExternalDigest externalDigest = new ExternalDigest() {
    5063                         public MessageDigest getMessageDigest(String hashAlgorithm)
    5064                         throws GeneralSecurityException {
    5065                                 return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
    5066                         }
    5067                 };
    5068                        
    5069                        
    5070                 PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
    5071                
    5072                 InputStream data = sap.getRangeStream();
    5073                
    5074                 byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
    5075                
    5076                 Calendar cal = Calendar.getInstance();
    5077                 byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
    5078                
    5079                 sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
    5080                
    5081                 System.out.println("sh length: "+ sh.length);
    5082                        
    5083                 String hashToSign = byteArrayToHexString(sh);
    5084                 System.out.println("***************************************************************");
    5085                 System.out.println("HASH EN HEXADECIMAL:");
    5086                 System.out.println(hashToSign);
    5087                 System.out.println("length: " +hashToSign.length());   
    5088                 System.out.println("***************************************************************");
    5089                        
    5090                 DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    5091                         Date date = new Date();
    5092                         System.out.println(dateFormat.format(date));
    5093                         String d = dateFormat.format(date);
    5094                        
    5095                        
    5096                         // almacenar los objetos necesarios para realizar el postsign en una sesion
    5097                         HttpSession session = req.getSession(true);
    5098                         session.setAttribute("hashToSign", hashToSign);
    5099                        
    5100                         session.setAttribute("sgn", sgn);
    5101                         session.setAttribute("hash", hash);
    5102                         session.setAttribute("cal", cal);
    5103                         session.setAttribute("sap", sap);
    5104                         session.setAttribute("baos", baos);
    5105                        
    5106                
    5107                        
    5108                         resp.sendRedirect("http://localhost/murachi2.html");
    5109                        
    5110                        
    5111                 } catch (CertificateException e1) {
    5112                         // TODO Auto-generated catch block
    5113                         e1.printStackTrace();
    5114                 } catch (IOException e) {
    5115                         // TODO Auto-generated catch block
    5116                         e.printStackTrace();
    5117                 } catch (DocumentException e) {
    5118                         // TODO Auto-generated catch block
    5119                         e.printStackTrace();
    5120                 } catch (InvalidKeyException e) {
    5121                         // TODO Auto-generated catch block
    5122                         e.printStackTrace();
    5123                 } catch (NoSuchProviderException e) {
    5124                         // TODO Auto-generated catch block
    5125                         e.printStackTrace();
    5126                 } catch (NoSuchAlgorithmException e) {
    5127                         // TODO Auto-generated catch block
    5128                         e.printStackTrace();
    5129                 } catch (GeneralSecurityException e) {
    5130                         // TODO Auto-generated catch block
    5131                         e.printStackTrace();
    5132                 }
    5133                
    5134                
    5135        
    5136         }
    5137        
    5138        
    5139         @POST
    5140         @Path("/postsign")
    5141         public String postsignOld(@Context HttpServletRequest req,
    5142                         @Context HttpServletResponse resp) {
    5143                
    5144                 System.out.println("...postsign()...");
    5145                
    5146                 HttpSession session = req.getSession(false);
    5147                 Object att = session.getAttribute("hashToSign");
    5148                                
    5149        
    5150                 String output = "atributo leido de la sesion: " + att.toString();
    5151                
    5152                
    5153                 return output;
    5154                 //return Response.status(200).entity(output).build();
    5155         }
    5156        
    5157        
    5158         @GET
    5159         @Path("/retornajson")
    5160         @Produces(MediaType.APPLICATION_JSON)
    5161         public PresignHash retornajson(@Context HttpServletRequest req) {
    5162                
    5163                
    5164                
    5165                 PresignHash h = new PresignHash();
    5166                 h.setHash("ESTO SERIA UN HASH");
    5167                
    5168                 System.out.println("...retornajson..."+ h.getHash());
    5169                
    5170                 return h;
    5171                
    5172         }
    5173        
    5174         @POST
    5175         @Path("/enviarjson")
    5176         @Consumes(MediaType.APPLICATION_JSON)
    5177         @Produces(MediaType.APPLICATION_JSON)
    5178         public PresignHash recibejson( PresignParameters par) {
    5179                
    5180                 String fileId = par.getFileId();
    5181                 System.out.println("...fileId recibido..."+ fileId);
    5182                
    5183                 String cert = par.getCertificate();
    5184                 System.out.println("...certificate recibido..."+ cert);
    5185                
    5186                 PresignHash h = new PresignHash();
    5187                 h.setHash("DEBES FIRMAR ESTO");
    5188                
    5189                 System.out.println("...recibejson..."+ h.getHash());
    5190                
    5191                 return h;
    5192                
    5193         }
    5194        
    5195        
    5196        
     4226
    51974227       
    51984228        /**
     
    53594389          }
    53604390         
     4391         
     4392        // ************************************************************************
     4393        // ************************************************************************
     4394        // ************************************************************************
     4395         
     4396         
     4397       
     4398
     4399        // pruebas de funciones para gestionar un contenedor BDOC
     4400               
     4401                @GET
     4402                @Path("/pruebaBDOC")
     4403                @Produces("text/plain")
     4404                public String testBDOCFunctions()  {
     4405                       
     4406                        Security.addProvider(new BouncyCastleProvider());
     4407                       
     4408                        Container c = createBDOCContainer();
     4409                       
     4410                        String containerId = UUID.randomUUID().toString();
     4411                        System.out.println(containerId);
     4412                       
     4413                        if (c==null)
     4414                        {
     4415                                System.out.println("container == null");
     4416                        }
     4417                        else
     4418                        {
     4419                                System.out.println("container != null");
     4420                        }
     4421                       
     4422                        addFileToBDOCContainer("/tmp/slides-93-cfrg-9.pdf", c);
     4423                       
     4424                        System.out.println("numero de archivos en el contenedor: " + Integer.toString(c.getDataFiles().size()));
     4425                       
     4426                        PKCS12Signer PKCS12_SIGNER = new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray());
     4427                       
     4428                        SignatureParameters signatureParameters = new SignatureParameters();
     4429                        SignatureProductionPlace productionPlace = new SignatureProductionPlace();
     4430                        productionPlace.setCity("Merida");
     4431                        productionPlace.setStateOrProvince("Merida");
     4432                        productionPlace.setPostalCode("5101");
     4433                        productionPlace.setCountry("Venezuela");
     4434                        signatureParameters.setProductionPlace(productionPlace);
     4435                        logger.debug("container setProductionPlace");
     4436                        signatureParameters.setRoles(asList("Desarrollador"));
     4437                        c.setSignatureParameters(signatureParameters);
     4438                        c.setSignatureProfile(SignatureProfile.B_BES);
     4439                       
     4440                        c.sign(PKCS12_SIGNER);
     4441                       
     4442                       
     4443                        if (deleteDataFileFromBDOCContainer("/tmp/slides-93-cfrg-9.pdf", c))
     4444                        {
     4445                                System.out.println("eliminado archivo del contenedor");
     4446                        }
     4447                        else
     4448                        {
     4449                                System.out.println("NO se eliminó el archivo del contenedor");
     4450                        }
     4451                               
     4452                        if (deleteSignatureFromBDOCContainer(0, c))
     4453                        {
     4454                                System.out.println("SE ELIMINO la firma 2");
     4455                        }
     4456                        else
     4457                        {
     4458                                System.out.println("no se pudo eliminar la firma 0");
     4459                        }
     4460                       
     4461                        System.out.println("numero de firmas restantes: "+ Integer.toString(c.getSignatures().size()));
     4462                       
     4463                        c.save("/tmp/prueba.bdoc");
     4464                       
     4465                        return "prueba exitosa";
     4466                }
     4467               
     4468                @GET
     4469                @Path("/serializar")
     4470                @Produces("text/plain")
     4471                public String serialize()  {
     4472                       
     4473                        logger.debug("recurso /serializar");
     4474                       
     4475                        Security.addProvider(new BouncyCastleProvider());
     4476                       
     4477                        Container c;
     4478                        try {
     4479                                c = deserialize("/tmp/container.bin");
     4480                                logger.debug("deserializado contenedor");
     4481                               
     4482                                logger.debug("numero de firmas: "+ Integer.toString(c.getSignatures().size()));
     4483                               
     4484                                Security.addProvider(new BouncyCastleProvider());
     4485                               
     4486                                //c.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray()));
     4487                                                       
     4488                                //c.save("/tmp/deserializado.bdoc");
     4489                               
     4490                                if (c.getSignatures().size() > 0) {
     4491                                ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
     4492                                c.save(byteOut);
     4493                                ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
     4494                               
     4495                                //Configuration configuration = initConfig(); // also need to re-initialize configuration settings
     4496                               
     4497                                Configuration configuration = new Configuration(Configuration.Mode.PROD);               
     4498                                configuration.loadConfiguration("/tmp/digidoc4j.yaml");
     4499                                configuration.setTslLocation("file:///tmp/venezuela-tsl.xml");       
     4500                               
     4501                                Container container2 = Container.open(byteIn, configuration);
     4502                                container2.sign(new PKCS12Signer("/tmp/ayzarra.p12", "ayzarra".toCharArray()));
     4503                               
     4504                                System.out.println("********numero de firmas deserialize : "+ Integer.toString(container2.getSignatures().size()));
     4505                                container2.save("/tmp/deserializado2.bdoc");
     4506
     4507                            }
     4508                               
     4509                               
     4510                               
     4511                        } catch (ClassNotFoundException | IOException e) {
     4512                                e.printStackTrace();
     4513                               
     4514                                logger.error("ClassNotFoundException | IOException e");
     4515                                return "error ClassNotFoundException | IOException e";
     4516                               
     4517                        }
     4518                       
     4519                               
     4520                        return "prueba exitosa";
     4521                }
     4522         
     4523         
     4524          /**
     4525                 * Verifica si un archivo posee firmas electronicas y retorna informacion
     4526                 * de las mismas en un json
     4527                 * @param idFile
     4528                 * @return
     4529                 */
     4530                @GET
     4531                @Path("/verificar/{idFile}")
     4532                //@Produces("application/json")
     4533                @Produces("text/plain")
     4534                public String verifyFile(@PathParam("idFile") String idFile) {
     4535                       
     4536                        String file = SERVER_UPLOAD_LOCATION_FOLDER + idFile;
     4537               
     4538                        //return getMimeType(file);
     4539                       
     4540                                       
     4541                        File tmpFile = new File(file);
     4542                        String result = "";
     4543
     4544                       
     4545                       
     4546                       
     4547                        if (tmpFile.exists()) {
     4548                                result = "El archivo existe.";
     4549                               
     4550                                try {
     4551                                        PdfReader reader = new PdfReader(file);
     4552                                        AcroFields af = reader.getAcroFields();
     4553                                        ArrayList<String> names = af.getSignatureNames();
     4554                                        if (names.size() > 0) {
     4555                                                result = "el archivo PDF posee "+ names.size() +" firma(s).\n";
     4556                                               
     4557                                                // sin esto explota: se debe agregar una implementacion del provider en tiempo de ejecucion
     4558                                                //http://www.cs.berkeley.edu/~jonah/bc/org/bouncycastle/jce/provider/BouncyCastleProvider.html
     4559                                                Security.addProvider(new BouncyCastleProvider());
     4560                                               
     4561                                                for (String name: names) {
     4562                                                        result = result +"Nombre de la firma: "+ name + "\n";
     4563                                                        System.out.println("Nombre de la firma: "+ name);
     4564                                                       
     4565                                                        PdfPKCS7 pk = af.verifySignature(name);
     4566                                                       
     4567                                                        Certificate[] pkc = pk.getCertificates();
     4568                                                       
     4569                                                        String tmpSignerName = pk.getSigningCertificate().getSubjectX500Principal().toString();
     4570                                                       
     4571                                                       
     4572                                                        result = result + "Sujeto del certificado firmante: " + tmpSignerName + "\n";
     4573                                                        //pk.getSigningCertificate().getSubjectX500Principal().getName() + "\n";
     4574                                                        System.out.println("Sujeto del certificado firmante: " +
     4575                                                                        pk.getSigningCertificate().getSubjectX500Principal().toString());
     4576                                                         
     4577                                                        Calendar cal = pk.getSignDate();
     4578                                                       
     4579                                                        SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
     4580                                                       
     4581                                                        //result = result + "Fecha de la firma: " + cal.toString() + "\n";
     4582                                                        result = result + "Fecha de la firma: " + date_format.format(cal.getTime()) + "\n";
     4583                                                       
     4584                                                        /*
     4585                                                        System.out.println("año: "+ cal.get(Calendar.YEAR));
     4586                                                        System.out.println("mes: "+ (cal.get(Calendar.MONTH) + 1));
     4587                                                        System.out.println("día: "+ cal.get(Calendar.DAY_OF_MONTH));
     4588                                                        System.out.println("hora: "+ cal.get(Calendar.HOUR));
     4589                                                        System.out.println("minuto: "+ cal.get(Calendar.MINUTE));
     4590                                                        System.out.println("segundo: "+ cal.get(Calendar.SECOND));
     4591                                                        */
     4592                                                        //SimpleDateFormat date_format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
     4593                                                    System.out.println(date_format.format(cal.getTime()));
     4594
     4595                                                }
     4596                                               
     4597                                               
     4598                                        }else{
     4599                                                result = "el archivo PDF no posee firmas";
     4600                                        }
     4601                                       
     4602                                       
     4603                                       
     4604                                } catch (IOException e) {
     4605
     4606                                        e.printStackTrace();
     4607                                }
     4608                               
     4609                               
     4610                        }else {
     4611                                result = "El archivo NO existe.";
     4612                        }
     4613                       
     4614                       
     4615                        return result;
     4616                       
     4617                       
     4618                } 
     4619         
     4620       
     4621       
     4622        /**
     4623         * Ejecuta el proceso de presign o preparacion de firma de documento pdf
     4624         * @param presignPar
     4625         * @param req objeto request para crear una sesion y mantener elementos del
     4626         * pdf en la misma
     4627         * @param resp
     4628         */
     4629        @POST
     4630        @Path("/prepararfirmapdf")
     4631        @Consumes(MediaType.APPLICATION_JSON)
     4632        @Produces(MediaType.APPLICATION_JSON)
     4633        //public Response presign(PresignParameters presignPar, @Context HttpServletRequest req) {
     4634        public PresignHash presign(PresignParameters presignPar, @Context HttpServletRequest req) {
     4635               
     4636
     4637                // cadena resultado de la funcion
     4638                String result = "";
     4639               
     4640                PresignHash presignHash = new PresignHash();
     4641               
     4642               
     4643                // cadena con el certificado
     4644                String certHex = presignPar.getCertificate();
     4645                System.out.println("certificado en Hex: " + certHex);
     4646               
     4647                // obtener el id del archivo
     4648                String fileId = presignPar.getFileId();
     4649                               
     4650                try {
     4651                        CertificateFactory factory = CertificateFactory.getInstance("X.509");
     4652                        Certificate[] chain = new Certificate[1];
     4653                       
     4654                        InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
     4655                        chain[0] = factory.generateCertificate(in);
     4656                       
     4657                        if (chain[0] == null) {
     4658                                System.out.println("error chain[0] == null");
     4659                        }else {
     4660                               
     4661                                System.out.println("se cargo el certificado correctamente");
     4662                                System.out.println(chain[0].toString());
     4663                        }
     4664                       
     4665                        //String pdf = SERVER_UPLOAD_LOCATION_FOLDER + "e27a6a90-f955-4191-8e54-580e316a999d";
     4666                        String pdf = SERVER_UPLOAD_LOCATION_FOLDER + fileId;
     4667                        System.out.println("archivo a firmar: " + pdf);
     4668                       
     4669                        PdfReader reader = new PdfReader(pdf);
     4670                       
     4671                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
     4672                       
     4673                        //FileOutputStream baos = new FileOutputStream(pdf+"-signed.pdf");
     4674                       
     4675                        PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
     4676                       
     4677                        // crear la apariencia de la firma
     4678                PdfSignatureAppearance sap = stamper.getSignatureAppearance();
     4679                sap.setReason("Prueba de firma en dos partes");
     4680                sap.setLocation("Merida, Venezuela");
     4681                sap.setVisibleSignature(new Rectangle(36, 748, 144,780),1, "sig");
     4682                sap.setCertificate(chain[0]);
     4683               
     4684                // crear la estructura de la firma
     4685                PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
     4686                dic.setReason(sap.getReason());
     4687                dic.setLocation(sap.getLocation());
     4688                dic.setContact(sap.getContact());
     4689                dic.setDate(new PdfDate(sap.getSignDate()));
     4690               
     4691                sap.setCryptoDictionary(dic);
     4692               
     4693                HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer> ();
     4694                exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
     4695                sap.preClose(exc);
     4696               
     4697                ExternalDigest externalDigest = new ExternalDigest() {
     4698                        public MessageDigest getMessageDigest(String hashAlgorithm)
     4699                        throws GeneralSecurityException {
     4700                                return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
     4701                        }
     4702                };
     4703                       
     4704                       
     4705                PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
     4706               
     4707                InputStream data = sap.getRangeStream();
     4708               
     4709                byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
     4710               
     4711                Calendar cal = Calendar.getInstance();
     4712                byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
     4713               
     4714                sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
     4715               
     4716                System.out.println("sh length: "+ sh.length);
     4717                       
     4718                String hashToSign = byteArrayToHexString(sh);
     4719                System.out.println("***************************************************************");
     4720                System.out.println("HASH EN HEXADECIMAL:");
     4721                System.out.println(hashToSign);
     4722                System.out.println("length: " +hashToSign.length());   
     4723                System.out.println("***************************************************************");
     4724                       
     4725                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
     4726                        Date date = new Date();
     4727                        System.out.println(dateFormat.format(date));
     4728                        //String d = dateFormat.format(date);
     4729                       
     4730                       
     4731                        // almacenar los objetos necesarios para realizar el postsign en una sesion
     4732                        HttpSession session = req.getSession(true);
     4733                        session.setAttribute("hashToSign", hashToSign);
     4734                       
     4735                        session.setAttribute("stamper", stamper);
     4736                        session.setAttribute("sgn", sgn);
     4737                        session.setAttribute("hash", hash);
     4738                        session.setAttribute("cal", cal);
     4739                        session.setAttribute("sap", sap);
     4740                        session.setAttribute("baos", baos);
     4741                        session.setAttribute("fileId", fileId);
     4742                       
     4743                        // creacion del json
     4744                        JSONObject jsonHash = new JSONObject();
     4745                        jsonHash.put("hashToSign", hashToSign);
     4746                       
     4747                        result = jsonHash.toString();
     4748                       
     4749                        presignHash.setHash(hashToSign);
     4750                               
     4751                       
     4752                } catch (CertificateException e1) {
     4753                        // TODO Auto-generated catch block
     4754                        e1.printStackTrace();
     4755                } catch (IOException e) {
     4756                        // TODO Auto-generated catch block
     4757                        e.printStackTrace();
     4758                } catch (DocumentException e) {
     4759                        // TODO Auto-generated catch block
     4760                        e.printStackTrace();
     4761                } catch (InvalidKeyException e) {
     4762                        // TODO Auto-generated catch block
     4763                        e.printStackTrace();
     4764                } catch (NoSuchProviderException e) {
     4765                        // TODO Auto-generated catch block
     4766                        e.printStackTrace();
     4767                } catch (NoSuchAlgorithmException e) {
     4768                        // TODO Auto-generated catch block
     4769                        e.printStackTrace();
     4770                } catch (GeneralSecurityException e) {
     4771                        // TODO Auto-generated catch block
     4772                        e.printStackTrace();
     4773                }
     4774               
     4775                //return Response.status(200).entity(result).build();
     4776                return presignHash;
     4777                       
     4778        }
     4779       
     4780       
     4781        /**
     4782         * Ejecuta el proceso de postsign o completacion de firma de documento pdf
     4783         * @param postsignPar
     4784         * @param req objeto request para crear una sesion y mantener elementos del
     4785         * pdf en la misma
     4786         * @param resp
     4787         * @throws IOException
     4788         */
     4789        @POST
     4790        @Path("/completarfirmapdf")
     4791        @Consumes(MediaType.APPLICATION_JSON)
     4792        @Produces(MediaType.APPLICATION_JSON)
     4793        public Response postsign(PostsignParameters postsignPar, @Context HttpServletRequest req) throws IOException {
     4794               
     4795               
     4796                // cadena resultado de la funcion
     4797                String result = "";
     4798                               
     4799                // cadena con la firma
     4800                String signature = postsignPar.getSignature();
     4801                System.out.println("firma en Hex: " + signature);
     4802               
     4803                HttpSession session = req.getSession(false);
     4804               
     4805                String fileId = (String) session.getAttribute("fileId");
     4806                System.out.println("fileId: " + fileId);
     4807               
     4808                PdfStamper stamper = (PdfStamper) session.getAttribute("stamper");
     4809               
     4810                PdfPKCS7 sgn = (PdfPKCS7) session.getAttribute("sgn");
     4811               
     4812                byte[] hash = (byte[]) session.getAttribute("hash");
     4813               
     4814                Calendar cal = (Calendar) session.getAttribute("cal");
     4815               
     4816                PdfSignatureAppearance sap = (PdfSignatureAppearance) session.getAttribute("sap");
     4817               
     4818                ByteArrayOutputStream os = (ByteArrayOutputStream) session.getAttribute("baos");
     4819               
     4820                if (sgn == null) {
     4821                        System.out.println("sgn == null");
     4822                }
     4823                if (hash == null) {
     4824                        System.out.println("hash == null");
     4825                }
     4826                if (cal == null) {
     4827                        System.out.println("cal == null");
     4828                }
     4829                if (sap == null) {
     4830                        System.out.println("sap == null");
     4831                }
     4832                if (os == null) {
     4833                        System.out.println("os == null");
     4834                }
     4835               
     4836               
     4837               
     4838                // convertir signature en bytes         
     4839                byte[] signatureInBytes = hexStringToByteArray(signature);
     4840                               
     4841                // completar el proceso de firma
     4842                sgn.setExternalDigest(signatureInBytes, null, RSA_DIGEST_ENCRYPTION_ALGORITHM);
     4843                byte[] encodeSig = sgn.getEncodedPKCS7(hash, cal, null, null, null, CryptoStandard.CMS);
     4844                byte[] paddedSig = new byte[8192];
     4845                System.arraycopy(encodeSig, 0, paddedSig, 0, encodeSig.length);
     4846                PdfDictionary dic2 = new PdfDictionary();
     4847                dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
     4848                try {
     4849                        sap.close(dic2);
     4850                       
     4851                        stamper.close();
     4852                        System.out.println("stamper.close");
     4853                       
     4854                }catch(DocumentException e) {
     4855                       
     4856                        System.out.println("throw new IOException");
     4857                        throw new IOException(e);
     4858                       
     4859                } catch (IOException e) {
     4860                        // TODO Auto-generated catch block
     4861                        System.out.println("IOException e");
     4862                        e.printStackTrace();
     4863                       
     4864                }
     4865               
     4866                String signedPdf = SERVER_UPLOAD_LOCATION_FOLDER + fileId + "-signed.pdf";
     4867               
     4868                FileOutputStream signedFile = new FileOutputStream(signedPdf);
     4869               
     4870                os.writeTo(signedFile);
     4871                os.flush();
     4872               
     4873               
     4874               
     4875                // en este punto el archivo pdf debe estar disponible en la ruta
     4876                // SERVER_UPLOAD_LOCATION_FOLDER + fileId;
     4877               
     4878                // llamar a una funcion que permita descargar el archivo
     4879               
     4880                result = "Archivo firmado correctamente";
     4881                System.out.println("Archivo firmado correctamente");
     4882               
     4883                return Response.status(200).entity(result).build();
     4884        }
     4885       
     4886        /**
     4887         * Ejecuta el proceso de presign o preparacion de firma de documento en formato BDOC
     4888         *
     4889         * @param presignPar
     4890         * @param req
     4891         * @return
     4892         */
     4893        @POST
     4894        @Path("/bdoc/")
     4895        @Consumes(MediaType.APPLICATION_JSON)
     4896        @Produces(MediaType.APPLICATION_JSON)
     4897        public PresignHash presignBdoc2(PresignParameters presignPar, @Context HttpServletRequest req) {
     4898               
     4899                System.out.println("presignBdoc2: ");
     4900               
     4901               
     4902                String fileId;
     4903                String certHex;
     4904               
     4905                CertificateFactory cf;
     4906                X509Certificate signerCert;
     4907               
     4908                // cadena resultado de la funcion
     4909                String result = "";
     4910                               
     4911                PresignHash presignHash = new PresignHash();
     4912               
     4913                SignedInfo signedInfo;
     4914               
     4915                fileId = presignPar.getFileId();
     4916                String sourceFile = SERVER_UPLOAD_LOCATION_FOLDER + fileId;
     4917               
     4918                certHex = presignPar.getCertificate();
     4919                System.out.println("certificado en Hex: " + certHex);
     4920               
     4921//              try {
     4922                        /*             
     4923                        Configuration configuration = new Configuration(Configuration.Mode.TEST);
     4924                       
     4925                        configuration.loadConfiguration("/home/aaraujo/desarrollo/2015/workspace-luna/JAXRS-Murachi/WebContent/WEB-INF/lib/digidoc4j.yaml");
     4926                        configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
     4927                   
     4928                        Container container = Container.create(configuration);
     4929                    SignatureParameters signatureParameters = new SignatureParameters();
     4930                    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
     4931                    productionPlace.setCity("Merida");
     4932                    signatureParameters.setProductionPlace(productionPlace);
     4933                    signatureParameters.setRoles(asList("Desarrollador"));
     4934                    container.setSignatureParameters(signatureParameters);
     4935                    container.setSignatureProfile(SignatureProfile.B_BES);
     4936                    container.addDataFile("/tmp/215d6ef7-d639-4191-87a1-ef68a91b2b27", "text/plain");
     4937                    container.sign(new PKCS12Signer("/tmp/JuanHilario.p12", "123456".toCharArray()));
     4938//                  Container container = Container.open("util/faulty/bdoc21-bad-nonce-content.bdoc");
     4939                    container.save("/tmp/signed.bdoc");
     4940                    ValidationResult results = container.validate();
     4941                    System.out.println(results.getReport());
     4942                        */
     4943
     4944                       
     4945                Security.addProvider(new BouncyCastleProvider());
     4946                        System.setProperty("digidoc4j.mode", "TEST");
     4947                       
     4948                        Configuration configuration;
     4949                        configuration = new Configuration(Configuration.Mode.TEST);
     4950                        //configuration.loadConfiguration("/home/aaraujo/desarrollo/2015/workspace-luna/JAXRS-Murachi/WebContent/WEB-INF/lib/digidoc4j.yaml");
     4951                       
     4952                        //configuration.setTslLocation("https://tibisay.cenditel.gob.ve/murachi/raw-attachment/wiki/WikiStart/trusted-test-mp.xml");
     4953                        configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
     4954                       
     4955                        Container container;
     4956                       
     4957                        container = Container.create(Container.DocumentType.BDOC, configuration);
     4958                       
     4959                        SignatureParameters signatureParameters = new SignatureParameters();
     4960                    SignatureProductionPlace productionPlace = new SignatureProductionPlace();
     4961                    productionPlace.setCity("Merida");
     4962                    signatureParameters.setProductionPlace(productionPlace);
     4963                    signatureParameters.setRoles(asList("Desarrollador"));
     4964                    container.setSignatureParameters(signatureParameters);
     4965                    container.setSignatureProfile(SignatureProfile.B_BES);
     4966                       
     4967                        container.addDataFile(sourceFile, "text/plain");
     4968                       
     4969                        container.sign(new PKCS12Signer("/tmp/JuanHilario.p12", "123456".toCharArray()));
     4970                    container.save("/tmp/signed.bdoc");
     4971                    ValidationResult results = container.validate();
     4972                    System.out.println(results.getReport());
     4973                       
     4974                        /*
     4975                        cf = CertificateFactory.getInstance("X.509");
     4976               
     4977                        InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
     4978                       
     4979                        signerCert = (X509Certificate) cf.generateCertificate(in);
     4980                       
     4981                        signedInfo = container.prepareSigning(signerCert);
     4982                       
     4983                        String hashToSign = byteArrayToHexString(signedInfo.getDigest());
     4984                        //System.out.println("presignBdoc - hash: " + byteArrayToHexString(signedInfo.getDigest()));
     4985                        System.out.println("presignBdoc - hash: " + hashToSign);
     4986                       
     4987                       
     4988                        //container.save("/tmp/containerTmp.bdoc");
     4989                        serialize(container, "/tmp/containerSerialized");
     4990                        */
     4991                       
     4992                        String hashToSign = "firma exitosa";
     4993                       
     4994                        // creacion del json
     4995                        JSONObject jsonHash = new JSONObject();
     4996                        jsonHash.put("hashToSign", hashToSign);
     4997                                               
     4998                        result = jsonHash.toString();
     4999                                               
     5000                        presignHash.setHash(hashToSign);
     5001                       
     5002                       
     5003/*                     
     5004                } catch (CertificateException e1) {
     5005                        // TODO Auto-generated catch block
     5006                        e1.printStackTrace();
     5007                } catch (IOException e) {
     5008                        // TODO Auto-generated catch block
     5009                        e.printStackTrace();
     5010                }
     5011*/             
     5012               
     5013                return presignHash;
     5014               
     5015        }
     5016       
     5017       
     5018        @GET
     5019        @Path("/testbdoc/")
     5020        public String testBdoc() {
     5021               
     5022                Security.addProvider(new BouncyCastleProvider());
     5023               
     5024                Configuration configuration = new Configuration(Configuration.Mode.PROD);
     5025               
     5026                configuration.loadConfiguration("/tmp/digidoc4j.yaml");
     5027                //configuration.setTslLocation("http://localhost/trusted-test-mp.xml");
     5028                configuration.setTslLocation("file:///tmp/venezuela-tsl.xml");
     5029               
     5030            Container container = Container.create(configuration);
     5031            SignatureParameters signatureParameters = new SignatureParameters();
     5032            SignatureProductionPlace productionPlace = new SignatureProductionPlace();
     5033            productionPlace.setCity("Merida");
     5034            signatureParameters.setProductionPlace(productionPlace);
     5035            signatureParameters.setRoles(asList("Desarrollador"));
     5036            container.setSignatureParameters(signatureParameters);
     5037            container.setSignatureProfile(SignatureProfile.B_BES);
     5038            container.addDataFile("/tmp/salida.txt", "text/plain");
     5039            container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
     5040//          Container container = Container.open("util/faulty/bdoc21-bad-nonce-content.bdoc");
     5041            container.save("/tmp/signed.bdoc");
     5042            ValidationResult result = container.validate();
     5043            System.out.println(result.getReport());
     5044               
     5045                return "test";
     5046        }
     5047       
     5048        /**
     5049         * Prueba de agregar una firma electrónica a un contenedor existente.
     5050         *
     5051         * NOTA: A un contenedor que posee una firma no se le pueden agregar nuevos DataFiles.
     5052         * @return
     5053         */
     5054        @GET
     5055        @Path("/addsignaturebdoc/")
     5056        public String addSignatureBdoc() {
     5057                logger.debug("/addsignaturebdoc/");
     5058               
     5059                Security.addProvider(new BouncyCastleProvider());
     5060               
     5061                Configuration configuration = new Configuration(Configuration.Mode.PROD);
     5062               
     5063                configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION);
     5064               
     5065                configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION);
     5066                               
     5067                //String bdocFile = "/tmp/c1d099ad-44b3-4227-82fa-8c8f03746787.bdoc";
     5068                String bdocFile = "/tmp/twoSignatures.bdoc";
     5069               
     5070                Container container = Container.open(bdocFile, configuration);
     5071                logger.debug("open container: "+ bdocFile);
     5072               
     5073            SignatureParameters signatureParameters = new SignatureParameters();
     5074           
     5075            SignatureProductionPlace productionPlace = new SignatureProductionPlace();
     5076            productionPlace.setCity("Merida");
     5077            productionPlace.setStateOrProvince("Merida");
     5078            productionPlace.setPostalCode("5101");
     5079            productionPlace.setCountry("Venezuela");
     5080           
     5081            signatureParameters.setProductionPlace(productionPlace);
     5082           
     5083            signatureParameters.setRoles(asList("Desarrollador"));
     5084           
     5085            container.setSignatureParameters(signatureParameters);
     5086           
     5087            container.setSignatureProfile(SignatureProfile.B_BES);
     5088                   
     5089            logger.debug("signing: "+ bdocFile);
     5090            container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
     5091
     5092            String outputFile = "/tmp/threeSignatures.bdoc";
     5093            container.save(outputFile);
     5094            logger.debug("saved file in : "+ outputFile);
     5095           
     5096            ValidationResult result = container.validate();
     5097            System.out.println(result.getReport());
     5098               
     5099                return "success";
     5100        }
     5101       
     5102       
     5103       
     5104        /**
     5105         * Prueba de ejecucion de programa desde consola. Incompleta
     5106         * @return
     5107         * @throws InterruptedException
     5108         */
     5109        @GET
     5110        @Path("/ejecutar")
     5111        @Produces("text/plain")
     5112        public String executeProcess() throws InterruptedException {
     5113               
     5114                String s = "9712f235-4dd4-4b09-957d-b06c33af482b-serialized.bin";
     5115                String[] array = s.split("-serialized\\.bin");
     5116               
     5117                return array[0];
     5118               
     5119               
     5120               
     5121                /*
     5122                String line = "";
     5123                OutputStream stdin = null;
     5124                InputStream stderr = null;
     5125                InputStream stdout = null;
     5126               
     5127                try {
     5128                        System.out.print("...a crear el proceso");
     5129                        Process process = Runtime.getRuntime().exec("/usr/java/jdk1.7.0_21/bin/java -jar /home/aaraujo/desarrollo/2015/servicioVerificacion/testsigningpdf/holamundopdf.jar /tmp/589750.pdf /tmp/simonDiaz.pem /tmp/firmadoconsola.pdf");
     5130                        //Process process = Runtime.getRuntime().exec("ls -l");
     5131                        stdin = process.getOutputStream();
     5132                        stderr = process.getErrorStream();
     5133                        stdout = process.getInputStream();
     5134                       
     5135                        InputStreamReader isr = new InputStreamReader(stdout);
     5136                        BufferedReader buff = new BufferedReader (isr);
     5137
     5138                       
     5139                        while((line = buff.readLine()) != null)
     5140                                System.out.print(line+"\n");
     5141                        int exitValue = process.waitFor();
     5142                        if (exitValue != 0) {
     5143                            System.out.println("Abnormal process termination");
     5144                        }       
     5145                       
     5146                } catch (IOException e) {
     5147                        // TODO Auto-generated catch block
     5148                        e.printStackTrace();
     5149                }
     5150                System.out.print("...saliendo");
     5151                return line;
     5152                */
     5153        }
     5154       
     5155       
     5156       
     5157       
     5158       
     5159        /**
     5160         *
     5161         * @param certHex
     5162         * @param httpHeaders
     5163         * @param req
     5164         * @param resp
     5165         */
     5166        @POST
     5167        @Path("/presignOld")
     5168        @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
     5169        public void presignOld(
     5170                        @FormParam("certHexInForm") String certHex,
     5171                        @Context HttpHeaders httpHeaders,
     5172                        @Context HttpServletRequest req,
     5173                        @Context HttpServletResponse resp) {
     5174               
     5175
     5176                String host = httpHeaders.getRequestHeader("host").get(0);
     5177               
     5178                String agent = httpHeaders.getRequestHeader("user-agent").get(0);
     5179                String salida = "User agent :"+ agent +" from host : "+host;
     5180                System.out.println(host);
     5181                System.out.println(agent);
     5182                System.out.println(salida);
     5183               
     5184                System.out.println("certificado en Hex: " + certHex);
     5185               
     5186                try {
     5187                        CertificateFactory factory = CertificateFactory.getInstance("X.509");
     5188                        Certificate[] chain = new Certificate[1];
     5189                       
     5190                        InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
     5191                        chain[0] = factory.generateCertificate(in);
     5192                       
     5193                        if (chain[0] == null) {
     5194                                System.out.println("error chain[0] == null");
     5195                        }else {
     5196                               
     5197                                System.out.println("se cargo el certificado correctamente");
     5198                                System.out.println(chain[0].toString());
     5199                        }
     5200                       
     5201                        String pdf = SERVER_UPLOAD_LOCATION_FOLDER + "e27a6a90-f955-4191-8e54-580e316a999d";
     5202                       
     5203                        PdfReader reader = new PdfReader(pdf);
     5204                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
     5205                        PdfStamper stamper = PdfStamper.createSignature(reader, baos, '\0');
     5206                       
     5207                        // crear la apariencia de la firma
     5208                PdfSignatureAppearance sap = stamper.getSignatureAppearance();
     5209                sap.setReason("Prueba de firma en dos partes");
     5210                sap.setLocation("Merida, Venezuela");
     5211                sap.setVisibleSignature(new Rectangle(36, 748, 144,780),1, "sig");
     5212                sap.setCertificate(chain[0]);
     5213               
     5214                // crear la estructura de la firma
     5215                PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
     5216                dic.setReason(sap.getReason());
     5217                dic.setLocation(sap.getLocation());
     5218                dic.setContact(sap.getContact());
     5219                dic.setDate(new PdfDate(sap.getSignDate()));
     5220               
     5221                sap.setCryptoDictionary(dic);
     5222               
     5223                HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer> ();
     5224                exc.put(PdfName.CONTENTS, new Integer(8192 * 2 + 2));
     5225                sap.preClose(exc);
     5226               
     5227                ExternalDigest externalDigest = new ExternalDigest() {
     5228                        public MessageDigest getMessageDigest(String hashAlgorithm)
     5229                        throws GeneralSecurityException {
     5230                                return DigestAlgorithms.getMessageDigest(hashAlgorithm, null);
     5231                        }
     5232                };
     5233                       
     5234                       
     5235                PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", null, externalDigest, false);
     5236               
     5237                InputStream data = sap.getRangeStream();
     5238               
     5239                byte hash[] = DigestAlgorithms.digest(data, externalDigest.getMessageDigest("SHA256"));
     5240               
     5241                Calendar cal = Calendar.getInstance();
     5242                byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
     5243               
     5244                sh = DigestAlgorithms.digest(new ByteArrayInputStream(sh), externalDigest.getMessageDigest("SHA256"));
     5245               
     5246                System.out.println("sh length: "+ sh.length);
     5247                       
     5248                String hashToSign = byteArrayToHexString(sh);
     5249                System.out.println("***************************************************************");
     5250                System.out.println("HASH EN HEXADECIMAL:");
     5251                System.out.println(hashToSign);
     5252                System.out.println("length: " +hashToSign.length());   
     5253                System.out.println("***************************************************************");
     5254                       
     5255                DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
     5256                        Date date = new Date();
     5257                        System.out.println(dateFormat.format(date));
     5258                        String d = dateFormat.format(date);
     5259                       
     5260                       
     5261                        // almacenar los objetos necesarios para realizar el postsign en una sesion
     5262                        HttpSession session = req.getSession(true);
     5263                        session.setAttribute("hashToSign", hashToSign);
     5264                       
     5265                        session.setAttribute("sgn", sgn);
     5266                        session.setAttribute("hash", hash);
     5267                        session.setAttribute("cal", cal);
     5268                        session.setAttribute("sap", sap);
     5269                        session.setAttribute("baos", baos);
     5270                       
     5271               
     5272                       
     5273                        resp.sendRedirect("http://localhost/murachi2.html");
     5274                       
     5275                       
     5276                } catch (CertificateException e1) {
     5277                        // TODO Auto-generated catch block
     5278                        e1.printStackTrace();
     5279                } catch (IOException e) {
     5280                        // TODO Auto-generated catch block
     5281                        e.printStackTrace();
     5282                } catch (DocumentException e) {
     5283                        // TODO Auto-generated catch block
     5284                        e.printStackTrace();
     5285                } catch (InvalidKeyException e) {
     5286                        // TODO Auto-generated catch block
     5287                        e.printStackTrace();
     5288                } catch (NoSuchProviderException e) {
     5289                        // TODO Auto-generated catch block
     5290                        e.printStackTrace();
     5291                } catch (NoSuchAlgorithmException e) {
     5292                        // TODO Auto-generated catch block
     5293                        e.printStackTrace();
     5294                } catch (GeneralSecurityException e) {
     5295                        // TODO Auto-generated catch block
     5296                        e.printStackTrace();
     5297                }
     5298               
     5299               
     5300       
     5301        }
     5302       
     5303       
     5304        @POST
     5305        @Path("/postsign")
     5306        public String postsignOld(@Context HttpServletRequest req,
     5307                        @Context HttpServletResponse resp) {
     5308               
     5309                System.out.println("...postsign()...");
     5310               
     5311                HttpSession session = req.getSession(false);
     5312                Object att = session.getAttribute("hashToSign");
     5313                               
     5314       
     5315                String output = "atributo leido de la sesion: " + att.toString();
     5316               
     5317               
     5318                return output;
     5319                //return Response.status(200).entity(output).build();
     5320        }
     5321       
     5322       
     5323        @GET
     5324        @Path("/retornajson")
     5325        @Produces(MediaType.APPLICATION_JSON)
     5326        public PresignHash retornajson(@Context HttpServletRequest req) {
     5327               
     5328               
     5329               
     5330                PresignHash h = new PresignHash();
     5331                h.setHash("ESTO SERIA UN HASH");
     5332               
     5333                System.out.println("...retornajson..."+ h.getHash());
     5334               
     5335                return h;
     5336               
     5337        }
     5338       
     5339        @POST
     5340        @Path("/enviarjson")
     5341        @Consumes(MediaType.APPLICATION_JSON)
     5342        @Produces(MediaType.APPLICATION_JSON)
     5343        public PresignHash recibejson( PresignParameters par) {
     5344               
     5345                String fileId = par.getFileId();
     5346                System.out.println("...fileId recibido..."+ fileId);
     5347               
     5348                String cert = par.getCertificate();
     5349                System.out.println("...certificate recibido..."+ cert);
     5350               
     5351                PresignHash h = new PresignHash();
     5352                h.setHash("DEBES FIRMAR ESTO");
     5353               
     5354                System.out.println("...recibejson..."+ h.getHash());
     5355               
     5356                return h;
     5357               
     5358        }
     5359       
     5360       
     5361       
     5362       
     5363       
     5364         
    53615365}
Note: See TracChangeset for help on using the changeset viewer.