Esempio n. 1
0
  /**
   * see if we can find an algorithm (or its alias and what it represents) in the property table for
   * the given provider.
   *
   * @return null if no algorithm found, an Implementation if it is.
   */
  static Implementation getImplementation(
      String baseName, String algorithm, Provider prov, Class[] ctorparamtype, Object[] ctorparam)
      throws InvalidAlgorithmParameterException {
    String alias;

    while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) {
      algorithm = alias;
    }

    String className = prov.getProperty(baseName + "." + algorithm);

    if (className != null) {
      try {
        return new Implementation(
            Class.forName(className).getConstructor(ctorparamtype).newInstance(ctorparam), prov);
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException(
            "algorithm " + algorithm + " in provider " + prov.getName() + " but no class found!");
      } catch (Exception e) {
        if (e instanceof InvalidAlgorithmParameterException) {
          throw (InvalidAlgorithmParameterException) e;
        }

        throw new IllegalStateException(
            "algorithm "
                + algorithm
                + " in provider "
                + prov.getName()
                + " but class inaccessible!");
      }
    }

    return null;
  }
 static {
   for (Provider provider : Security.getProviders()) {
     if (provider.getName().startsWith("SunPKCS11")) {
       Security.removeProvider(provider.getName());
     }
   }
 }
Esempio n. 3
0
 private void premain(Provider p) throws Exception {
   long start = System.currentTimeMillis();
   System.out.println("Running test with provider " + p.getName() + "...");
   main(p);
   long stop = System.currentTimeMillis();
   System.out.println(
       "Completed test with provider " + p.getName() + " (" + (stop - start) + " ms).");
 }
Esempio n. 4
0
  public String getSecurityProviders() {
    StringBuilder sb = new StringBuilder();
    Provider[] p = Security.getProviders();

    for (Provider provider : p) {
      sb.append(provider.getName())
          .append("   ")
          .append(provider.getVersion())
          .append("   ")
          .append(provider.getInfo())
          .append("<br>");
    }

    Set<String> s = Security.getAlgorithms("MessageDigest");
    for (String string : s) {
      sb.append(string).append("   ");
    }

    sb.append(Integer.toBinaryString(7))
        .append("   ")
        .append(Integer.toOctalString(15))
        .append("   ")
        .append(Integer.toHexString(17));

    return sb.toString();
  }
Esempio n. 5
0
 /** 获取当前所有提供者 */
 public static void getAllProviders() {
   for (Provider provider : Security.getProviders()) {
     System.out.println("provider name:" + provider.getName());
     for (Map.Entry<Object, Object> map : provider.entrySet()) {
       System.out.println("key=" + map.getKey());
       System.out.println("value=" + map.getValue());
     }
   }
 }
