Example #1
2
  /**
   * @param caminhoCertificado
   * @param senhaCertificado
   * @paaram senhaCertificado
   * @param caminhoArquivo
   * @return
   * @throws Exception
   */
  public static String assinarDocumento(
      String caminhoCertificado, String senhaCertificado, String caminhoArquivo) throws Exception {

    final KeyStore keyStore = KeyStore.getInstance("PKCS12");
    try (InputStream certificadoStream = new FileInputStream(new File(caminhoCertificado))) {
      keyStore.load(certificadoStream, senhaCertificado.toCharArray());
    }

    final KeyStore.PrivateKeyEntry keyEntry =
        (KeyStore.PrivateKeyEntry)
            keyStore.getEntry(
                keyStore.aliases().nextElement(),
                new KeyStore.PasswordProtection(senhaCertificado.toCharArray()));

    final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");

    final List<Transform> transforms = new ArrayList<>(2);
    transforms.add(
        signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    transforms.add(
        signatureFactory.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null));

    final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
    final X509Data x509Data =
        keyInfoFactory.newX509Data(
            Collections.singletonList((X509Certificate) keyEntry.getCertificate()));
    final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));

    final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);

    final Document document =
        documentBuilderFactory.newDocumentBuilder().parse(new File(caminhoArquivo));

    for (final String elementoAssinavel : ELEMENTOS_ASSINAVEIS) {
      final NodeList elements = document.getElementsByTagName(elementoAssinavel);
      for (int i = 0; i < elements.getLength(); i++) {
        final Element element = (Element) elements.item(i);
        final String id = element.getAttribute("Id");
        element.setIdAttribute("Id", true);

        final Reference reference =
            signatureFactory.newReference(
                "#" + id,
                signatureFactory.newDigestMethod(DigestMethod.SHA1, null),
                transforms,
                null,
                null);
        final SignedInfo signedInfo =
            signatureFactory.newSignedInfo(
                signatureFactory.newCanonicalizationMethod(
                    CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null),
                signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                Collections.singletonList(reference));

        final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
        signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode()));
      }
    }

    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
      final Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      transformer.transform(new DOMSource(document), new StreamResult(outputStream));
      return outputStream.toString();
    }
  }
  private static KeyPair _getKeyPair(String p12, String alias, String password)
      throws KeyStoreException {

    KeyStore.PrivateKeyEntry entry;
    InputStream in = null;
    try {
      in = new FileInputStream(p12);
      KeyStore ks = KeyStore.getInstance("PKCS12");
      ks.load(in, password.toCharArray());

      entry =
          (KeyStore.PrivateKeyEntry)
              ks.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));
    } catch (Exception e) {
      throw new KeyStoreException(
          String.format("Failed to get certificate entry from key store: %1$s/%2$s", p12, alias),
          e);
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
        }
      }
    }

    if (entry == null) {
      throw new KeyStoreException(String.format("Bad key store: %1$s/%2$s", p12, alias));
    }

    return new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
  }
Example #3
0
 KeyStore.Entry getProtectedEntry(String alias) {
   try {
     return keyStore.getEntry(alias, getPasswordObject());
   } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
     throw new RuntimeException(String.format("Could not get keystore entry %s", alias), e);
   }
 }
