public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    PrivateKey privateKey = null;
    Certificate[] certs = null;
    while (uploadedFilesIterator.hasNext()) {
      FileItem fileItem = uploadedFilesIterator.next();
      if (!fileItem.isFormField()) {
        if ("keyFile".equals(fileItem.getFieldName())) {
          KeyFactory kf = KeyFactory.getInstance("RSA");
          privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get()));
        }
        if ("certFile".equals(fileItem.getFieldName())) {
          CertificateFactory cf = CertificateFactory.getInstance("X.509");
          certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
        }
      }
    }

    if (privateKey == null || certs == null) {
      throw new WebApplicationException(
          Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs);
    save();
  }
Exemplo n.º 2
0
  @SuppressWarnings("unchecked")
  private X509Certificate[] parseX509CertificateChain(InputStream is) throws CertificateException {
    X509Certificate[] certificateChain;
    CertificateFactory cf;
    Collection certificateChainCollection;
    Iterator chainIterator;

    certificateChain = null;
    cf = null;
    certificateChainCollection = null;
    chainIterator = null;

    // Instantiate X509 certificate factory
    cf = CertificateFactory.getInstance("X509");

    // Parse X509 certificate chain
    certificateChainCollection = cf.generateCertificates(is);

    // Instantiate array to hold X509 certificate chain
    certificateChain = new X509Certificate[certificateChainCollection.size()];

    // Get iterator over X509 certificate chain
    chainIterator = certificateChainCollection.iterator();

    // Work through each X509 certificate in certificate chain collection
    for (int i = 0; i < certificateChain.length; i++) {
      // Copy next X509 certificate from collection to array
      certificateChain[i] = (X509Certificate) chainIterator.next();
    }

    return certificateChain;
  }
Exemplo n.º 3
0
 private void loadCert(String certFilename) throws CertificateException, IOException {
   InputStream is = load(certFilename);
   Collection<? extends Certificate> c = factory.generateCertificates(is);
   serverChain = new Certificate[c.size()];
   int i = 0;
   for (Certificate crt : c) {
     serverChain[i++] = crt;
   }
 }
Exemplo n.º 4
0
  /**
   * Récupère une liste de certificats à partir d'un fichier .cer.
   *
   * @param aCertStream
   * @return
   * @throws GeneralSecurityException
   */
  private static Collection<X509Certificate> chargerCertificatsX509(
      InputStream aCertStream, String typeCert, String provider) throws GeneralSecurityException {
    // création d'une fabrique de certificat X509
    CertificateFactory cf = CertificateFactory.getInstance(typeCert, provider);

    // chargement du certificat
    Collection<X509Certificate> certs =
        (Collection<X509Certificate>) cf.generateCertificates(aCertStream);
    return certs;
  }
  public static void main(String[] args) throws Exception {
    /*
     * create an empty SignedData content type in ASN.1
     * as defined in PKCS#7
     */
    byte[] b = {
      0x30,
      0x23,
      /* contentInfo ::= signedData */
      0x06,
      0x09,
      0x2A,
      (byte) 0x86,
      0x48,
      (byte) 0x86,
      (byte) 0xF7,
      0x0D,
      0x01,
      0x07,
      0x02,
      0x00,
      0x16,
      0x30,
      0x14, /* SignedData */
      0x02,
      0x01,
      0x01, /* version */
      0x31,
      0x00, /* digestAlgorithms */
      0x30,
      0x0B, /* contentInfo ::= data */
      0x06,
      0x09,
      0x2A,
      (byte) 0x86,
      0x48,
      (byte) 0x86,
      (byte) 0xF7,
      0x0D,
      0x01,
      0x07,
      0x01,
      /* certificates are absent */
      0x31,
      0x00 /* signerInfos */
    };

    CertificateFactory cf = CertificateFactory.getInstance("X509", "SUN");
    Collection c = cf.generateCertificates(new ByteArrayInputStream(b));
    if (!c.isEmpty())
      throw new Exception(
          "CertificateFactory.generateCertificates() " + "did not return an empty Collection");
  }
 public static CertPathEntry decode(DataInputStream in) throws IOException {
   CertPathEntry entry = new CertPathEntry();
   entry.properties.decode(in);
   entry.makeCreationDate();
   int len = in.readInt();
   MeteredInputStream in2 = new MeteredInputStream(in, len);
   try {
     CertificateFactory fact = CertificateFactory.getInstance("X.509");
     entry.path = (Certificate[]) fact.generateCertificates(in2).toArray(new Certificate[0]);
   } catch (CertificateException ce) {
     throw new MalformedKeyringException(ce.toString());
   }
   return entry;
 }