Esempio n. 6
0
  /**
   * see if we can find an algorithm (or its alias and what it represents) in the property table for
   * the given provider.
   *
   * @return null if no algorithm found, an Implementation if it is.
   */
  static Implementation getImplementation(String baseName, String algorithm, Provider prov) {
    if (prov == null) {
      Provider[] provider = Security.getProviders();

      //
      // search every provider looking for the algorithm we want.
      //
      for (int i = 0; i != provider.length; i++) {
        Implementation imp = getImplementation(baseName, algorithm, provider[i]);
        if (imp != null) {
          return imp;
        }
      }

      return null;
    }

    String alias;

    while ((alias = prov.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) {
      algorithm = alias;
    }

    String className = prov.getProperty(baseName + "." + algorithm);

    if (className != null) {
      try {
        return new Implementation(Class.forName(className).newInstance(), prov);
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException(
            "algorithm " + algorithm + " in provider " + prov.getName() + " but no class found!");
      } catch (Exception e) {
        throw new IllegalStateException(
            "algorithm "
                + algorithm
                + " in provider "
                + prov.getName()
                + " but class inaccessible: "
                + e.toString());
      }
    }

    return null;
  }
Esempio n. 7
0
 static Instance getInstance(String type, Class<?> clazz, String algorithm, Provider provider)
     throws NoSuchAlgorithmException {
   Service s = GetInstance.getService(type, algorithm, provider);
   Exception ve = JceSecurity.getVerificationResult(provider);
   if (ve != null) {
     String msg = "JCE cannot authenticate the provider " + provider.getName();
     throw new SecurityException(msg, ve);
   }
   return GetInstance.getInstance(s, clazz);
 }
 /**
  * Inizializza il Verificatore passandogli come parametro la busta crittografica di cui deve
  * verificare la firma
  *
  * @param signedData la busta crittografica da controllare
  * @param token Il token crittografico contenente i certicati di ROOT utilizzati dal verificatore
  *     per verificare l'affidabilità dei certificati dei firmatari
  */
 CadesBESVerifier(CMSSignedData signedData, CRToken token) {
   // inizializza il provider di Bouncy Castle
   Provider p1 = new BouncyCastleProvider();
   Security.addProvider(p1);
   this.bcProvName = p1.getName();
   this.signedData = signedData;
   if (this.signedData == null) throw new NullPointerException();
   if (token != null) this.token = token;
   this.certStore = this.signedData.getCertificates();
 }
 static Provider findProvider(String name) {
   Provider[] providers = Security.getProviders();
   Provider registeredProvider = null;
   for (Provider provider : providers) {
     if (name.equals(provider.getName())) {
       registeredProvider = provider;
       break;
     }
   }
   return registeredProvider;
 }
Esempio n. 10
0
 private static Object findImplEngine(final String baseName, String algorithm) {
   final Provider bcProvider = securityProvider;
   String alias;
   while ((alias = bcProvider.getProperty("Alg.Alias." + baseName + "." + algorithm)) != null) {
     algorithm = alias;
   }
   final String className = bcProvider.getProperty(baseName + "." + algorithm);
   if (className != null) {
     try {
       Class klass;
       ClassLoader loader = bcProvider.getClass().getClassLoader();
       if (loader != null) {
         klass = loader.loadClass(className);
       } else {
         klass = Class.forName(className);
       }
       return klass.newInstance();
     } catch (ClassNotFoundException e) {
       throw new IllegalStateException(
           "algorithm "
               + algorithm
               + " in provider "
               + bcProvider.getName()
               + " but no class \""
               + className
               + "\" found!");
     } catch (Exception e) {
       throw new IllegalStateException(
           "algorithm "
               + algorithm
               + " in provider "
               + bcProvider.getName()
               + " but class \""
               + className
               + "\" inaccessible!");
     }
   }
   return null;
 }
Esempio n. 11
0
  public static void testDefault(PKCS11Test test) throws Exception {
    // run test for default configured PKCS11 providers (if any)

    if ("true".equals(System.getProperty("NO_DEFAULT"))) {
      return;
    }

    Provider[] providers = Security.getProviders();
    for (int i = 0; i < providers.length; i++) {
      Provider p = providers[i];
      if (p.getName().startsWith("SunPKCS11-")) {
        test.premain(p);
      }
    }
  }
Esempio n. 12
0
 private static void checkProviderInfoEntries(Provider p) throws Exception {
   String value = (String) p.get("Provider.id name");
   if (!SampleProvider.NAME.equalsIgnoreCase(value) || !p.getName().equalsIgnoreCase(value)) {
     throw new Exception("Test Failed: incorrect name!");
   }
   value = (String) p.get("Provider.id info");
   if (!SampleProvider.INFO.equalsIgnoreCase(value) || !p.getInfo().equalsIgnoreCase(value)) {
     throw new Exception("Test Failed: incorrect info!");
   }
   value = (String) p.get("Provider.id className");
   if (!p.getClass().getName().equalsIgnoreCase(value)) {
     throw new Exception("Test Failed: incorrect className!");
   }
   double dvalue = Double.parseDouble((String) p.get("Provider.id version"));
   if ((SampleProvider.VERSION != dvalue) || p.getVersion() != dvalue) {
     throw new Exception("Test Failed: incorrect version!");
   }
   System.out.println("Test Passed");
 }
  public void main(Provider p) throws Exception {

    /*
     * Use Solaris SPARC 11.2 or later to avoid an intermittent failure
     * when running SunPKCS11-Solaris (8044554)
     */
    if (p.getName().equals("SunPKCS11-Solaris")
        && System.getProperty("os.name").equals("SunOS")
        && System.getProperty("os.arch").equals("sparcv9")
        && System.getProperty("os.version").compareTo("5.11") <= 0
        && getDistro().compareTo("11.2") < 0) {

      System.out.println(
          "SunPKCS11-Solaris provider requires " + "Solaris SPARC 11.2 or later, skipping");
      return;
    }

    long start = System.currentTimeMillis();
    provider = p;
    data = new byte[2048];
    new Random().nextBytes(data);
    KeyStore ks = getKeyStore();
    KeyFactory kf = KeyFactory.getInstance("RSA", provider);
    for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
      String alias = (String) e.nextElement();
      if (ks.isKeyEntry(alias)) {
        System.out.println("* Key " + alias + "...");
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password);
        PublicKey publicKey = ks.getCertificate(alias).getPublicKey();
        privateKey = (PrivateKey) kf.translateKey(privateKey);
        publicKey = (PublicKey) kf.translateKey(publicKey);
        test(privateKey, publicKey);
      }
    }
    long stop = System.currentTimeMillis();
    System.out.println("All tests passed (" + (stop - start) + " ms).");
  }
Esempio n. 14
0
  /**
   * Makes sure all all expected implementations (but not aliases) and that there are no extras,
   * according to what we expect from StandardNames
   */
  public void test_Provider_getServices() throws Exception {

    // build set of expected algorithms
    Map<String, Set<String>> remaining =
        new HashMap<String, Set<String>>(StandardNames.PROVIDER_ALGORITHMS);
    for (Entry<String, Set<String>> entry : remaining.entrySet()) {
      entry.setValue(new HashSet<String>(entry.getValue()));
    }

    List<String> extra = new ArrayList();
    List<String> missing = new ArrayList();

    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
      String providerName = provider.getName();
      // ignore BouncyCastle provider if it is installed on the RI
      if (StandardNames.IS_RI && providerName.equals("BC")) {
        continue;
      }
      Set<Provider.Service> services = provider.getServices();
      assertNotNull(services);
      assertFalse(services.isEmpty());

      for (Provider.Service service : services) {
        String type = service.getType();
        String algorithm = service.getAlgorithm().toUpperCase();
        String className = service.getClassName();
        if (false) {
          System.out.println(providerName + " " + type + " " + algorithm + " " + className);
        }

        // remove from remaining, assert unknown if missing
        Set<String> algorithms = remaining.get(type);
        if (algorithms == null || !algorithms.remove(algorithm)) {
          // seems to be missing, but sometimes the same
          // algorithm is available from multiple providers
          // (e.g. KeyFactory RSA is available from
          // SunRsaSign and SunJSSE), so double check in
          // original source before giving error
          if (!(StandardNames.PROVIDER_ALGORITHMS.containsKey(type)
              && StandardNames.PROVIDER_ALGORITHMS.get(type).contains(algorithm))) {
            extra.add("Unknown " + type + " " + algorithm + " " + providerName + "\n");
          }
        }
        if (algorithms != null && algorithms.isEmpty()) {
          remaining.remove(type);
        }

        // make sure class exists and can be initialized
        try {
          assertNotNull(Class.forName(className, true, provider.getClass().getClassLoader()));
        } catch (ClassNotFoundException e) {
          // Sun forgot their own class
          if (!className.equals("sun.security.pkcs11.P11MAC")) {
            missing.add(className);
          }
        }
      }
    }

    // assert that we don't have any extra in the implementation
    Collections.sort(extra); // sort so that its grouped by type
    assertEquals("Extra algorithms", Collections.EMPTY_LIST, extra);

    // assert that we don't have any missing in the implementation
    assertEquals("Missing algorithms", Collections.EMPTY_MAP, remaining);

    // assert that we don't have any missing classes
    Collections.sort(missing); // sort it for readability
    assertEquals("Missing classes", Collections.EMPTY_LIST, missing);
  }