Example #4
0
  /**
   * Used during setup to get the certification from the keystore and encrypt the auth_value with
   * the private key
   *
   * @return true if the certificate was found and the string encypted correctly otherwise returns
   *     false
   */
  public void setCertificate()
      throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
          NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
          BadPaddingException, UnrecoverableEntryException {
    KeyStore store = KeyStore.getInstance(this.keystore_type);
    java.io.FileInputStream fis = new java.io.FileInputStream(this.keystore_path);
    store.load(fis, this.keystore_password);

    this.cipher = Cipher.getInstance(this.cipher_type);
    this.certificate = (X509Certificate) store.getCertificate(this.cert_alias);

    if (log.isDebugEnabled()) {
      log.debug("certificate = " + this.certificate.toString());
    }

    this.cipher.init(Cipher.ENCRYPT_MODE, this.certificate);
    this.encryptedToken = this.cipher.doFinal(this.auth_value.getBytes());

    if (log.isDebugEnabled()) {
      log.debug("encryptedToken = " + this.encryptedToken);
    }

    KeyStore.PrivateKeyEntry privateKey =
        (KeyStore.PrivateKeyEntry)
            store.getEntry(this.cert_alias, new KeyStore.PasswordProtection(this.cert_password));
    this.certPrivateKey = privateKey.getPrivateKey();

    this.valueSet = true;

    if (log.isDebugEnabled()) {
      log.debug("certPrivateKey = " + this.certPrivateKey.toString());
    }
  }
  /**
   * Writes out the details of all the key store entries. This makes for a long output. For
   * debugging purposes.
   */
  public void printKeyStoreContents() {
    try {
      String alias = null;
      KeyStore.TrustedCertificateEntry entry = null;

      for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
        alias = aliases.nextElement();
        System.out.println("");
        if (alias.startsWith(aliasPrefix)) {
          System.out.print(" * ===== ");
        } else {
          System.out.print("   ===== ");
        }
        System.out.println(alias);
        if (keyStore.isKeyEntry(alias)) {
          System.out.println("   is a KeyEntry                       (details hidden)");
          continue;
        } else if (keyStore.isCertificateEntry(alias)) {
          entry = (TrustedCertificateEntry) keyStore.getEntry(alias, null);
          System.out.println(entry.toString());
        }
        System.out.flush();
      } // end for

      System.out.println("");
      System.out.print("Number of entries in key store: ");
      System.out.println(keyStore.size());
      System.out.flush();

    } catch (Exception e) {
      System.err.println("ERROR: GFIPMKeystore.printKeyStoreContents failed: ");
      System.err.println(e.toString());
      System.err.flush();
    }
  } // end printKeyStoreContents
 KeyStore.PrivateKeyEntry getKey()
     throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
         UnrecoverableEntryException {
   KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
   keyStore.load(null);
   return (PrivateKeyEntry) keyStore.getEntry(alias, null);
 }
    @Override
    protected Boolean doInBackground(String... params) {
      final String alias = params[0];
      final String dataString = params[1];
      final String signatureString = params[2];
      try {
        byte[] data = dataString.getBytes();
        byte[] signature;
        try {
          signature = Base64.decode(signatureString, Base64.DEFAULT);
        } catch (IllegalArgumentException e) {
          signature = new byte[0];
        }

        /*
         * Verify a signature previously made by a PrivateKey in our
         * KeyStore. This uses the X.509 certificate attached to our
         * private key in the KeyStore to validate a previously
         * generated signature.
         */
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        KeyStore.Entry entry = ks.getEntry(alias, null);
        if (!(entry instanceof PrivateKeyEntry)) {
          Log.w(TAG, "Not an instance of a PrivateKeyEntry");
          return false;
        }
        Signature s = Signature.getInstance("SHA256withECDSA");
        s.initVerify(((PrivateKeyEntry) entry).getCertificate());
        s.update(data);
        boolean valid = s.verify(signature);

        return valid;
      } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
      } catch (KeyStoreException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
      } catch (CertificateException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
      } catch (IOException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
      } catch (UnrecoverableEntryException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
      } catch (InvalidKeyException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
      } catch (SignatureException e) {
        Log.w(TAG, "Could not generate key", e);
        return false;
      }
    }
  public static byte[] getSharedSecret(String keyStorePath, String keyStorePassword)
      throws Exception {
    if (keyStorePath == null) return null;
    char[] password = keyStorePassword.toCharArray();
    KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(password);

    KeyStore ks = readKeyStore(keyStorePath, password);

    KeyStore.SecretKeyEntry entry =
        (KeyStore.SecretKeyEntry) ks.getEntry(CHALLENGE_RESPONSE_SECRET, protParam);
    SecretKey secretKey = entry.getSecretKey();
    return secretKey.getEncoded();
  }
    @Override
    protected String doInBackground(String... params) {
      final String alias = params[0];
      final String dataString = params[1];
      try {
        byte[] data = dataString.getBytes();

        /*
         * Use a PrivateKey in the KeyStore to create a signature over
         * some data.
         */
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        KeyStore.Entry entry = ks.getEntry(alias, null);
        if (!(entry instanceof PrivateKeyEntry)) {
          Log.w(TAG, "Not an instance of a PrivateKeyEntry");
          return null;
        }
        Signature s = Signature.getInstance("SHA256withECDSA");
        s.initSign(((PrivateKeyEntry) entry).getPrivateKey());
        s.update(data);
        byte[] signature = s.sign();

        return Base64.encodeToString(signature, Base64.DEFAULT);
      } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "Could not generate key", e);
        return null;
      } catch (KeyStoreException e) {
        Log.w(TAG, "Could not generate key", e);
        return null;
      } catch (CertificateException e) {
        Log.w(TAG, "Could not generate key", e);
        return null;
      } catch (IOException e) {
        Log.w(TAG, "Could not generate key", e);
        return null;
      } catch (UnrecoverableEntryException e) {
        Log.w(TAG, "Could not generate key", e);
        return null;
      } catch (InvalidKeyException e) {
        Log.w(TAG, "Could not generate key", e);
        return null;
      } catch (SignatureException e) {
        Log.w(TAG, "Could not generate key", e);
        return null;
      }
    }
