Ejemplo n.º 1
0
  /**
   * Creates trust managers using the receiver's trust store configuration.
   *
   * @param context context for status messages
   * @return an array of trust managers or {@code null} if no trust store configuration was provided
   * @throws NoSuchProviderException if a provider specified for one of the trust manager components
   *     is not known to the platform
   * @throws NoSuchAlgorithmException if an algorithm specified for one of the trust manager
   *     components is not known to the relevant provider
   * @throws KeyStoreException if an error occurs in reading a key store containing trust anchors
   */
  private TrustManager[] createTrustManagers(ContextAware context)
      throws NoSuchProviderException, NoSuchAlgorithmException, KeyStoreException {

    if (getTrustStore() == null) return null;

    KeyStore trustStore = getTrustStore().createKeyStore();
    context.addInfo(
        "trust store of type '"
            + trustStore.getType()
            + "' provider '"
            + trustStore.getProvider()
            + "': "
            + getTrustStore().getLocation());

    TrustManagerFactory tmf = getTrustManagerFactory().createTrustManagerFactory();
    context.addInfo(
        "trust manager algorithm '"
            + tmf.getAlgorithm()
            + "' provider '"
            + tmf.getProvider()
            + "'");

    tmf.init(trustStore);
    return tmf.getTrustManagers();
  }
Ejemplo n.º 2
0
  @SuppressWarnings("unchecked")
  private static void printKeyStoreInfo(KeyStore keystore) throws KeyStoreException {
    log.debug("Provider : " + keystore.getProvider().getName());
    log.debug("Type : " + keystore.getType());
    log.debug("Size : " + keystore.size());

    Enumeration en = keystore.aliases();
    while (en.hasMoreElements()) {
      System.out.println("Alias: " + en.nextElement());
    }
  }
  protected CamelContext createPropertiesPlaceholderAwareContext() throws Exception {
    Properties supplementalProperties = new Properties();

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    TrustManagerFactory tmf =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    SecureRandom sr = null;
    try {
      sr = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
      // Ignore
    }

    SSLContext sslc = SSLContext.getInstance("TLS");
    sslc.init(null, null, null);
    SSLSocket socket = (SSLSocket) sslc.getSocketFactory().createSocket();

    supplementalProperties.setProperty("keyStoreParameters.type", KeyStore.getDefaultType());
    supplementalProperties.setProperty("keyStoreParameters.provider", ks.getProvider().getName());

    supplementalProperties.setProperty(
        "keyManagersParameters.algorithm", KeyManagerFactory.getDefaultAlgorithm());
    supplementalProperties.setProperty(
        "keyManagersParameters.provider", kmf.getProvider().getName());

    supplementalProperties.setProperty(
        "trustManagersParameters.algorithm", TrustManagerFactory.getDefaultAlgorithm());
    supplementalProperties.setProperty(
        "trustManagersParameters.provider", tmf.getProvider().getName());

    if (sr != null) {
      supplementalProperties.setProperty("secureRandomParameters.algorithm", "SHA1PRNG");
      supplementalProperties.setProperty(
          "secureRandomParameters.provider", sr.getProvider().getName());
    }

    supplementalProperties.setProperty(
        "sslContextParameters.provider", sslc.getProvider().getName());
    supplementalProperties.setProperty("cipherSuite.0", socket.getSupportedCipherSuites()[0]);

    // Have to skip this guy because he doesn't work with TLS as the SSLContext protocol
    String ssp = "";
    for (String protocol : socket.getSupportedProtocols()) {
      if (!"SSLv2Hello".equals(protocol)) {
        ssp = protocol;
        break;
      }
    }
    supplementalProperties.setProperty("secureSocketProtocol.0", ssp);

    return this.createPropertiesPlaceholderAwareContext(supplementalProperties);
  }