Esempio n. 15
0
  /**
   * Makes sure all provider properties either point to a class implementation that exists or are
   * aliases to known algorithms.
   */
  public void test_Provider_Properties() throws Exception {
    /*
     * A useful reference on Provider properties
     * <a href="http://java.sun.com/javase/6/docs/technotes/guides/security/crypto/HowToImplAProvider.html>
     * How to Implement a Provider in the Java &trade; Cryptography Architecture
     * </a>
     */

    Provider[] providers = Security.getProviders();
    for (Provider provider : providers) {
      // check Provider.id proprieties
      assertEquals(provider.getName(), provider.get("Provider.id name"));
      assertEquals(String.valueOf(provider.getVersion()), provider.get("Provider.id version"));
      assertEquals(provider.getInfo(), provider.get("Provider.id info"));
      assertEquals(provider.getClass().getName(), provider.get("Provider.id className"));

      // build map of all known aliases and implementations
      Map<String, String> aliases = new HashMap<String, String>();
      Map<String, String> implementations = new HashMap<String, String>();
      for (Entry<Object, Object> entry : provider.entrySet()) {
        Object k = entry.getKey();
        Object v = entry.getValue();
        assertEquals(String.class, k.getClass());
        assertEquals(String.class, v.getClass());
        String key = (String) k;
        String value = (String) v;

        // skip Provider.id keys, we check well known ones values above
        if (key.startsWith("Provider.id ")) {
          continue;
        }

        // skip property settings such as: "Signature.SHA1withDSA ImplementedIn" "Software"
        if (key.indexOf(' ') != -1) {
          continue;
        }

        Matcher m = alias.matcher(key);
        if (m.find()) {
          String type = m.group(1);
          aliases.put(key, type + "." + value);
        } else {
          implementations.put(key, value);
        }
      }

      // verify implementation classes are available
      for (Entry<String, String> entry : implementations.entrySet()) {
        String typeAndAlgorithm = entry.getKey();
        String className = entry.getValue();
        try {
          assertNotNull(Class.forName(className, true, provider.getClass().getClassLoader()));
        } catch (ClassNotFoundException e) {
          // Sun forgot their own class
          if (!className.equals("sun.security.pkcs11.P11MAC")) {
            fail("Could not find class " + className + " for " + typeAndAlgorithm);
          }
        }
      }

      // make sure all aliases point to some known implementation
      for (Entry<String, String> entry : aliases.entrySet()) {
        String alias = entry.getKey();
        String actual = entry.getValue();
        assertTrue(
            "Could not find implementation " + actual + " for alias " + alias,
            implementations.containsKey(actual));
      }
    }
  }
