Proceso Jave en TWebview

Proceso Jave en TWebview

Postby acuellar » Wed Jul 19, 2023 5:55 pm

Estimado Antonio

Me puede ayudar a ejecutar éste proceso Java con TWebview
Code: Select all  Expand view

   public class Firmador {

    private static Firmador instancia;
    private String ALG = "SHA1withRSA";
    static {
        Init.init();
        Security.addProvider(new BouncyCastleProvider());
    }
    public static Firmador getInstance() {
        if (instancia == null) {
            instancia = new Firmador();
        }
        return instancia;
    }
    private Firmador() {
    }
    public static byte[] firmarDsig(byte[] datos, PrivateKey priv, X509Certificate... cert) throws ParserConfigurationException, IOException, SAXException, XMLSecurityException {
        ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, "");
        Document documento = leerXML(datos);
        Element root = (Element) documento.getFirstChild();
        documento.setXmlStandalone(false);
        XMLSignature signature = new XMLSignature(documento, null, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256);
        root.appendChild(signature.getElement());
        Transforms transforms = new Transforms(documento);
        transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        signature.addDocument("", transforms, MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256);
        if (cert != null) {
            signature.addKeyInfo(cert[0]);
        }
        signature.sign(priv);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLUtils.outputDOMc14nWithComments(documento, baos);
        return baos.toString().getBytes();
    }
    public static Document leerXML(byte datos[]) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        factory.setNamespaceAware(true);
        builder = factory.newDocumentBuilder();
        return builder.parse(new ByteArrayInputStream(datos));
    }
    private static String getKey(String filename) throws IOException {
        // Read key from file
        String strKeyPEM = "";
        BufferedReader br = new BufferedReader(new FileReader(filename));
        String line;
        while ((line = br.readLine()) != null) {
            strKeyPEM += line + "\n";
        }
        br.close();
        return strKeyPEM;
    }
    public static RSAPrivateKey getPrivateKey(String filename) throws IOException, GeneralSecurityException {
        String privateKeyPEM = getKey(filename);
        return getPrivateKeyFromString(privateKeyPEM);
    }
    public static RSAPrivateKey getPrivateKeyFromString(String key) throws IOException, GeneralSecurityException {
        String privateKeyPEM = key;
        privateKeyPEM = privateKeyPEM.replace("-----BEGIN PRIVATE KEY-----\n", "");
        privateKeyPEM = privateKeyPEM.replace("-----END PRIVATE KEY-----", "");
        byte[] encoded = Base64.decodeBase64(privateKeyPEM);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);
        return privKey;
    }
    public static RSAPublicKey getPublicKey(String filename) throws IOException, GeneralSecurityException {
        String publicKeyPEM = getKey(filename);
        return getPublicKeyFromString(publicKeyPEM);
    }
    public static RSAPublicKey getPublicKeyFromString(String key) throws IOException, GeneralSecurityException {
        String publicKeyPEM = key;
        publicKeyPEM = publicKeyPEM.replace("-----BEGIN PUBLIC KEY-----\n", "");
        publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
        byte[] encoded = Base64.decodeBase64(publicKeyPEM);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        RSAPublicKey pubKey = (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(encoded));
        return pubKey;
    }  
    public static X509Certificate getX509Certificate(String filename) throws IOException, CertificateException
    {
        CertificateFactory fact = CertificateFactory.getInstance("X.509");
        FileInputStream is = new FileInputStream (filename);
        X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
        PublicKey key = cer.getPublicKey();
        return cer;
    }
}
 


El proceso se debe llamar de ésta forma
Code: Select all  Expand view

      public void firmarXML() throws URISyntaxException, ParserConfigurationException, XMLSecurityException, org.xml.sax.SAXException {

        String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><facturaElectronicaEstandar> AQUI VA LA FACTURA XML </fin>";
        byte[] datos = xml.getBytes(StandardCharsets.UTF_8);
        try {
            String path = new File(Firmador.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath();
            PrivateKey privateKey = Firmador.getPrivateKey(path + "/vladimir_private.pem");
            X509Certificate cert =  Firmador.getX509Certificate(path + "/vladimir.cer");
            byte[] xmlFirmado = Firmador.firmarDsig(datos, privateKey, cert);
            String respuesta = new String(xmlFirmado);
            System.out.println("facturaFirmada: "+respuesta);
        } catch (IOException | GeneralSecurityException ex) {
            Logger.getLogger(FirmadorUnitTest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 


La puede insertar en éste código
Code: Select all  Expand view

#include "FiveWin.ch"
*
function Main()

   local oWebView := TWebView():New()

   oWebView:bOnBind = { | cJson, nCalls | MsgInfo( cJson, nCalls ) }
   oWebView:Bind( "SendToFWH" )
   oWebView:Navigate( firma() )
   Sleep( 200 )
   oWebView:Run()
   oWebView:Destroy()

return nil
*
Function Firma()
   local cHtml
   
   TEXT INTO cHtml
    data:text/html,
   <head> </head>
    <body>
      <button id='btn-test' >Firma xml</button>
      <script>
        function test(evt) {
          //....
     </script>
  </body>
ENDTEXT

return cHtml
 


Muchas gracias por la ayuda.
Saludos,

Adhemar C.
User avatar
acuellar
 
Posts: 1593
Joined: Tue Oct 28, 2008 6:26 pm
Location: Santa Cruz-Bolivia

Return to FiveWin para Harbour/xHarbour

Who is online

Users browsing this forum: No registered users and 84 guests