Ejemplo n.º 4
0
  protected void execute() throws CertificateException, IOException {
    KeyStore keyStore = getKeyStore();
    if (keyStore == null) {
      throw new IOException("No se pudo obtener almacen de firma.");
    }
    String alias = getAlias(keyStore);

    X509Certificate certificate = null;
    try {
      certificate = (X509Certificate) keyStore.getCertificate(alias);
      if (certificate == null) {
        throw new IOException("No existe ningún certificado para firmar.");
      }
    } catch (KeyStoreException e1) {
      throw new IOException("Error: " + e1.getMessage());
    }

    PrivateKey privateKey = null;
    KeyStore tmpKs = keyStore;

    try {
      privateKey = (PrivateKey) tmpKs.getKey(alias, this.passSignature.toCharArray());
    } catch (UnrecoverableKeyException e) {
      throw new IOException("No existe clave privada para firmar.");
    } catch (KeyStoreException e) {
      throw new IOException("No existe clave privada para firmar.");
    } catch (NoSuchAlgorithmException e) {
      throw new IOException("No existe clave privada para firmar.");
    }

    Provider provider = keyStore.getProvider();
    DataToSign dataToSign = createDataToSign();
    FirmaXML firma = new FirmaXML();
    Document docSigned = null;

    try {
      Object[] res = firma.signFile(certificate, dataToSign, privateKey, provider);
      docSigned = (Document) res[0];
    } catch (Exception ex) {
      throw new IOException("Error realizando la firma: " + ex.getMessage());
    }
    String filePath = getPathOut() + File.separatorChar + getSignatureFileName();

    saveDocumenteDisk(docSigned, filePath);
  }
Ejemplo n.º 5
0
  /**
   * Creates key managers using the receiver's key store configuration.
   *
   * @param context context for status messages
   * @return an array of key managers or {@code null} if no key store configuration was provided
   * @throws NoSuchProviderException if a provider specified for one of the key manager components
   *     is not known to the platform
   * @throws NoSuchAlgorithmException if an algorithm specified for one of the key manager
   *     components is not known to the relevant provider
   * @throws KeyStoreException if an error occurs in reading a key store
   */
  private KeyManager[] createKeyManagers(ContextAware context)
      throws NoSuchProviderException, NoSuchAlgorithmException, UnrecoverableKeyException,
          KeyStoreException {

    if (getKeyStore() == null) return null;

    KeyStore keyStore = getKeyStore().createKeyStore();
    context.addInfo(
        "key store of type '"
            + keyStore.getType()
            + "' provider '"
            + keyStore.getProvider()
            + "': "
            + getKeyStore().getLocation());

    KeyManagerFactory kmf = getKeyManagerFactory().createKeyManagerFactory();
    context.addInfo(
        "key manager algorithm '" + kmf.getAlgorithm() + "' provider '" + kmf.getProvider() + "'");

    char[] passphrase = getKeyStore().getPassword().toCharArray();
    kmf.init(keyStore, passphrase);
    return kmf.getKeyManagers();
  }