Esempio n. 16
0
  public static void main(String[] argv) throws Exception {
    OptionSet args = parseOptions(argv);

    if (args.has(OPT_VERBOSE)) {
      verbose = true;
      // Set up slf4j simple in a way that pleases us
      System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug");
      System.setProperty("org.slf4j.simpleLogger.showThreadName", "true");
      System.setProperty("org.slf4j.simpleLogger.showShortLogName", "true");
      System.setProperty("org.slf4j.simpleLogger.levelInBrackets", "true");
    } else {
      System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "warn");
    }

    if (args.has(OPT_VERSION)) {
      String version = "apdu4j " + getVersion(SCTool.class);
      // Append host information
      version += "\nRunning on " + System.getProperty("os.name");
      version += " " + System.getProperty("os.version");
      version += " " + System.getProperty("os.arch");
      version += ", Java " + System.getProperty("java.version");
      version += " by " + System.getProperty("java.vendor");
      System.out.println(version);
    }
    if (args.has(OPT_TEST_SERVER)) {
      // TODO: have the possibility to run SocketServer as well?
      RemoteTerminalServer srv = new RemoteTerminalServer(TestServer.class);
      srv.start(string2socket((String) args.valueOf(OPT_TEST_SERVER)));
      System.console().readLine("Press enter to stop\n");
      srv.stop(1);
      System.exit(0);
    }

    // List TerminalFactory providers
    if (args.has(OPT_PROVIDERS)) {
      Provider providers[] = Security.getProviders("TerminalFactory.PC/SC");
      if (providers != null) {
        System.out.println("Existing TerminalFactory providers:");
        for (Provider p : providers) {
          System.out.println(p.getName());
        }
      }
    }

    // Fix properties on non-windows platforms
    TerminalManager.fixPlatformPaths();

    // Only applies to SunPCSC
    if (args.has(OPT_NO_GET_RESPONSE)) {
      System.setProperty("sun.security.smartcardio.t0GetResponse", "false");
      System.setProperty("sun.security.smartcardio.t1GetResponse", "false");
    }

    // Override PC/SC library path
    if (args.has(OPT_LIB)) {
      System.setProperty("sun.security.smartcardio.library", (String) args.valueOf(OPT_LIB));
    }

    TerminalFactory tf = null;
    CardTerminals terminals = null;

    try {
      // Get a terminal factory
      if (args.has(OPT_PROVIDER)) {
        String pn = (String) args.valueOf(OPT_PROVIDER);
        String pt = (String) args.valueOf(OPT_PROVIDER_TYPE);
        tf = loadFactory(pn, pt);
      } else if (args.has(OPT_SUN)) {
        tf = loadFactory(SUN_CLASS, null);
      } else if (args.has(OPT_JNA)) {
        tf = loadFactory(JNA_CLASS, null);
      } else {
        tf = TerminalFactory.getDefault();
      }

      if (verbose) {
        System.out.println(
            "# Using " + tf.getProvider().getClass().getCanonicalName() + " - " + tf.getProvider());
        if (System.getProperty(TerminalManager.lib_prop) != null) {
          System.out.println(
              "# " + TerminalManager.lib_prop + "=" + System.getProperty(TerminalManager.lib_prop));
        }
      }
      // Get all terminals
      terminals = tf.terminals();
    } catch (Exception e) {
      // XXX: we catch generic Exception here to avoid importing JNA.
      // Try to get a meaningful message
      String msg = TerminalManager.getExceptionMessage(e);
      if (msg == null) msg = e.getMessage();
      System.out.println("No readers: " + msg);
      System.exit(1);
    }

    // Terminals to work on
    List<CardTerminal> do_readers = new ArrayList<CardTerminal>();

    try {
      // List Terminals
      if (args.has(CMD_LIST)) {
        List<CardTerminal> terms = terminals.list();
        if (verbose) {
          System.out.println(
              "# Found " + terms.size() + " terminal" + (terms.size() == 1 ? "" : "s"));
        }
        if (terms.size() == 0) {
          System.err.println("No readers found");
          System.exit(1);
        }
        for (CardTerminal t : terms) {
          String vmd = " ";
          try (PinPadTerminal pp = new PinPadTerminal(t)) {
            pp.probe();
            // Verify, Modify, Display
            if (verbose) {
              vmd += "[";
              vmd += pp.canVerify() ? "V" : " ";
              vmd += pp.canModify() ? "M" : " ";
              vmd += pp.hasDisplay() ? "D" : " ";
              vmd += "] ";
            }
          } catch (CardException e) {
            if (verbose) {
              System.err.println("Could not probe PinPad: " + e.getMessage());
            }
          }

          System.out.println((t.isCardPresent() ? "[*]" : "[ ]") + vmd + t.getName());

          if (args.has(OPT_VERBOSE) && t.isCardPresent()) {
            Card c = t.connect("DIRECT");
            String atr = HexUtils.encodeHexString(c.getATR().getBytes()).toUpperCase();
            c.disconnect(false);
            System.out.println("          " + atr);
            if (args.has(OPT_WEB)) {
              String url = "http://smartcard-atr.appspot.com/parse?ATR=" + atr;
              if (Desktop.isDesktopSupported()) {
                Desktop.getDesktop().browse(new URI(url + "&from=apdu4j"));
              } else {
                System.out.println("          " + url);
              }
            }
          }
        }
      }

      // Select terminals to work on
      if (args.has(OPT_READER)) {
        String reader = (String) args.valueOf(OPT_READER);
        CardTerminal t = terminals.getTerminal(reader);
        if (t == null) {
          System.err.println("Reader \"" + reader + "\" not found.");
          System.exit(1);
        }
        do_readers = Arrays.asList(t);
      } else {
        do_readers = terminals.list(State.CARD_PRESENT);
        if (do_readers.size() > 1 && !args.hasArgument(OPT_ALL)) {
          System.err.println("More than one reader with a card found.");
          System.err.println("Run with --" + OPT_ALL + " to work with all found cards");
          System.exit(1);
        } else if (do_readers.size() == 0 && !args.has(CMD_LIST)) {
          // But if there is a single reader, wait for a card insertion
          List<CardTerminal> empty = terminals.list(State.CARD_ABSENT);
          if (empty.size() == 1 && args.has(OPT_WAIT)) {
            CardTerminal rdr = empty.get(0);
            System.out.println("Please enter a card into " + rdr.getName());
            if (!empty.get(0).waitForCardPresent(30000)) {
              System.out.println("Timeout.");
            } else {
              do_readers = Arrays.asList(rdr);
            }
          } else {
            System.err.println("No reader with a card found!");
            System.exit(1);
          }
        }
      }

    } catch (CardException e) {
      System.out.println("Could not list readers: " + TerminalManager.getExceptionMessage(e));
      e.printStackTrace();
    }

    for (CardTerminal t : do_readers) {
      work(t, args);
    }
  }
