/**
   * Prueba de firma convencional.
   *
   * @throws Exception en cualquier error
   */
  @SuppressWarnings("static-method")
  @Test
  public void testSignature() throws Exception {

    Assert.assertEquals(
        "file.signed.pdf", AOPDFSigner.getSignedName("file.pdf")); // $NON-NLS-1$ //$NON-NLS-2$

    Logger.getLogger("es.gob.afirma").setLevel(Level.WARNING); // $NON-NLS-1$
    final PrivateKeyEntry pke;
    final X509Certificate cert;

    final KeyStore ks = KeyStore.getInstance("PKCS12"); // $NON-NLS-1$
    ks.load(ClassLoader.getSystemResourceAsStream(CERT_PATH), CERT_PASS.toCharArray());
    pke =
        (PrivateKeyEntry)
            ks.getEntry(CERT_ALIAS, new KeyStore.PasswordProtection(CERT_PASS.toCharArray()));
    cert = (X509Certificate) ks.getCertificate(CERT_ALIAS);

    final AOSigner signer = new AOPDFSigner();

    String prueba;

    for (final Properties extraParams : PADES_MODES) {
      for (final String algo : ALGOS) {
        for (final String file : TEST_FILES) {

          final byte[] testPdf =
              AOUtil.getDataFromInputStream(ClassLoader.getSystemResourceAsStream(file));

          Assert.assertTrue(
              "No se ha reconocido como un PDF", signer.isValidDataFile(testPdf)); // $NON-NLS-1$

          prueba =
              "Firma PAdES en modo '"
                  + //$NON-NLS-1$
                  extraParams.getProperty("mode")
                  + //$NON-NLS-1$
                  "' con el algoritmo ': "
                  + //$NON-NLS-1$
                  algo
                  + "' y el fichero '"
                  + //$NON-NLS-1$
                  file
                  + "'"; //$NON-NLS-1$

          System.out.println(prueba);

          final byte[] result =
              signer.sign(
                  testPdf, algo, pke.getPrivateKey(), pke.getCertificateChain(), extraParams);

          Assert.assertNotNull(prueba, result);
          Assert.assertTrue(signer.isSign(result));

          AOTreeModel tree = signer.getSignersStructure(result, false);
          Assert.assertEquals(
              "Datos", ((AOTreeNode) tree.getRoot()).getUserObject()); // $NON-NLS-1$
          Assert.assertEquals(
              "ANF Usuario Activo",
              ((AOTreeNode) tree.getRoot()).getChildAt(0).getUserObject()); // $NON-NLS-1$

          tree = signer.getSignersStructure(result, true);
          Assert.assertEquals(
              "Datos", ((AOTreeNode) tree.getRoot()).getUserObject()); // $NON-NLS-1$
          final AOSimpleSignInfo simpleSignInfo =
              (AOSimpleSignInfo) ((AOTreeNode) tree.getRoot()).getChildAt(0).getUserObject();

          // Assert.assertNotNull(simpleSignInfo.getSigningTime());
          Assert.assertEquals(cert, simpleSignInfo.getCerts()[0]);

          Assert.assertEquals(result, signer.getData(result));

          Assert.assertEquals(
              AOSignConstants.SIGN_FORMAT_PDF, signer.getSignInfo(result).getFormat());

          final File saveFile = File.createTempFile(algo, ".pdf"); // $NON-NLS-1$
          final OutputStream os = new FileOutputStream(saveFile);
          os.write(result);
          os.flush();
          os.close();
          System.out.println(
              "Temporal para comprobacion manual: " + saveFile.getAbsolutePath()); // $NON-NLS-1$
        }
      }
    }
  }
  /**
   * Prueba la firma de un PDF certificado.
   *
   * @throws Exception en cualquier error
   */
  @SuppressWarnings("static-method")
  @Test
  public void testCertifiedSignature() throws Exception {
    Logger.getLogger("es.gob.afirma").setLevel(Level.WARNING); // $NON-NLS-1$
    final PrivateKeyEntry pke;

    final KeyStore ks = KeyStore.getInstance("PKCS12"); // $NON-NLS-1$
    ks.load(ClassLoader.getSystemResourceAsStream(CERT_PATH), CERT_PASS.toCharArray());
    pke =
        (PrivateKeyEntry)
            ks.getEntry(CERT_ALIAS, new KeyStore.PasswordProtection(CERT_PASS.toCharArray()));

    final AOSigner signer = new AOPDFSigner();

    final byte[] testPdf =
        AOUtil.getDataFromInputStream(ClassLoader.getSystemResourceAsStream(TEST_FILE_CTF));

    Assert.assertTrue(
        "No se ha reconocido como un PDF", signer.isValidDataFile(testPdf)); // $NON-NLS-1$

    String prueba =
        "Firma PAdES de PDF certificado en SHA512withRSA indicando allowSigningCertifiedPdfs=true"; //$NON-NLS-1$

    System.out.println(prueba);

    Properties extraParams = new Properties();
    extraParams.put("allowSigningCertifiedPdfs", "true"); // $NON-NLS-1$ //$NON-NLS-2$
    byte[] result =
        signer.sign(
            testPdf,
            "SHA512withRSA", //$NON-NLS-1$
            pke.getPrivateKey(),
            pke.getCertificateChain(),
            extraParams);

    Assert.assertNotNull(prueba, result);
    Assert.assertTrue(signer.isSign(result));

    prueba =
        "Firma PAdES de PDF certificado en SHA512withRSA indicando unicamente headLess=true"; //$NON-NLS-1$
    System.out.println(prueba);

    extraParams = new Properties();
    extraParams.put("headLess", "true"); // $NON-NLS-1$ //$NON-NLS-2$

    boolean failed = false;
    try {
      result =
          signer.sign(
              testPdf,
              "SHA512withRSA", //$NON-NLS-1$
              pke.getPrivateKey(),
              pke.getCertificateChain(),
              extraParams);
    } catch (final Exception e) {
      failed = true;
    }
    Assert.assertTrue("Deberia haber fallado", failed); // $NON-NLS-1$

    prueba =
        "Firma PAdES de PDF certificado en SHA512withRSA indicando unicamente allowSigningCertifiedPdfs=false"; //$NON-NLS-1$
    System.out.println(prueba);

    extraParams = new Properties();
    extraParams.put("allowSigningCertifiedPdfs", "false"); // $NON-NLS-1$ //$NON-NLS-2$

    failed = false;
    try {
      result =
          signer.sign(
              testPdf,
              "SHA512withRSA", //$NON-NLS-1$
              pke.getPrivateKey(),
              pke.getCertificateChain(),
              extraParams);
    } catch (final Exception e) {
      failed = true;
    }
    Assert.assertTrue("Deberia haber fallado", failed); // $NON-NLS-1$
  }
  /**
   * Prueba de PDF con sello de tiempo contra la TSA de CATCert.
   *
   * @throws Exception
   */
  @SuppressWarnings("static-method")
  @Test
  @Ignore
  public void testTimestampedSignature() throws Exception {

    Logger.getLogger("es.gob.afirma").setLevel(Level.WARNING); // $NON-NLS-1$
    final PrivateKeyEntry pke;

    final KeyStore ks = KeyStore.getInstance("PKCS12"); // $NON-NLS-1$
    ks.load(ClassLoader.getSystemResourceAsStream(CERT_PATH), CERT_PASS.toCharArray());
    pke =
        (PrivateKeyEntry)
            ks.getEntry(CERT_ALIAS, new KeyStore.PasswordProtection(CERT_PASS.toCharArray()));

    final AOSigner signer = new AOPDFSigner();

    final byte[] testPdf =
        AOUtil.getDataFromInputStream(ClassLoader.getSystemResourceAsStream(TEST_FILES[0]));

    final String prueba = "Firma PAdES de PDF con sello de tiempo en SHA512withRSA"; // $NON-NLS-1$

    System.out.println(prueba);

    final Properties extraParams = new Properties();
    // ********* TSA CATCERT ********************************************************************
    // ******************************************************************************************
    extraParams.put("tsaURL", CMSTimestamper.CATCERT_TSP); // $NON-NLS-1$
    extraParams.put("tsaPolicy", CMSTimestamper.CATCERT_POLICY); // $NON-NLS-1$
    extraParams.put("tsaRequireCert", CMSTimestamper.CATCERT_REQUIRECERT); // $NON-NLS-1$
    extraParams.put("tsaHashAlgorithm", "SHA1"); // $NON-NLS-1$ //$NON-NLS-2$
    // ******************************************************************************************
    // ********* FIN TSA CATCERT ****************************************************************

    //        //********** TSA AFIRMA
    // ********************************************************************
    //
    // //******************************************************************************************
    //        extraParams.put("tsaURL", "https://10.253.252.184:10318/tsamap/TspHttpServer");
    // //$NON-NLS-1$ //$NON-NLS-2$
    //        //extraParams.put("tsaURL",
    // "socket://10.253.252.184:318/tsamap/TspHttpServer"/*"http://des-tsafirma.redsara.es:318/tsamap/TspHttpServer"*/); //$NON-NLS-1$ //$NON-NLS-2$
    //        extraParams.put("tsaPolicy", "1.3.4.6.1.3.4.6"); //$NON-NLS-1$ //$NON-NLS-2$
    //        extraParams.put("tsaRequireCert", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    //        extraParams.put("tsaHashAlgorithm", "SHA1"); //$NON-NLS-1$ //$NON-NLS-2$
    //        extraParams.put("tsaHashAlgorithm", "SHA1"); //$NON-NLS-1$ //$NON-NLS-2$
    //        extraParams.put("tsaExtensionOid", "1.3.4.6.1.3.4.6");  //$NON-NLS-1$//$NON-NLS-2$
    //        extraParams.put("tsaExtensionValueBase64", "NOMBRE_APP_AFIRMA_EN_BASE64");
    // //$NON-NLS-1$ //$NON-NLS-2$
    //        extraParams.put("tsaUsr", "USUARIO"); //$NON-NLS-1$ //$NON-NLS-2$
    //        extraParams.put("tsaPwd", "CONTRASENA"); //$NON-NLS-1$ //$NON-NLS-2$
    //
    // //******************************************************************************************
    //        //********** FIN TSA AFIRMA
    // ****************************************************************

    final byte[] result =
        signer.sign(
            testPdf,
            "SHA512withRSA", //$NON-NLS-1$
            pke.getPrivateKey(),
            pke.getCertificateChain(),
            extraParams);

    final File saveFile = File.createTempFile("TSA-", ".pdf"); // $NON-NLS-1$ //$NON-NLS-2$
    final OutputStream os = new FileOutputStream(saveFile);
    os.write(result);
    os.flush();
    os.close();
    System.out.println(
        "Temporal para comprobacion manual: " + saveFile.getAbsolutePath()); // $NON-NLS-1$

    Assert.assertNotNull(prueba, result);
    Assert.assertTrue(signer.isSign(result));
  }