Ignore:
Timestamp:
Jul 1, 2015, 3:41:10 PM (9 years ago)
Author:
antonioaraujob <aaraujo@…>
Branches:
master
Children:
0f76179
Parents:
ce3da18
Message:

Revisión en los recursos /archivos/bdocs para preparar la firma de un archivo con el formato BDOC y /archivos/bdocs/resenas para completar la firma de un archivo con el formato BDOC al recibir el hash cifrado desde el cliente. Adicionalmente se establece la posibilidad de crear un nuevo contenedor BDOC para la firma de un archivo o de agregar una firma a un contenedor existente.

File:
1 edited

Legend:

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

    rce3da18 rb1392c3  
    996996         *  "contact":"contact"
    997997         *  }
    998          * 
     998         *
    999999         *
    10001000         * @param presignPar JSON con los parametros de preparacion: Id del archivo y certificado
     
    10151015         *  "contact":"contact"
    10161016         *  }
     1017         * 
     1018         *  fileId: corresponde al identificador del archivo que se encuentra en el servidor y se desea firmar.
     1019         * 
     1020         *  certificate: corresponde al certificado del firmante en formato hexadecimal.
     1021         * 
     1022         *  reason: corresponde a la razón de la firma (cadena descriptiva del por qué de la firma).
     1023         * 
     1024         *  location: corresponde a la ubicación donde se realiza la firma.
     1025         * 
     1026         *  contact: corresponde a información de contacto del firmante.
    10171027         *
    10181028         * @apiSuccess {String} hash Reseña o hash del archivo que se debe cifrar con la clave privada protegida por el
     
    17891799       
    17901800       
     1801        /**
     1802         * Ejecuta el proceso de presign o preparacion de firma de un archivo en formato BDOC.
     1803         *
     1804         * Estructura del JSON que recibe la funcion:
     1805         *
     1806         *      {"fileId":"file_id",
     1807         *      "certificate":"hex_cert_value",
     1808         *  "city":"ciudad",
     1809         *  "state":"estado",
     1810         *  "postalCode":"codigoPostal",
     1811         *  "country":"pais",
     1812         *  "role":"rol",
     1813         *  "addSignature":true/false
     1814         *  }
     1815         *
     1816         *
     1817         * @param presignPar JSON con los parametros de preparacion: Id del archivo, certificado, ciudad, estado, codigoPostal, país, rol.
     1818         *
     1819         * @param req objeto request para crear una sesion y mantener elementos del BDOC
     1820         *  en la misma.
     1821         *
     1822         * @throws MurachiException
     1823         *
     1824         * @api {post} /Murachi/0.1/archivos/firmados/bdocs Prepara la firma de un archivo en formato BDOC.
     1825         * @apiName BDocs
     1826         * @apiGroup BDOCS
     1827         * @apiVersion 0.1.0
     1828         * @apiDescription Prepara la firma de un archivo en formato BDOC. Se debe pasar un JSON con la siguiente estructura:
     1829         *
     1830         * {"fileId":"file_id", "certificate":"hex_cert_value",
     1831         * "city":"ciudad", "state":"estado", "postalCode":"codigoPostal",
     1832         * "country":"pais", "role":"rol", "addSignature":true/false
     1833         * }
     1834         * 
     1835         *  fileId: corresponde al identificador del archivo que se encuentra en el servidor y se desea firmar.
     1836         * 
     1837         *  certificate: corresponde al certificado del firmante en formato hexadecimal.
     1838         * 
     1839         *  city: corresponde a la ciudad en la que se realiza la firma.
     1840         * 
     1841         *  state: corresponde al estado en el que se reailza la firma.
     1842         * 
     1843         *  postalCode: corresponde al código postal del lugar donde se realiza la firma.
     1844         * 
     1845         *  country: corresponde al país donde se realiza la firma.
     1846         * 
     1847         *  role: corresponde al rol del firmante.
     1848         * 
     1849         *  addSignature: true si se debe agregar una firma a un contenedor BDOC existente; false si se debe crear
     1850         *  un contenedor nuevo para firmar.
     1851         *
     1852         * @apiSuccess {String} hash Reseña o hash del archivo que se debe cifrar con la clave privada protegida por el
     1853         * dispositivo criptográfico.
     1854         *
     1855         * @apiExample Example usage:
     1856         *
     1857         * var parameters = JSON.stringify({
     1858         *                             "fileId":fileId,
     1859         *                             "certificate":cert.hex,
     1860         *                             "city":"Merida",
     1861     *                             "state":"Merida",
     1862         *                             "postalCode":"5101",
     1863         *                             "country":"Venezuela",
     1864         *                             "role":"Desarrollador",
     1865         *                             "addSignature":true
     1866         *                             });
     1867         *
     1868         * $.ajax({
     1869     *           url: "https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/bdocs",
     1870     *           type: "post",
     1871     *           dataType: "json",
     1872     *           data: parameters,
     1873     *           contentType: "application/json",
     1874     *           success: function(data, textStatus, jqXHR){
     1875         *                              var json_x = data;
     1876     *                              var hash = json_x['hash'];
     1877     *                              alert("hash recibido del servidor "+hash);
     1878     *           },
     1879         *           error: function(jqXHR, textStatus, errorThrown){
     1880         *                              //alert('error: ' + textStatus);
     1881         *                              //var responseText = jQuery.parseJSON(jqXHR.responseText);
     1882         *                              alert('ajax error function: ' + jqXHR.responseText);
     1883         *                             
     1884         *           }
     1885     *  });
     1886         *
     1887         *
     1888         *
     1889         * @apiErrorExample {json} Error-Response:
     1890         *     HTTP/1.1 500 Internal Server Error
     1891         *     {
     1892         *       "hash": "",
     1893         *       "error": "Error en el certificado del firmante"
     1894         *     }
     1895         *
     1896         *
     1897         */
    17911898        @POST
    17921899        @Path("/bdocs")
     
    18211928                logger.debug("role: " + role);
    18221929               
     1930                Boolean addSignature = presignPar.getAddSignature();
     1931                logger.debug("addSignature: " + addSignature.toString());
     1932               
    18231933                CertificateFactory cf;
    18241934                X509Certificate signerCert;
     
    18441954                try
    18451955                {
    1846                        
    1847                
    1848                 Security.addProvider(new BouncyCastleProvider());
    1849                 Container container = null;
    1850                
    1851                 Configuration configuration = new Configuration(Configuration.Mode.PROD);
    1852                
    1853                 configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION);
    1854                
    1855                 configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION);
    1856        
    1857                 container = Container.create(Container.DocumentType.BDOC, configuration);
    1858                
    1859                 SignatureParameters signatureParameters = new SignatureParameters();
    1860             SignatureProductionPlace productionPlace = new SignatureProductionPlace();
    1861             productionPlace.setCity(city);
    1862             productionPlace.setStateOrProvince(state);
    1863             productionPlace.setPostalCode(postalCode);
    1864             productionPlace.setCountry(country);
    1865             signatureParameters.setProductionPlace(productionPlace);
    1866             signatureParameters.setRoles(asList(role));
    1867             container.setSignatureParameters(signatureParameters);
    1868             container.setSignatureProfile(SignatureProfile.B_BES);
    1869                
    1870                 container.addDataFile(sourceFile, sourceFileMimeType);
    1871                
    1872                 cf = CertificateFactory.getInstance("X.509");
    1873                
    1874                 InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
    1875                
    1876                 signerCert = (X509Certificate) cf.generateCertificate(in);
    1877                
    1878                 signedInfo = container.prepareSigning(signerCert);
    1879                
    1880                 hashToSign = byteArrayToHexString(signedInfo.getDigest());
    1881                 //System.out.println("presignBdoc - hash: " + byteArrayToHexString(signedInfo.getDigest()));
    1882                 System.out.println("presignBdoc - hash: " + hashToSign);
    1883                 logger.debug("presignBdoc - hash: " + hashToSign);
    1884                
    1885                 // establecer el nombre del archivo a serializar
    1886                 String serializedContainerId = sourceFile + "-serialized";
    1887                
    1888                 // serializar el archivo
    1889                 serialize(container, serializedContainerId);
    1890                
    1891                
    1892                 // almacenar los objetos necesarios para realizar el postsign en una sesion
    1893                 HttpSession session = req.getSession(true);
    1894                 session.setAttribute("hashToSign", hashToSign);                         
    1895                 session.setAttribute("fileId", fileId);
    1896                 session.setAttribute("serializedContainerId", serializedContainerId);
    1897                
    1898                
    1899                
     1956                        Security.addProvider(new BouncyCastleProvider());
     1957                        Container container = null;
     1958               
     1959                        Configuration configuration = new Configuration(Configuration.Mode.PROD);
     1960               
     1961                        configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION);
     1962               
     1963                        configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION);
     1964       
     1965                        // se debe agregar una firma al contenedor existente
     1966                        if (addSignature)
     1967                        {
     1968                                container = Container.open(sourceFile, configuration);
     1969                                logger.debug("open container: "+ sourceFile);
     1970                        }
     1971                        else // crear un contenedor nuevo
     1972                        {
     1973                                container = Container.create(Container.DocumentType.BDOC, configuration);
     1974                                logger.debug("container created");
     1975                                container.addDataFile(sourceFile, sourceFileMimeType);
     1976                                logger.debug("container addDataFile");
     1977                        }
     1978                       
     1979               
     1980                        SignatureParameters signatureParameters = new SignatureParameters();
     1981                        SignatureProductionPlace productionPlace = new SignatureProductionPlace();
     1982                        productionPlace.setCity(city);
     1983                        productionPlace.setStateOrProvince(state);
     1984                        productionPlace.setPostalCode(postalCode);
     1985                        productionPlace.setCountry(country);
     1986                        signatureParameters.setProductionPlace(productionPlace);
     1987                        logger.debug("container setProductionPlace");
     1988                        signatureParameters.setRoles(asList(role));
     1989                        container.setSignatureParameters(signatureParameters);
     1990                        container.setSignatureProfile(SignatureProfile.B_BES);
     1991               
     1992                       
     1993               
     1994                        cf = CertificateFactory.getInstance("X.509");
     1995               
     1996                        InputStream in = new ByteArrayInputStream(hexStringToByteArray(certHex));
     1997               
     1998                        signerCert = (X509Certificate) cf.generateCertificate(in);
     1999               
     2000                        signedInfo = container.prepareSigning(signerCert);
     2001               
     2002                        hashToSign = byteArrayToHexString(signedInfo.getDigest());
     2003               
     2004                        System.out.println("presignBdoc - hash: " + hashToSign);
     2005                        logger.debug("hash to sign: " + hashToSign);
     2006               
     2007                        // establecer el nombre del archivo a serializar
     2008                        String serializedContainerId = sourceFile + "-serialized";
     2009               
     2010                        // serializar el archivo
     2011                        serialize(container, serializedContainerId);
     2012                               
     2013                        // almacenar los objetos necesarios para realizar el postsign en una sesion
     2014                        HttpSession session = req.getSession(true);
     2015                        session.setAttribute("hashToSign", hashToSign);                         
     2016                        session.setAttribute("fileId", fileId);
     2017                        session.setAttribute("serializedContainerId", serializedContainerId);           
    19002018                } catch(IOException e)
    19012019                {
     
    19142032                JSONObject jsonHash = new JSONObject();
    19152033                jsonHash.put("hashToSign", hashToSign);
    1916                                        
    1917                                        
     2034
    19182035                presignHash.setHash(hashToSign);
    1919                 presignHash.setError("");
    1920                
     2036                presignHash.setError("");               
    19212037               
    19222038                logger.debug("presignBdoc: "+ presignHash.toString());
     
    19252041       
    19262042       
     2043       
     2044        /**
     2045         * Ejecuta el proceso de postsign o completacion de firma de archivo en formato BDOC.
     2046         *
     2047         * @param postsignPar JSON con los parametros de postsign: signature realizada a partir
     2048         * del hardware criptografico en el navegador.
     2049         *
     2050         * @param req objeto request para crear una sesion y mantener elementos del
     2051         * BDOC en la misma.
     2052         *
     2053         * @throws IOException
     2054         * @throws MurachiException
     2055         *
     2056         *
     2057         * @api {post} /Murachi/0.1/archivos/firmados/bdocs/resenas Completa la firma del archivo en formato BDOC.
     2058         * @apiName BdocResenas
     2059         * @apiGroup BDOCS
     2060         * @apiVersion 0.1.0
     2061         * @apiDescription Completa la firma del archivo en formato BDOC. Recibe el hash cifrado del cliente y termina de completar la firma del
     2062         * archivo en formato BDOC.
     2063         *
     2064         * @apiSuccess {String} signedFileId Identificador único del archivo firmado en el servidor.
     2065         *
     2066         * @apiExample Example usage:
     2067         *
     2068         * $.ajax({
     2069     *           url: "https://murachi.cenditel.gob.ve/Murachi/0.1/archivos/bdocs/resenas",
     2070     *           type: "post",
     2071     *           dataType: "json",
     2072     *           data: JSON.stringify({"signature":signature.hex}),
     2073     *           contentType: "application/json",
     2074     *           success: function(data, textStatus, jqXHR){
     2075     *                              alert('Archivo firmado correctamente: ' + data['signedFileId']);
     2076     *           },
     2077         *           error: function(jqXHR, textStatus, errorThrown){
     2078         *                              alert('error en pdfs/resenas: ' + textStatus);
     2079         *           }
     2080     *  });
     2081         *
     2082         *
     2083         *
     2084         * @apiErrorExample {json} Error-Response:
     2085         *     HTTP/1.1 500 Internal Server Error
     2086         *     {
     2087         *       "error": "Error en proceso de deserialización y completación de firma"
     2088         *     }
     2089         *
     2090         */
    19272091        @POST
    19282092        @Path("/bdocs/resenas")
     
    19452109               
    19462110                String serializedContainerId = (String) session.getAttribute("serializedContainerId") + ".bin";
    1947                
    1948                
     2111                               
    19492112                System.out.println("serializedContainerId: " + serializedContainerId);
    19502113                logger.debug("serializedContainerId: " + serializedContainerId);
     
    19592122                        deserializedContainer.signRaw(signatureInBytes);
    19602123                        deserializedContainer.save(signedBdoc);
    1961                         logger.debug("archivo firmado escrito en: " + signedBdoc);
    1962                        
    1963                        
    1964                        
     2124                        logger.debug("archivo firmado escrito en: " + signedBdoc);                     
    19652125                } catch (ClassNotFoundException e) {
    19662126                        //e.printStackTrace();
     
    19682128                        JSONObject jsonError = new JSONObject();
    19692129                                               
    1970                         System.out.println("sgn == null");
     2130                        System.out.println("ClassNotFoundException e: " + e.getMessage());
    19712131                        logger.error("error: " + e.getMessage());
    19722132                                                       
     
    19822142                PostsignMessage message = new PostsignMessage();
    19832143                message.setMessage("{\"signedFile\":"+fileId + ".bdoc}");
    1984                
    1985                
     2144                               
    19862145                JSONObject jsonFinalResult = new JSONObject();
    19872146                jsonFinalResult.put("signedFileId",fileId + ".bdoc");
     
    19902149                return Response.status(200).entity(jsonFinalResult.toString()).build();
    19912150        }
     2151       
     2152       
     2153       
     2154       
     2155       
     2156       
     2157       
    19922158       
    19932159       
     
    26002766        }
    26012767       
    2602        
    2603        
     2768        /**
     2769         * Prueba de agregar una firma electrónica a un contenedor existente.
     2770         *
     2771         * NOTA: A un contenedor que posee una firma no se le pueden agregar nuevos DataFiles.
     2772         * @return
     2773         */
     2774        @GET
     2775        @Path("/addsignaturebdoc/")
     2776        public String addSignatureBdoc() {
     2777                logger.debug("/addsignaturebdoc/");
     2778               
     2779                Security.addProvider(new BouncyCastleProvider());
     2780               
     2781                Configuration configuration = new Configuration(Configuration.Mode.PROD);
     2782               
     2783                configuration.loadConfiguration(DIGIDOC4J_CONFIGURATION);
     2784               
     2785                configuration.setTslLocation(DIGIDOC4J_TSL_LOCATION);
     2786                               
     2787                //String bdocFile = "/tmp/c1d099ad-44b3-4227-82fa-8c8f03746787.bdoc";
     2788                String bdocFile = "/tmp/twoSignatures.bdoc";
     2789               
     2790                Container container = Container.open(bdocFile, configuration);
     2791                logger.debug("open container: "+ bdocFile);
     2792               
     2793            SignatureParameters signatureParameters = new SignatureParameters();
     2794           
     2795            SignatureProductionPlace productionPlace = new SignatureProductionPlace();
     2796            productionPlace.setCity("Merida");
     2797            productionPlace.setStateOrProvince("Merida");
     2798            productionPlace.setPostalCode("5101");
     2799            productionPlace.setCountry("Venezuela");
     2800           
     2801            signatureParameters.setProductionPlace(productionPlace);
     2802           
     2803            signatureParameters.setRoles(asList("Desarrollador"));
     2804           
     2805            container.setSignatureParameters(signatureParameters);
     2806           
     2807            container.setSignatureProfile(SignatureProfile.B_BES);
     2808                   
     2809            logger.debug("signing: "+ bdocFile);
     2810            container.sign(new PKCS12Signer("/tmp/tibisay.p12", "123456".toCharArray()));
     2811
     2812            String outputFile = "/tmp/threeSignatures.bdoc";
     2813            container.save(outputFile);
     2814            logger.debug("saved file in : "+ outputFile);
     2815           
     2816            ValidationResult result = container.validate();
     2817            System.out.println(result.getReport());
     2818               
     2819                return "success";
     2820        }
    26042821       
    26052822       
Note: See TracChangeset for help on using the changeset viewer.