Exemplo n.º 7
0
 public X509Certificate[] getCertificateChain(String alias) {
   if (cert == null && certfile != null) // If certfile is null, we do not load the certificate
   { // The certificate must be loaded
     CertificateFactory cf;
     try {
       cf = CertificateFactory.getInstance("X.509");
     } catch (
         CertificateException
             ex) { // For some strange reason it throws CertificateException instead of
                   // NoSuchAlgorithmException...
       error =
           new PSQLException(
               GT.tr(
                   "Could not find a java cryptographic algorithm: X.509 CertificateFactory not available.",
                   null),
               PSQLState.CONNECTION_FAILURE,
               ex);
       return null;
     }
     Collection certs;
     try {
       certs = cf.generateCertificates(new FileInputStream(certfile));
     } catch (FileNotFoundException ioex) {
       if (!defaultfile) { // It is not an error if there is no file at the default location
         error =
             new PSQLException(
                 GT.tr("Could not open SSL certificate file {0}.", new Object[] {certfile}),
                 PSQLState.CONNECTION_FAILURE,
                 ioex);
       }
       return null;
     } catch (CertificateException gsex) {
       error =
           new PSQLException(
               GT.tr(
                   "Loading the SSL certificate {0} into a KeyManager failed.",
                   new Object[] {certfile}),
               PSQLState.CONNECTION_FAILURE,
               gsex);
       return null;
     }
     cert = (X509Certificate[]) certs.toArray(new X509Certificate[certs.size()]);
   }
   return cert;
 }
Exemplo n.º 8
0
  /**
   * Decode a {@link CertPath}.
   *
   * @param certificateBytes the byte[] to decode from.
   * @return a {@link CertPath}
   * @throws UaException if decoding the {@link CertPath} fails.
   */
  public static List<X509Certificate> decodeCertificates(byte[] certificateBytes)
      throws UaException {
    Preconditions.checkNotNull(certificateBytes, "certificateBytes cannot be null");

    CertificateFactory factory;

    try {
      factory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
      throw new UaException(StatusCodes.Bad_InternalError, e);
    }

    try {
      Collection<? extends Certificate> certificates =
          factory.generateCertificates(new ByteArrayInputStream(certificateBytes));

      return certificates.stream().map(X509Certificate.class::cast).collect(Collectors.toList());
    } catch (CertificateException e) {
      throw new UaException(StatusCodes.Bad_CertificateInvalid, e);
    }
  }
Exemplo n.º 9
0
  /**
   * Apply SSL related settings to httpClient according to the current values of verifyingSsl and
   * sslCaCert.
   */
  private void applySslSettings() {
    try {
      KeyManager[] keyManagers = null;
      TrustManager[] trustManagers = null;
      HostnameVerifier hostnameVerifier = null;
      if (!verifyingSsl) {
        TrustManager trustAll =
            new X509TrustManager() {
              @Override
              public void checkClientTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              @Override
              public void checkServerTrusted(X509Certificate[] chain, String authType)
                  throws CertificateException {}

              @Override
              public X509Certificate[] getAcceptedIssuers() {
                return null;
              }
            };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        trustManagers = new TrustManager[] {trustAll};
        hostnameVerifier =
            new HostnameVerifier() {
              @Override
              public boolean verify(String hostname, SSLSession session) {
                return true;
              }
            };
      } else if (sslCaCert != null) {
        char[] password = null; // Any password will work.
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certificates =
            certificateFactory.generateCertificates(sslCaCert);
        if (certificates.isEmpty()) {
          throw new IllegalArgumentException("expected non-empty set of trusted certificates");
        }
        KeyStore caKeyStore = newEmptyKeyStore(password);
        int index = 0;
        for (Certificate certificate : certificates) {
          String certificateAlias = "ca" + Integer.toString(index++);
          caKeyStore.setCertificateEntry(certificateAlias, certificate);
        }
        TrustManagerFactory trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(caKeyStore);
        trustManagers = trustManagerFactory.getTrustManagers();
      }

      if (keyManagers != null || trustManagers != null) {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, new SecureRandom());
        httpClient.setSslSocketFactory(sslContext.getSocketFactory());
      } else {
        httpClient.setSslSocketFactory(null);
      }
      httpClient.setHostnameVerifier(hostnameVerifier);
    } catch (GeneralSecurityException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 10
0
 /**
  * Reads X509Certificate object from given base64 data.
  *
  * @param base64data the certificate in base64
  * @return the collection of read certificates
  * @throws Exception if any errors occur
  */
 @SuppressWarnings("unchecked")
 public static Collection<X509Certificate> readCertificates(String base64data) throws Exception {
   try (InputStream is = new ByteArrayInputStream(decodeBase64(base64data))) {
     return (Collection<X509Certificate>) CERT_FACTORY.generateCertificates(is);
   }
 }