Esempio n. 17
0
  public String hashSignExternalTimestamp(String read, String write) throws Exception {
    Provider prov = entry.getProvider();
    PrivateKey key = entry.getPrivateKey();
    Certificate[] chain = entry.getCertificateChain();

    PdfReader reader = new PdfReader(read);
    int pageCount = reader.getNumberOfPages();

    File outputFile = new File(write);
    PdfStamper stp = PdfStamper.createSignature(reader, null, '\0', outputFile, true);

    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    sap.setProvider(prov.getName());
    sap.setReason(getReason());
    sap.setLocation(getLocation());
    sap.setContact(getContact());

    sap.setCrypto(null, chain, null, PdfSignatureAppearance.SELF_SIGNED);

    int[] coord = LoadImageAction.getImageXY();

    if (!LoadImageAction.posMatriz) { // Se for por coordenadas do sample
      coord[0] = LoadImageAction.getAssX();
      coord[1] = LoadImageAction.getAssY();
    }

    // Adicionar imagem ao PDF se for para utilizar
    if (!isSignatureVisible()) {
      sap.setLayer2Text("");
    } else {
      if (LoadImageAction.getFlagPDF()) {
        sap.setAcro6Layers(true);
        Image img = LoadImageAction.getAssImagePDF();

        if (LoadImageAction.getPagToSign() == -1)
          sap.setVisibleSignature(
              new Rectangle(
                  coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()),
              pageCount,
              null);
        else
          sap.setVisibleSignature(
              new Rectangle(
                  coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()),
              LoadImageAction.getPagToSign(),
              null);

        sap.setLayer2Text("\n\n(Doc. assinado digitalmente)");
        sap.setImage(img);
      } else {
        if (LoadImageAction.getPagToSign() == -1)
          sap.setVisibleSignature(
              new Rectangle(coord[0], coord[1], coord[0] + 150, coord[1] + 40), pageCount, null);
        else
          sap.setVisibleSignature(
              new Rectangle(coord[0], coord[1], coord[0] + 150, coord[1] + 40),
              LoadImageAction.getPagToSign(),
              null);

        sap.setLayer2Text(getSignatureText((X509Certificate) chain[0], sap.getSignDate()));
      }
    }

    PdfSignature dic =
        new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); // $NON-NLS-1$
    dic.setReason(sap.getReason());
    dic.setLocation(sap.getLocation());
    dic.setContact(sap.getContact());
    dic.setDate(new PdfDate(sap.getSignDate()));
    sap.setCryptoDictionary(dic);
    int contentEstimated = 15000;
    HashMap<Object, Object> exc = new HashMap<Object, Object>();
    exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
    sap.preClose(exc);

    PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", prov.getName(), false);
    InputStream data = sap.getRangeStream();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); // $NON-NLS-1$
    byte buf[] = new byte[8192];
    int n;
    while ((n = data.read(buf)) > 0) {
      messageDigest.update(buf, 0, n);
    }
    byte hash[] = messageDigest.digest();
    Calendar cal = Calendar.getInstance();
    byte[] ocsp = null;
    if (isUseOCSP() && chain.length >= 2) {
      String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
      if (url != null && url.length() > 0)
        ocsp =
            new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url)
                .getEncoded();
    }
    byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
    sgn.update(sh, 0, sh.length);
    TSAClient tsc = null;
    if (isUseTSA() && tsaLocation != null) tsc = new TSAClientBouncyCastle(tsaLocation);

    // o PIN/PASS dos certificados � pedido aqui
    byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);

    if (contentEstimated + 2 < encodedSig.length)
      throw new Exception("Not enough space"); // $NON-NLS-1$

    byte[] paddedSig = new byte[contentEstimated];
    System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
    PdfDictionary dic2 = new PdfDictionary();
    dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
    sap.close(dic2);

    deleteFile(read);
    return write;
  }
  /**
   * Inicializa un almac&eacute;n PKCS#11.
   *
   * @param pssCallBack Callback para la recuperaci&oacute;n de la contrase&ntilde;a del
   *     almac&eacute;n.
   * @param params Parametros adicionales para la configuraci&oacute;n del almac&eacute;n.
   * @return Array con los almacenes configurados.
   * @throws AOKeyStoreManagerException Cuando ocurre un error durante la inicializaci&oacute;n.
   * @throws IOException Cuando se indique una contrase&ntilde;a incorrecta para la apertura del
   *     almac&eacute;n.
   * @throws es.gob.afirma.keystores.main.common.MissingSunPKCS11Exception Si no se encuentra la
   *     biblioteca SunPKCS11
   */
  private List<KeyStore> initPKCS11(final PasswordCallback pssCallBack, final Object[] params)
      throws AOKeyStoreManagerException, IOException {
    // En el "params" debemos traer los parametros:
    // [0] -p11lib: Biblioteca PKCS#11, debe estar en el Path (Windows) o en el LD_LIBRARY_PATH
    // (UNIX, Linux, Mac OS X)
    // [1] -desc: Descripcion del token PKCS#11 (opcional)
    // [2] -slot: Numero de lector de tarjeta (Sistema Operativo) [OPCIONAL]

    // Anadimos el proveedor PKCS11 de Sun
    if (params == null || params.length < 2) {
      throw new IOException(
          "No se puede acceder al KeyStore PKCS#11 si no se especifica la biblioteca"); //$NON-NLS-1$
    }
    final String p11lib;
    if (params[0] != null) {
      p11lib = params[0].toString();
    } else {
      throw new IllegalArgumentException(
          "No se puede acceder al KeyStore PKCS#11 si se especifica una biblioteca nula"); //$NON-NLS-1$
    }

    // Numero de lector
    Integer slot = null;
    if (params.length >= 3 && params[2] instanceof Integer) {
      slot = (Integer) params[2];
    }

    // Agregamos un nombre a cada PKCS#11 para asegurarnos de no se
    // agregan mas de una vez como provider.
    // Si ya se cargo el PKCS#11 anteriormente, se volvera a instanciar.
    final String p11ProviderName = new File(p11lib).getName().replace('.', '_').replace(' ', '_');
    Provider p11Provider = Security.getProvider("SunPKCS11-" + p11ProviderName); // $NON-NLS-1$

    if (p11Provider == null) {

      Constructor<?> sunPKCS11Contructor;
      try {
        sunPKCS11Contructor =
            Class.forName("sun.security.pkcs11.SunPKCS11")
                .getConstructor(InputStream.class); // $NON-NLS-1$
      } catch (final Exception e) {
        throw new MissingSunPKCS11Exception(e);
      }

      final byte[] config =
          KeyStoreUtilities.createPKCS11ConfigFile(p11lib, p11ProviderName, slot).getBytes();
      try {
        p11Provider = (Provider) sunPKCS11Contructor.newInstance(new ByteArrayInputStream(config));
      } catch (final Exception e) {
        // El PKCS#11 del DNIe a veces falla a la primera pero va
        // correctamente a la segunda
        // asi que reintentamos una vez mas
        try {
          p11Provider =
              (Provider) sunPKCS11Contructor.newInstance(new ByteArrayInputStream(config));
        } catch (final Exception ex) {
          throw new AOKeyStoreManagerException(
              "No se ha podido instanciar el proveedor SunPKCS11 para la la biblioteca " + p11lib,
              ex); //$NON-NLS-1$
        }
      }
      Security.addProvider(p11Provider);
    } else {
      LOGGER.info(
          "El proveedor SunPKCS11 solicitado ya estaba instanciado, se reutilizara esa instancia: "
              + p11Provider.getName()); // $NON-NLS-1$
    }

    try {
      this.ks = KeyStore.getInstance(this.ksType.getProviderName(), p11Provider);
    } catch (final Exception e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen PKCS#11", e); // $NON-NLS-1$
    }

    try {
      this.ks.load(null, pssCallBack != null ? pssCallBack.getPassword() : null);
    } catch (final IOException e) {
      if (e.getCause() instanceof UnrecoverableKeyException
          || e.getCause() instanceof BadPaddingException) {
        throw new IOException("Contrasena invalida: " + e, e); // $NON-NLS-1$
      }
      throw new AOKeyStoreManagerException(
          "No se ha podido obtener el almacen PKCS#11 solicitado", e); // $NON-NLS-1$
    } catch (final CertificateException e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se han podido cargar los certificados del almacen PKCS#11 solicitado",
          e); //$NON-NLS-1$
    } catch (final NoSuchAlgorithmException e) {
      Security.removeProvider(p11Provider.getName());
      p11Provider = null;
      throw new AOKeyStoreManagerException(
          "No se ha podido verificar la integridad del almacen PKCS#11 solicitado",
          e); //$NON-NLS-1$
    }
    final List<KeyStore> ret = new ArrayList<KeyStore>(1);
    ret.add(this.ks);
    return ret;
  }