Ejemplo n.º 6
0
  public void runTest(String provider) throws Exception {

    // load private key
    // all keystore types should support private keys
    KeySpec spec =
        new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(PRIVATE_KEY_PKCS8_BASE64));
    PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);

    // load x509 certificate
    Certificate cert;
    try (InputStream is =
        new BufferedInputStream(new ByteArrayInputStream(CERTIFICATE.getBytes()))) {
      cert = CertificateFactory.getInstance("X.509").generateCertificate(is);
    }

    int numEntries = 5;
    String type = null;
    for (int i = 0; i < PROVIDERS.length; i++) {
      if (provider.compareTo(PROVIDERS[i]) == 0) {
        type = KS_Type[i];
        break;
      }
    }

    System.out.printf("Test %s provider and %s keystore%n", provider, type);
    KeyStore ks = KeyStore.getInstance(type, provider);
    KeyStore ks2 = KeyStore.getInstance(type, ks.getProvider().getName());

    // create an empty key store
    ks.load(null, null);

    // store the secret keys
    for (int j = 0; j < numEntries; j++) {
      ks.setKeyEntry(ALIAS_HEAD + j, privateKey, PASSWDK, new Certificate[] {cert});
    }

    // initialize the 2nd key store object with the 1st one
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ks.store(baos, PASSWDK);
    byte[] bArr = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(bArr);
    ks2.load(bais, null);

    // check 2nd key store type
    checkType(ks2, type);
    // check the existing aliases for the 2nd key store
    checkAlias(ks2, numEntries);

    // compare the creation date of the 2 key stores for all aliases
    compareCreationDate(ks, ks2, numEntries);
    // remove the last entry from the 2nd key store
    numEntries--;
    ks2.deleteEntry(ALIAS_HEAD + numEntries);

    // re-initialize the 1st key store with the 2nd key store
    baos.reset();
    ks2.store(baos, PASSWD2);
    bais = new ByteArrayInputStream(baos.toByteArray());
    try {
      // expect an exception since the password is incorrect
      ks.load(bais, PASSWDK);
      throw new RuntimeException("ERROR: passed the loading with incorrect password");
    } catch (IOException ex) {
      System.out.println("Expected exception: " + ex);
      if (!causedBy(ex, UnrecoverableKeyException.class)) {
        ex.printStackTrace(System.out);
        throw new RuntimeException("Unexpected cause");
      }
      System.out.println("Expected cause: " + UnrecoverableKeyException.class.getName());

      bais.reset();
      ks.load(bais, PASSWD2);
      bais.reset();
      ks.load(bais, null);
    }

    // check key store type
    checkType(ks, type);

    // check the existing aliases
    checkAlias(ks, numEntries);

    // compare the creation date of the 2 key stores for all aliases
    compareCreationDate(ks, ks2, numEntries);
  }
Ejemplo n.º 7
0
  private void readTest(String inKeyStore) throws Exception {

    KeyStore inputKeyStore;

    // Initialize KeyStore
    String dir = System.getProperty("test.src", ".");
    String keystorePath = dir + File.separator + "certs" + File.separator + "readP12";
    inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE);
    // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
    // first.
    byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
    ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64.getMimeDecoder().decode(input));
    inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
    out.println("Initialize KeyStore : " + inKeyStore + " success");

    out.println("getProvider : " + inputKeyStore.getProvider());
    out.println("getType : " + inputKeyStore.getType());
    out.println("getDefaultType : " + KeyStore.getDefaultType());

    int idx = 0;
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
      alias = e.nextElement();
      out.println("Alias " + idx + " : " + alias);
      if (inputKeyStore.containsAlias(alias) == false) {
        throw new RuntimeException("Alias not found");
      }

      out.println("getCreationDate : " + inputKeyStore.getCreationDate(alias));

      X509Certificate cert = (X509Certificate) inputKeyStore.getCertificate(alias);
      out.println("getCertificate : " + cert.getSubjectDN());
      String retAlias = inputKeyStore.getCertificateAlias(cert);
      if (!retAlias.equals(alias)) {
        throw new RuntimeException("Alias mismatch");
      }
      out.println("getCertificateAlias : " + retAlias);

      Certificate[] certs = inputKeyStore.getCertificateChain(alias);
      for (int i = 0; i < certs.length; i++) {
        out.println(
            "getCertificateChain " + i + " : " + ((X509Certificate) certs[i]).getSubjectDN());
      }

      boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
      // test KeyStore only contain key pair entries.
      if (isCertEntry == true) {
        throw new RuntimeException(
            "inputKeystore should not be certEntry because test keystore only contain key pair entries.");
      }

      boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
      if (isKeyEntry) {
        Key key = inputKeyStore.getKey(alias, IN_STORE_PASS.toCharArray());
        out.println("Key : " + key.toString());
      } else {
        throw new RuntimeException("Entry type unknown\n");
      }
      idx++;
    }

    int size = inputKeyStore.size();
    if (idx != size) {
      throw new RuntimeException("Size not match");
    }
  }
 public Provider getProvider() {
   return _mscapi.getProvider();
 }