Example #10
0
  /**
   * Prueba la firma de un PDF protegido con contrase&ntilde;a contra modificaci&oacute;n.
   *
   * @throws Exception en cualquier error
   */
  @SuppressWarnings("static-method")
  @Test
  public void testModificationPasswordSignature() 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_PWD_MOD));

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

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

    System.out.println(prueba);

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

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

    Assert.assertNotNull(prueba, result);

    final File out = File.createTempFile("TEST-PWD", ".pdf"); // $NON-NLS-1$ //$NON-NLS-2$
    final FileOutputStream fos = new FileOutputStream(out);
    fos.write(result);
    fos.flush();
    fos.close();
    System.out.println(
        "Temporal para comprobacion manual: " + out.getAbsolutePath()); // $NON-NLS-1$
  }
  /**
   * Creates an instance initialized with the key material specified in the parameters. The
   * passwords may be null in case none are set in the keystore.
   *
   * @param jksFile Stream to the keystore containing the certificate an private key.
   * @param storePass Password for the keystore itself. May be null in case none is set.
   * @param alias Alias pointing to both the certificate an the private key.
   * @param keyPass Password for the private key entry. May be null in case none is set.
   * @return Instance initialized with the key material.
   * @throws GeneralSecurityException Thrown in case the the keys could not be loaded.
   * @throws IOException Thrown in case the keystore could not be read.
   */
  @Nonnull
  public static Sha1RSASignature createInstance(
      @Nonnull InputStream jksFile,
      @Nullable String storePass,
      @Nonnull String alias,
      @Nullable String keyPass)
      throws GeneralSecurityException, IOException {
    char[] storePassChars = storePass == null ? null : storePass.toCharArray();
    char[] keyPassChars = keyPass == null ? null : keyPass.toCharArray();
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(jksFile, storePassChars);

    KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(keyPassChars);
    KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, protParam);
    PrivateKey pkey = pkEntry.getPrivateKey();
    Certificate cert = pkEntry.getCertificate();

    Sha1RSASignature inst = new Sha1RSASignature(pkey, cert);
    return inst;
  }
  /**
   * Returns the CertificateInfo for the given signing configuration.
   *
   * @return the certificate info if it could be loaded.
   * @throws KeytoolException If the password is wrong.
   * @throws FileNotFoundException If the store file cannot be found.
   */
  @NonNull
  public static CertificateInfo getCertificateInfo(
      @Nullable String storeType,
      @NonNull File storeFile,
      @NonNull String storePassword,
      @NonNull String keyPassword,
      @NonNull String keyAlias)
      throws KeytoolException, FileNotFoundException {

    try {
      KeyStore keyStore =
          KeyStore.getInstance(storeType != null ? storeType : KeyStore.getDefaultType());

      FileInputStream fis = new FileInputStream(storeFile);
      keyStore.load(fis, storePassword.toCharArray());
      fis.close();

      char[] keyPasswordArray = keyPassword.toCharArray();
      PrivateKeyEntry entry =
          (KeyStore.PrivateKeyEntry)
              keyStore.getEntry(keyAlias, new KeyStore.PasswordProtection(keyPasswordArray));

      if (entry == null) {
        throw new KeytoolException(
            String.format(
                "No key with alias '%1$s' found in keystore %2$s",
                keyAlias, storeFile.getAbsolutePath()));
      }

      return new CertificateInfo(entry.getPrivateKey(), (X509Certificate) entry.getCertificate());
    } catch (FileNotFoundException e) {
      throw e;
    } catch (Exception e) {
      throw new KeytoolException(
          String.format(
              "Failed to read key %1$s from store \"%2$s\": %3$s",
              keyAlias, storeFile, e.getMessage()),
          e);
    }
  }
  /** java.security.KeyStore#getEntry(String, KeyStore.ProtectionParameter) */
  public void test_getEntry() throws Exception {
    String type = "DSA";

    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.getEntry("anAlias", new KeyStore.PasswordProtection(new char[] {}));
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, pssWord);

    try {
      keyTest.getEntry(null, new KeyStore.PasswordProtection(new char[] {}));
      fail();
    } catch (NullPointerException expected) {
    }

    keyTest.getEntry("anAlias", null);

    try {
      keyTest.getEntry(null, null);
      fail();
    } catch (NullPointerException expected) {
    }

    assertNull(keyTest.getEntry("alias", null));

    Certificate[] chain = {
      new MyCertificate(type, testEncoding), new MyCertificate(type, testEncoding)
    };

    DSAPrivateKey privateKey1 =
        (DSAPrivateKey)
            KeyFactory.getInstance(type)
                .generatePrivate(
                    new DSAPrivateKeySpec(
                        new BigInteger("1"),
                        new BigInteger("2"),
                        new BigInteger("3"),
                        new BigInteger("4")));

    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(pssWord);
    assertNull(keyTest.getEntry("alias", pp));

    KeyStore.PrivateKeyEntry pke1 = new KeyStore.PrivateKeyEntry(getPrivateKey(), chain);
    KeyStore.PrivateKeyEntry pke2 = new KeyStore.PrivateKeyEntry(privateKey1, chain);

    keyTest.setEntry("alias1", pke1, pp);
    keyTest.setEntry("alias2", pke2, pp);

    assertNull(keyTest.getEntry("alias", pp));
    KeyStore.PrivateKeyEntry pkeActual1 = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias1", pp);
    KeyStore.PrivateKeyEntry pkeActual2 = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias2", pp);

    assertTrue(Arrays.equals(chain, pkeActual1.getCertificateChain()));
    assertEquals(getPrivateKey(), pkeActual1.getPrivateKey());
    assertEquals(new MyCertificate(type, testEncoding), pkeActual1.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias1", KeyStore.PrivateKeyEntry.class));

    assertTrue(Arrays.equals(chain, pkeActual2.getCertificateChain()));
    DSAPrivateKey entryPrivateKey = (DSAPrivateKey) pkeActual2.getPrivateKey();
    assertEquals(privateKey1.getX(), entryPrivateKey.getX());
    assertEquals(privateKey1.getParams().getG(), entryPrivateKey.getParams().getG());
    assertEquals(privateKey1.getParams().getP(), entryPrivateKey.getParams().getP());
    assertEquals(privateKey1.getParams().getQ(), entryPrivateKey.getParams().getQ());

    assertEquals(new MyCertificate(type, testEncoding), pkeActual2.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias2", KeyStore.PrivateKeyEntry.class));
  }
Example #14
0
  /**
   * Prueba la firma de un PDF certificado.
   *
   * @throws Exception en cualquier error
   */
  @SuppressWarnings("static-method")
  @Test
  public void testCertificatedSignature() 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]));

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

    String prueba =
        "Firma certificada PAdES de documento PDF indicando la propiedad certificationLevel"; //$NON-NLS-1$

    String[] certificationLevels =
        new String[] {
          "Firma de autor. No se permite ningun cambio posterior en el documento", //$NON-NLS-1$
          "Firma de autor certificada para formularios. Se permite unicamente el relleno posterior de los campos del formulario", //$NON-NLS-1$
          "Firma certificada. Se permite unicamente el relleno posterior de los campos del formulario o el anadido de firmas de aprobacion" //$NON-NLS-1$
        };

    System.out.println(prueba);

    Properties extraParams = new Properties();

    for (int i = 1; i <= certificationLevels.length; i++) {

      extraParams.put("certificationLevel", Integer.toString(i)); // $NON-NLS-1$

      System.out.println(certificationLevels[i - 1]);

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

      final File tempFile = File.createTempFile("afirmaPDF", ".pdf"); // $NON-NLS-1$ //$NON-NLS-2$

      final FileOutputStream fos = new FileOutputStream(tempFile);
      fos.write(result);
      fos.close();

      //        	Logger.getLogger("es.gob.afirma").info( //$NON-NLS-1$
      //        			"Fichero temporal para la comprobacion manual del resultado: " + //$NON-NLS-1$
      //        			tempFile.getAbsolutePath());
      System.out.println(
          "Fichero temporal para la comprobacion manual del resultado: "
              + //$NON-NLS-1$
              tempFile.getAbsolutePath());
    }
  }