Esempio n. 19
0
  public CertificationAuthorities getRoots(AbstractTask task)
      throws GeneralSecurityException, IOException {

    CertificationAuthorities roots = null;
    boolean rootsOk = false;
    String error = null;

    try {

      CertificationAuthorities CNIPARoot = new CertificationAuthorities();
      try {
        CNIPARoot.addCertificateAuthority(CNIPARoot.getBytesFromPath(this.CNIPACACertFilePath));
      } catch (GeneralSecurityException e) {
        log(task, "Errore nell'inizializzazione della CA CNIPA: " + e);
      }

      X509Certificate cert = null;
      CertStore certs = null;

      CMSSignedData CNIPA_CMS = null;
      try {

        CNIPA_CMS = getCNIPA_CMS();

      } catch (FileNotFoundException ex) {
        log(task, "Errore nell'acquisizione del file: " + ex);
      }

      Provider p = new org.bouncycastle.jce.provider.BouncyCastleProvider();
      if (Security.getProvider(p.getName()) == null) Security.addProvider(p);

      try {
        certs = CNIPA_CMS.getCertificatesAndCRLs("Collection", "BC");
      } catch (CMSException ex2) {
        log(task, "Errore nel CMS delle RootCA");
      } catch (NoSuchProviderException ex2) {
        log(task, "Non esiste il provider del servizio");
      } catch (NoSuchAlgorithmException ex2) {
        log(task, "Errore nell'algoritmo");
      }

      if (certs != null) {
        SignerInformationStore signers = CNIPA_CMS.getSignerInfos();
        Collection c = signers.getSigners();

        System.out.println(c.size() + " signers found.");

        Iterator it = c.iterator();

        // ciclo tra tutti i firmatari
        int i = 0;
        while (it.hasNext()) {
          SignerInformation signer = (SignerInformation) it.next();
          Collection certCollection = null;
          try {
            certCollection = certs.getCertificates(signer.getSID());
          } catch (CertStoreException ex1) {
            log(task, "Errore nel CertStore");
          }

          if (certCollection.size() == 1) {

            // task.setStatus(++current,
            // "Verifica delle CA firmate dal CNIPA...");

            byte[] signerFingerprint =
                getCertFingerprint((X509Certificate) certCollection.toArray()[0]);

            System.out.println("Signer fingerprint: " + formatAsGUString(signerFingerprint, 2));

            if (Arrays.equals(signerFingerprint, this.userApprovedFingerprint)) {

              VerifyResult vr =
                  new VerifyResult(
                      (X509Certificate) certCollection.toArray()[0],
                      CNIPA_CMS,
                      CNIPARoot,
                      signer,
                      false);
              rootsOk = vr.getPassed();
              error = vr.getCRLerror();
            } else log(task, "Signer certs has wrong fingerprint!");
          } else log(task, "There is not exactly one certificate for this signer!");

          i++;
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (CMSException e) {
      e.printStackTrace();
    }

    if (rootsOk) {

      roots = new CertificationAuthorities(getCmsInputStream(this.CAFilePath), true);

    } else {

      log(task, "Verifica del file CNIPA delle root CA fallita!");
    }

    return roots;
  }
Esempio n. 20
0
  public void insertImageRubrica(PdfReader reader, int pageCount, String fileWrite) {
    int iniY = 841 - 10;
    int iniX = 595 - 10;

    try {

      // Verificar qual � a imagem para utilizar na rubrica
      Image img = null;
      if (LoadImageAction.rubimgSameass) img = LoadImageAction.getAssImagePDF();
      else img = LoadImageAction.getRubImagePDF();

      // Criar Modelo para as Rubricas
      ByteArrayOutputStream out = new ByteArrayOutputStream();

      PdfStamper stp1 = new PdfStamper(reader, out, '\3', true);
      PdfFormField sig = PdfFormField.createSignature(stp1.getWriter());

      if (LoadImageAction.posRubSame) {

        int[] coord = LoadImageAction.getImageXY();

        if (!LoadImageAction.posMatriz) { // Se for por coordenadas do sample
          coord[0] = LoadImageAction.getAssX();
          coord[1] = LoadImageAction.getAssY();
        }

        sig.setWidget(
            new Rectangle(
                coord[0], coord[1], coord[0] + img.getWidth(), coord[1] + img.getHeight()),
            null);
      } else {
        sig.setWidget(
            new Rectangle(iniX - img.getWidth(), iniY - img.getHeight(), iniX, iniY), null);
      }

      sig.setFlags(PdfAnnotation.FLAGS_PRINT);
      sig.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g"));
      sig.setFieldName("Assinaturas");
      sig.setPage(1);

      // Se a imagem da rubrica n for a mesma da assinatura n�o mete na ultima pag
      if (!LoadImageAction.rubimgSameass) pageCount = pageCount - 1;

      // Inserir em todas as paginas o Modelo
      for (int i = 1; i <= pageCount; i++) stp1.addAnnotation(sig, i);

      stp1.close();

      // Guardar/Ler PDF com modelos inseridos
      reader = new PdfReader(out.toByteArray());
      File outputFile = new File(fileWrite);

      // Preencher Modelo com Dados
      PdfStamper stp = PdfStamper.createSignature(reader, null, '\0', outputFile, true);

      PdfSignatureAppearance sap = stp.getSignatureAppearance();
      sap.setAcro6Layers(true);
      reader.close();
      sap.setVisibleSignature("Assinaturas");
      sap.setLayer2Text("\n\n(Doc. assinado digitalmente)");
      sap.setImage(img);
      PdfSignature dic =
          new PdfSignature(
              PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); // $NON-NLS-1$
      dic.setReason(sap.getReason());
      dic.setLocation(sap.getLocation());
      dic.setContact(sap.getContact());
      dic.setDate(new PdfDate(sap.getSignDate()));
      sap.setCryptoDictionary(dic);
      int contentEstimated = 15000;
      HashMap<Object, Object> exc = new HashMap<Object, Object>();
      exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
      sap.preClose(exc);

      Provider prov = entry.getProvider();
      PrivateKey key = entry.getPrivateKey();
      Certificate[] chain = entry.getCertificateChain();
      PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", prov.getName(), false); // $NON-NLS-1$
      InputStream data = sap.getRangeStream();
      MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); // $NON-NLS-1$
      byte buf[] = new byte[8192];
      int n;
      while ((n = data.read(buf)) > 0) {
        messageDigest.update(buf, 0, n);
      }
      byte hash[] = messageDigest.digest();
      Calendar cal = Calendar.getInstance();
      byte[] ocsp = null;

      if (isUseOCSP() && chain.length >= 2) {
        String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
        if (url != null && url.length() > 0)
          ocsp =
              new OcspClientBouncyCastle(
                      (X509Certificate) chain[0], (X509Certificate) chain[1], url)
                  .getEncoded();
      }
      byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
      sgn.update(sh, 0, sh.length);

      TSAClient tsc = null;
      if (isUseTSA() && tsaLocation != null) tsc = new TSAClientBouncyCastle(tsaLocation);
      byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);

      if (contentEstimated + 2 < encodedSig.length)
        throw new Exception("Not enough space"); // $NON-NLS-1$

      byte[] paddedSig = new byte[contentEstimated];
      PdfDictionary dic2 = new PdfDictionary();
      System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);
      dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));
      sap.close(dic2);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 protected void tearDown() throws Exception {
   super.tearDown();
   Security.removeProvider(support_TestProvider.getName());
 }
Esempio n. 22
0
  public static void main(String[] args) throws Exception {

    // Dynamically register the SunMSCAPI provider
    Security.addProvider(new sun.security.mscapi.SunMSCAPI());

    Provider p = Security.getProvider("SunMSCAPI");

    System.out.println("SunMSCAPI provider classname is " + p.getClass().getName());
    System.out.println("SunMSCAPI provider name is " + p.getName());
    System.out.println("SunMSCAPI provider version # is " + p.getVersion());
    System.out.println("SunMSCAPI provider info is " + p.getInfo());

    /*
     * Secure Random
     */
    SecureRandom random = SecureRandom.getInstance("Windows-PRNG", p);
    System.out.println("    Windows-PRNG is implemented by: " + random.getClass().getName());

    /*
     * Key Store
     */
    KeyStore keystore = KeyStore.getInstance("Windows-MY", p);
    System.out.println("    Windows-MY is implemented by: " + keystore.getClass().getName());

    keystore = KeyStore.getInstance("Windows-ROOT", p);
    System.out.println("    Windows-ROOT is implemented by: " + keystore.getClass().getName());

    /*
     * Signature
     */
    Signature signature = Signature.getInstance("SHA1withRSA", p);
    System.out.println("    SHA1withRSA is implemented by: " + signature.getClass().getName());

    signature = Signature.getInstance("MD5withRSA", p);
    System.out.println("    MD5withRSA is implemented by: " + signature.getClass().getName());

    signature = Signature.getInstance("MD2withRSA", p);
    System.out.println("    MD2withRSA is implemented by: " + signature.getClass().getName());

    /*
     * Key Pair Generator
     */
    KeyPairGenerator keypairGenerator = KeyPairGenerator.getInstance("RSA", p);
    System.out.println("    RSA is implemented by: " + keypairGenerator.getClass().getName());

    /*
     * Cipher
     */
    Cipher cipher = null;

    try {
      cipher = Cipher.getInstance("RSA", p);
      System.out.println("    RSA is implemented by: " + cipher.getClass().getName());

      cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", p);
      System.out.println(
          "    RSA/ECB/PKCS1Padding is implemented by: " + cipher.getClass().getName());

    } catch (GeneralSecurityException e) {
      System.out.println("Cipher not supported by provider, skipping...");
    }
  }
Esempio n. 23
0
  private byte[] getFingerprint() {

    byte[] fingerprint = null;
    byte[] serial = null;

    CertStore certs = null;
    CMSSignedData CNIPA_CMS = null;
    try {

      CNIPA_CMS = getCNIPA_CMS();

    } catch (FileNotFoundException ex) {
      System.out.println("Errore nella lettura del file delle RootCA: " + ex);
    } catch (CMSException e) {
      System.out.println("Errore nel CMS delle RootCA: " + e);
    }

    Provider p = new org.bouncycastle.jce.provider.BouncyCastleProvider();
    if (Security.getProvider(p.getName()) == null) Security.addProvider(p);

    try {
      certs = CNIPA_CMS.getCertificatesAndCRLs("Collection", "BC");
    } catch (CMSException ex2) {
      System.out.println("Errore nel CMS delle RootCA");
    } catch (NoSuchProviderException ex2) {
      System.out.println("Non esiste il provider del servizio");
    } catch (NoSuchAlgorithmException ex2) {
      System.out.println("Errore nell'algoritmo");
    }

    if (certs == null) System.out.println("No certs for CNIPA signature!");
    else {
      SignerInformationStore signers = CNIPA_CMS.getSignerInfos();
      Collection c = signers.getSigners();
      if (c.size() != 1) {
        System.out.println("There is not exactly one signer!");
      } else {

        Iterator it = c.iterator();

        if (it.hasNext()) {
          SignerInformation signer = (SignerInformation) it.next();
          Collection certCollection = null;
          try {
            certCollection = certs.getCertificates(signer.getSID());

            if (certCollection.size() == 1) {
              X509Certificate cnipaSignerCert = (X509Certificate) certCollection.toArray()[0];
              fingerprint = getCertFingerprint(cnipaSignerCert);
              serial = cnipaSignerCert.getSerialNumber().toByteArray();
            } else System.out.println("There is not exactly one certificate for this signer!");

          } catch (CertStoreException ex1) {
            System.out.println("Errore nel CertStore");
          }
        }
      }
    }

    if (JOptionPane.YES_OPTION
        == JOptionPane.showConfirmDialog(
            null,
            conf.getAcceptCAmsg()
                + "Seriale: "
                + ((serial == null)
                    ? "impossibile calcolare il numero seriale"
                    : formatAsGUString(serial, 1))
                + "\n"
                + "Impronta SHA1: "
                + ((fingerprint == null)
                    ? "impossibile calcolare l'impronta"
                    : formatAsGUString(fingerprint, 2))
                + "\n",
            "Impronta Certificato Presidente CNIPA",
            JOptionPane.YES_NO_OPTION)) return fingerprint;

    return null;
  }