Example #15
0
  /**
   * 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$
  }
Example #16
0
  /**
   * 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$
        }
      }
    }
  }
Example #17
0
  /**
   * 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));
  }
Example #18
0
  public static TokenSearchResults searchTokenEntries(
      final KeyStore keyStore,
      final int startIndex,
      final int max,
      final QueryCriteria qc,
      final boolean includeData)
      throws CryptoTokenOfflineException, QueryException {
    final TokenSearchResults result;
    try {
      final ArrayList<TokenEntry> tokenEntries = new ArrayList<TokenEntry>();
      final Enumeration<String> e =
          keyStore
              .aliases(); // We assume the order is the same for every call unless entries has been
                          // added or removed

      final long maxIndex = (long) startIndex + max;
      for (int i = 0; i < maxIndex && e.hasMoreElements(); ) {
        final String keyAlias = e.nextElement();

        final String type;
        if (keyStore.entryInstanceOf(keyAlias, KeyStore.PrivateKeyEntry.class)) {
          type = TokenEntry.TYPE_PRIVATEKEY_ENTRY;
        } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) {
          type = TokenEntry.TYPE_SECRETKEY_ENTRY;
        } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.TrustedCertificateEntry.class)) {
          type = TokenEntry.TYPE_TRUSTED_ENTRY;
        } else {
          type = null;
        }

        TokenEntry entry = new TokenEntry(keyAlias, type);

        if (shouldBeIncluded(entry, qc)) {
          if (i < startIndex) {
            i++;
            continue;
          }

          if (LOG.isDebugEnabled()) {
            LOG.debug("checking keyAlias: " + keyAlias);
          }

          // Add additional data
          if (includeData) {
            Map<String, String> info = new HashMap<String, String>();
            try {
              Date creationDate = keyStore.getCreationDate(keyAlias);
              entry.setCreationDate(creationDate);
            } catch (ProviderException ex) {
            } // NOPMD: We ignore if it is not supported

            if (TokenEntry.TYPE_PRIVATEKEY_ENTRY.equals(type)) {
              final Certificate[] chain = keyStore.getCertificateChain(keyAlias);
              if (chain.length > 0) {
                info.put(
                    INFO_KEY_ALGORITHM, AlgorithmTools.getKeyAlgorithm(chain[0].getPublicKey()));
                info.put(
                    INFO_KEY_SPECIFICATION,
                    AlgorithmTools.getKeySpecification(chain[0].getPublicKey()));
              }
              try {
                entry.setParsedChain(chain);
              } catch (CertificateEncodingException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
              }
            } else if (TokenEntry.TYPE_TRUSTED_ENTRY.equals(type)) {
              Certificate certificate = keyStore.getCertificate(keyAlias);
              try {
                entry.setParsedTrustedCertificate(certificate);
              } catch (CertificateEncodingException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
              }
            } else if (TokenEntry.TYPE_SECRETKEY_ENTRY.equals(type)) {
              try {
                KeyStore.Entry entry1 = keyStore.getEntry(keyAlias, null);
                SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry1).getSecretKey();

                info.put(INFO_KEY_ALGORITHM, secretKey.getAlgorithm());
                // info.put(INFO_KEY_SPECIFICATION,
                // AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); // TODO: Key
                // specification support for secret keys
              } catch (NoSuchAlgorithmException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
              } catch (UnrecoverableEntryException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
              }
            }
            entry.setInfo(info);
          }
          tokenEntries.add(entry);

          // Increase index
          i++;
        }
      }
      result = new TokenSearchResults(tokenEntries, e.hasMoreElements());
    } catch (KeyStoreException ex) {
      throw new CryptoTokenOfflineException(ex);
    }
    return result;
  }
  /**
   * @param chnlId
   * @param xmlStr
   * @param chnlStr
   * @return
   */
  public String processXMLForChnls(String chnlId, String xmlStr, final String chnlStr) {
    if ("106".equals(chnlId) || "102".equals(chnlId)) {
      try {
        xmlStr = URLEncoder.encode(xmlStr.trim(), "UTF-8");
      } catch (UnsupportedEncodingException e) {
      }
      xmlStr = "xml=".concat(xmlStr);

    } else if ("103".equals(chnlId) && !"Route1_CONT".equals(chnlStr)) {

      xmlStr =
          "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
              + "<soap:Header>"
              + "<SOAP-SEC:Signature xmlns:SOAP-SEC=\"http://schemas.xmlsoap.org/soap/security/2000-12\">"
              + "</SOAP-SEC:Signature>"
              + "</soap:Header>".concat(xmlStr).concat("</soap:Envelope>");
      try {

        // Create a DOM XMLSignatureFactory that will be used to
        // generate the enveloped signature.
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        Reference ref =
            fac.newReference(
                "#Body",
                fac.newDigestMethod(DigestMethod.SHA1, null),
                Collections.singletonList(
                    fac.newTransform(
                        "http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null)),
                null,
                null);

        // Create the SignedInfo.
        SignedInfo si =
            fac.newSignedInfo(
                fac.newCanonicalizationMethod(
                    CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                Collections.singletonList(ref));

        // Load the KeyStore and get the signing key and
        // certificate.
        KeyStore ks = KeyStore.getInstance("JKS");

        String certFileNm = "";
        // commonConfigHelper.getConfigMap().get(
        // "ROUTE1_CERTIFICATE_JSK");
        String pwd = ""; // commonConfigHelper.getConfigMap().get(
        // "ROUTE1_CERTIFICATE_PASSWORD");
        String aliasNm = ""; // commonConfigHelper.getConfigMap().get(
        // "ROUTE1_CERTIFICATE_ALIAS");
        ks.load(new FileInputStream(certFileNm), pwd.toCharArray());
        KeyStore.PrivateKeyEntry keyEntry =
            (KeyStore.PrivateKeyEntry)
                ks.getEntry(aliasNm, new KeyStore.PasswordProtection(pwd.toCharArray()));
        X509Certificate cert = (X509Certificate) keyEntry.getCertificate();

        // Create the KeyInfo containing the X509Data.
        KeyInfoFactory kif = fac.getKeyInfoFactory();
        List x509Content = new ArrayList();
        // x509Content.add(cert.getSubjectX500Principal().getName());
        x509Content.add(cert.getIssuerX500Principal().getName());
        X509Data xd = kif.newX509Data(x509Content);
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));

        // Instantiate the document to be signed.
        // Document doc = xmlUtil.getDocumentFromString(xmlStr);
        Document doc = null;

        // Create a DOMSignContext and specify the RSA PrivateKey
        // and
        // location of the resulting XMLSignature's parent element.
        DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());

        // Create the XMLSignature, but don't sign it yet.
        XMLSignature signature = fac.newXMLSignature(si, ki);

        // Marshal, generate, and sign the enveloped signature.
        signature.sign(dsc);

        // Output the resulting document.

        xmlStr = xmlUtil.convertXMLDocToString(doc);

      } catch (Exception e) {
      }
    }
    return xmlStr;
  }
  /** java.security.KeyStore#setEntry(String, KeyStore.Entry, KeyStore.ProtectionParameter) */
  public void test_setEntry() throws Exception {
    String type = "DSA";

    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    keyTest.load(null, pssWord);

    Certificate[] chain = {
      new MyCertificate(type, testEncoding), new MyCertificate(type, testEncoding)
    };
    DSAPrivateKey privateKey1 =
        (DSAPrivateKey)
            KeyFactory.getInstance(type)
                .generatePrivate(
                    new DSAPrivateKeySpec(
                        new BigInteger("1"),
                        new BigInteger("2"),
                        new BigInteger("3"),
                        new BigInteger("4")));

    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(pssWord);
    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(getPrivateKey(), chain);
    KeyStore.PrivateKeyEntry pke1 = new KeyStore.PrivateKeyEntry(privateKey1, chain);

    try {
      keyTest.setEntry("alias", pke, null);
      assertFalse(StandardNames.IS_RI); // BKS KeyStore does not require a password
    } catch (KeyStoreException e) {
      assertTrue(StandardNames.IS_RI); // JKS KeyStore requires a password
    }

    keyTest.setEntry("alias", pke, pp);

    KeyStore.PrivateKeyEntry pkeActual = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias", pp);

    assertTrue(Arrays.equals(chain, pkeActual.getCertificateChain()));
    assertEquals(getPrivateKey(), pkeActual.getPrivateKey());
    assertEquals(new MyCertificate(type, testEncoding), pkeActual.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias", KeyStore.PrivateKeyEntry.class));

    keyTest.setEntry("alias", pke1, pp);
    pkeActual = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias", pp);

    assertTrue(Arrays.equals(chain, pkeActual.getCertificateChain()));
    DSAPrivateKey actualPrivateKey = (DSAPrivateKey) pkeActual.getPrivateKey();
    assertEquals(privateKey1.getX(), actualPrivateKey.getX());
    assertEquals(privateKey1.getParams().getG(), actualPrivateKey.getParams().getG());
    assertEquals(privateKey1.getParams().getP(), actualPrivateKey.getParams().getP());
    assertEquals(privateKey1.getParams().getQ(), actualPrivateKey.getParams().getQ());
    assertEquals(new MyCertificate(type, testEncoding), pkeActual.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias", KeyStore.PrivateKeyEntry.class));

    keyTest.setEntry("alias2", pke1, pp);
    pkeActual = (KeyStore.PrivateKeyEntry) keyTest.getEntry("alias2", pp);

    assertTrue(Arrays.equals(chain, pkeActual.getCertificateChain()));
    actualPrivateKey = (DSAPrivateKey) pkeActual.getPrivateKey();
    assertEquals(privateKey1.getX(), actualPrivateKey.getX());
    assertEquals(privateKey1.getParams().getG(), actualPrivateKey.getParams().getG());
    assertEquals(privateKey1.getParams().getP(), actualPrivateKey.getParams().getP());
    assertEquals(privateKey1.getParams().getQ(), actualPrivateKey.getParams().getQ());
    assertEquals(new MyCertificate(type, testEncoding), pkeActual.getCertificate());
    assertTrue(keyTest.entryInstanceOf("alias2", KeyStore.PrivateKeyEntry.class));

    try {
      keyTest.setEntry(null, null, null);
      fail();
    } catch (NullPointerException expected) {
    }
  }
  private boolean doExport(IProgressMonitor monitor) {
    try {
      // if needed, create the keystore and/or key.
      if (mKeystoreCreationMode || mKeyCreationMode) {
        final ArrayList<String> output = new ArrayList<String>();
        boolean createdStore =
            KeystoreHelper.createNewStore(
                mKeystore,
                null /*storeType*/,
                mKeystorePassword,
                mKeyAlias,
                mKeyPassword,
                mDName,
                mValidity,
                new IKeyGenOutput() {
                  @Override
                  public void err(String message) {
                    output.add(message);
                  }

                  @Override
                  public void out(String message) {
                    output.add(message);
                  }
                });

        if (createdStore == false) {
          // keystore creation error!
          displayError(output.toArray(new String[output.size()]));
          return false;
        }

        // keystore is created, now load the private key and certificate.
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream fis = new FileInputStream(mKeystore);
        keyStore.load(fis, mKeystorePassword.toCharArray());
        fis.close();
        PrivateKeyEntry entry =
            (KeyStore.PrivateKeyEntry)
                keyStore.getEntry(
                    mKeyAlias, new KeyStore.PasswordProtection(mKeyPassword.toCharArray()));

        if (entry != null) {
          mPrivateKey = entry.getPrivateKey();
          mCertificate = (X509Certificate) entry.getCertificate();
        } else {
          // this really shouldn't happen since we now let the user choose the key
          // from a list read from the store.
          displayError("Could not find key");
          return false;
        }
      }

      // check the private key/certificate again since it may have been created just above.
      if (mPrivateKey != null && mCertificate != null) {
        boolean runZipAlign = false;
        String path = AdtPlugin.getOsAbsoluteZipAlign();
        File zipalign = new File(path);
        runZipAlign = zipalign.isFile();

        File apkExportFile = mDestinationFile;
        if (runZipAlign) {
          // create a temp file for the original export.
          apkExportFile = File.createTempFile("androidExport_", ".apk");
        }

        // export the signed apk.
        ExportHelper.exportReleaseApk(mProject, apkExportFile, mPrivateKey, mCertificate, monitor);

        // align if we can
        if (runZipAlign) {
          String message = zipAlign(path, apkExportFile, mDestinationFile);
          if (message != null) {
            displayError(message);
            return false;
          }
        } else {
          AdtPlugin.displayWarning(
              "Export Wizard",
              "The zipalign tool was not found in the SDK.\n\n"
                  + "Please update to the latest SDK and re-export your application\n"
                  + "or run zipalign manually.\n\n"
                  + "Aligning applications allows Android to use application resources\n"
                  + "more efficiently.");
        }

        return true;
      }
    } catch (Throwable t) {
      displayError(t);
    }

    return false;
  }
Example #22
0
  public void signJar(Jar jar) {
    if (digestNames == null || digestNames.length == 0)
      error("Need at least one digest algorithm name, none are specified");

    if (keystoreFile == null || !keystoreFile.getAbsoluteFile().exists()) {
      error("No such keystore file: " + keystoreFile);
      return;
    }

    if (alias == null) {
      error("Private key alias not set for signing");
      return;
    }

    MessageDigest digestAlgorithms[] = new MessageDigest[digestNames.length];

    getAlgorithms(digestNames, digestAlgorithms);

    try {
      Manifest manifest = jar.getManifest();
      manifest.getMainAttributes().putValue("Signed-By", "Bnd");

      // Create a new manifest that contains the
      // Name parts with the specified digests

      ByteArrayOutputStream o = new ByteArrayOutputStream();
      manifest.write(o);
      doManifest(jar, digestNames, digestAlgorithms, o);
      o.flush();
      byte newManifestBytes[] = o.toByteArray();
      jar.putResource("META-INF/MANIFEST.MF", new EmbeddedResource(newManifestBytes, 0));

      // Use the bytes from the new manifest to create
      // a signature file

      byte[] signatureFileBytes = doSignatureFile(digestNames, digestAlgorithms, newManifestBytes);
      jar.putResource("META-INF/BND.SF", new EmbeddedResource(signatureFileBytes, 0));

      // Now we must create an RSA signature
      // this requires the private key from the keystore

      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

      KeyStore.PrivateKeyEntry privateKeyEntry = null;

      java.io.FileInputStream keystoreInputStream = null;
      try {
        keystoreInputStream = new java.io.FileInputStream(keystoreFile);
        char[] pw = password == null ? new char[0] : password.toCharArray();

        keystore.load(keystoreInputStream, pw);
        keystoreInputStream.close();
        privateKeyEntry =
            (PrivateKeyEntry) keystore.getEntry(alias, new KeyStore.PasswordProtection(pw));
      } catch (Exception e) {
        error(
            "No able to load the private key from the give keystore("
                + keystoreFile.getAbsolutePath()
                + ") with alias "
                + alias
                + " : "
                + e);
        return;
      } finally {
        IO.close(keystoreInputStream);
      }
      PrivateKey privateKey = privateKeyEntry.getPrivateKey();

      Signature signature = Signature.getInstance("MD5withRSA");
      signature.initSign(privateKey);

      signature.update(signatureFileBytes);

      signature.sign();

      // TODO, place the SF in a PCKS#7 structure ...
      // no standard class for this? The following
      // is an idea but we will to have do ASN.1 BER
      // encoding ...

      ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
      jar.putResource("META-INF/BND.RSA", new EmbeddedResource(tmpStream.toByteArray(), 0));
    } catch (Exception e) {
      error("During signing: " + e);
    }
  }