Esempio n. 24
0
 /**
  * Private/Public Keys for a certificate
  *
  * @return
  * @throws NoSuchProviderException
  * @throws NoSuchAlgorithmException
  */
 private KeyPair newKeyPair() throws NoSuchProviderException, NoSuchAlgorithmException {
   KeyPairGenerator keyPairGenerator =
       KeyPairGenerator.getInstance("RSA", bouncyCastleProvider.getName());
   keyPairGenerator.initialize(2048, secureRandom);
   return keyPairGenerator.generateKeyPair();
 }
  /**
   * Replacement for JCA/JCE's {@link javax.crypto.Cipher#getInstance}. The original method only
   * accepts JCE providers from signed jars, which prevents us from bundling our cryptography
   * provider Bouncy Caster with the application.
   *
   * @param transformation the transformation to find an implementation for
   */
  public static Cipher getCipher(final String transformation) {
    try {
      /* Split the transformation into algorithm, mode and padding */

      final Matcher transformation_matcher =
          s_transformation_pattern.matcher(transformation.toUpperCase());
      if (!transformation_matcher.matches())
        throw new RuntimeException("Transformation " + transformation + " is invalid");

      final String algorithm = transformation_matcher.group(1);
      final String mode = transformation_matcher.group(3);
      final String padding = transformation_matcher.group(4);
      final boolean isBareAlgorithm = (mode == null) && (padding == null);

      /* Build the property values we need to search for. */

      final String algorithmModePadding =
          !isBareAlgorithm ? algorithm + "/" + mode + "/" + padding : null;
      final String algorithmMode = !isBareAlgorithm ? algorithm + "/" + mode : null;
      final String algorithmPadding = !isBareAlgorithm ? algorithm + "//" + padding : null;

      /* Search the provider for implementations. We ask for more specific (i.e matching
       * the requested mode and or padding) implementation first, then fall back to more
       * generals ones which we then must configure for the mode and padding.
       */

      final CipherSpi cipherSpi;

      if (!isBareAlgorithm && (resolveProperty(Provider, "Cipher", algorithmModePadding) != null)) {
        @SuppressWarnings("unchecked")
        final Class<? extends CipherSpi> cipherSpiClass =
            (Class<? extends CipherSpi>)
                Class.forName(resolveProperty(Provider, "Cipher", algorithmModePadding));
        cipherSpi = cipherSpiClass.newInstance();
      } else if (!isBareAlgorithm && (resolveProperty(Provider, "Cipher", algorithmMode) != null)) {
        @SuppressWarnings("unchecked")
        final Class<? extends CipherSpi> cipherSpiClass =
            (Class<? extends CipherSpi>)
                Class.forName(resolveProperty(Provider, "Cipher", algorithmMode));
        cipherSpi = cipherSpiClass.newInstance();
        if (!isBareAlgorithm) cipherSpiSetPadding(cipherSpi, padding);
      } else if (!isBareAlgorithm
          && (resolveProperty(Provider, "Cipher", algorithmPadding) != null)) {
        @SuppressWarnings("unchecked")
        final Class<? extends CipherSpi> cipherSpiClass =
            (Class<? extends CipherSpi>)
                Class.forName(resolveProperty(Provider, "Cipher", algorithmPadding));
        cipherSpi = cipherSpiClass.newInstance();
        if (!isBareAlgorithm) cipherSpiSetMode(cipherSpi, mode);
      } else if (resolveProperty(Provider, "Cipher", algorithm) != null) {
        @SuppressWarnings("unchecked")
        final Class<? extends CipherSpi> cipherSpiClass =
            (Class<? extends CipherSpi>)
                Class.forName(resolveProperty(Provider, "Cipher", algorithm));
        cipherSpi = cipherSpiClass.newInstance();
        if (!isBareAlgorithm) {
          cipherSpiSetMode(cipherSpi, mode);
          cipherSpiSetPadding(cipherSpi, padding);
        }
      } else {
        throw new RuntimeException(
            "Provider "
                + Provider.getName()
                + " ("
                + Provider.getClass()
                + ") does not implement "
                + transformation);
      }

      /* Create a {@link javax.crypto.Cipher} instance from the {@link javax.crypto.CipherSpi} the provider gave us */

      s_logger.info("Using SPI " + cipherSpi.getClass() + " for " + transformation);
      return getCipher(cipherSpi, transformation.toUpperCase());
    } catch (final RuntimeException e) {
      throw e;
    } catch (final Error e) {
      throw e;
    } catch (final Throwable e) {
      throw new RuntimeException(
          "Provider "
              + Provider.getName()
              + " ("
              + Provider.getClass()
              + ") failed to instanciate "
              + transformation,
          e);
    }
  }