예제 #1
0
 public static String pemEncodeJcaObject(Object object) throws IOException {
   StringWriter writer = new StringWriter();
   try (PemWriter pemWriter = new PemWriter(writer)) {
     pemWriter.writeObject(new JcaMiscPEMGenerator(object));
   }
   return writer.toString();
 }
예제 #2
0
 @DSGenerator(
     tool_name = "Doppelganger",
     tool_version = "2.0",
     generated_on = "2013-12-30 13:00:33.155 -0500",
     hash_original_method = "E0AF395E658580FE02EB9102C3B67CCE",
     hash_generated_method = "E3D2FAF639E209883C0A5DF5BE9B142A")
 public void writeObject(PemObjectGenerator obj) throws IOException {
   super.writeObject(obj);
 }
예제 #3
0
  /**
   * Returns the encoded form of this certification path, using the specified encoding.
   *
   * @param encoding the name of the encoding to use
   * @return the encoded bytes
   * @exception java.security.cert.CertificateEncodingException if an encoding error occurs or the
   *     encoding requested is not supported
   */
  public byte[] getEncoded(String encoding) throws CertificateEncodingException {
    if (encoding.equalsIgnoreCase("PkiPath")) {
      ASN1EncodableVector v = new ASN1EncodableVector();

      ListIterator iter = certificates.listIterator(certificates.size());
      while (iter.hasPrevious()) {
        v.add(toASN1Object((X509Certificate) iter.previous()));
      }

      return toDEREncoded(new DERSequence(v));
    } else if (encoding.equalsIgnoreCase("PKCS7")) {
      ContentInfo encInfo = new ContentInfo(PKCSObjectIdentifiers.data, null);

      ASN1EncodableVector v = new ASN1EncodableVector();
      for (int i = 0; i != certificates.size(); i++) {
        v.add(toASN1Object((X509Certificate) certificates.get(i)));
      }

      SignedData sd =
          new SignedData(
              new ASN1Integer(1), new DERSet(), encInfo, new DERSet(v), null, new DERSet());

      return toDEREncoded(new ContentInfo(PKCSObjectIdentifiers.signedData, sd));
    } else if (encoding.equalsIgnoreCase("PEM")) {
      ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      PemWriter pWrt = new PemWriter(new OutputStreamWriter(bOut));

      try {
        for (int i = 0; i != certificates.size(); i++) {
          pWrt.writeObject(
              new PemObject("CERTIFICATE", ((X509Certificate) certificates.get(i)).getEncoded()));
        }

        pWrt.close();
      } catch (Exception e) {
        throw new CertificateEncodingException("can't encode certificate for PEM encoded path");
      }

      return bOut.toByteArray();
    } else {
      throw new CertificateEncodingException("unsupported encoding: " + encoding);
    }
  }
 @Security.Authenticated(SignedIn.class)
 public Result generateKey(String applicationId) throws IOException {
   Logger.info(String.format("Generating new key pair for %s", applicationId));
   KeyPair keyPair = keyPairGenerator.genKeyPair();
   Application app = Application.find.byId(applicationId);
   app.key = keyPair.getPublic().getEncoded();
   app.save();
   String filename = "privatekey-" + applicationId + ".pem";
   String filepath = "generated_keys/" + filename;
   File pemfile = new File(filepath);
   pemfile.getParentFile().mkdirs();
   PemObject pemObject = new PemObject(PEM_FILE_HEADER, keyPair.getPrivate().getEncoded());
   PemWriter writer = new PemWriter(new FileWriter(pemfile));
   writer.writeObject(pemObject);
   writer.flush();
   writer.close();
   response().setContentType("application/x-download");
   response().setHeader("Content-disposition", "attachment; filename=" + filename);
   return ok(pemfile);
 }
예제 #5
0
 @DSGenerator(
     tool_name = "Doppelganger",
     tool_version = "2.0",
     generated_on = "2013-12-30 13:00:33.157 -0500",
     hash_original_method = "FE40F27E2DA82EBBE9E1DFDF41871C25",
     hash_generated_method = "5958F652D3CAD7EAE6B4AE73C8917183")
 public void writeObject(Object obj, String algorithm, char[] password, SecureRandom random)
     throws IOException {
   try {
     super.writeObject(new MiscPEMGenerator(obj, algorithm, password, random, provider));
   } catch (NoSuchProviderException e) {
     throw new EncryptionException(e.getMessage(), e);
   }
 }
예제 #6
0
  @DSGenerator(
      tool_name = "Doppelganger",
      tool_version = "2.0",
      generated_on = "2013-12-30 13:00:33.152 -0500",
      hash_original_method = "996091F5D25AD49D59450216DEC51F49",
      hash_generated_method = "7CB893726A0A5BBC7E264E409C979B5E")
  public void writeObject(Object obj) throws IOException {
    try {
      super.writeObject(new MiscPEMGenerator(obj));
    } catch (PemGenerationException e) {
      if (e.getCause() instanceof IOException) {
        throw (IOException) e.getCause();
      }

      throw e;
    }
  }
예제 #7
0
  public void createNifiKeystoresAndTrustStores(StandaloneConfig standaloneConfig)
      throws GeneralSecurityException, IOException {
    File baseDir = standaloneConfig.getBaseDir();
    if (!baseDir.exists() && !baseDir.mkdirs()) {
      throw new IOException(baseDir + " doesn't exist and unable to create it.");
    }

    if (!baseDir.isDirectory()) {
      throw new IOException("Expected directory to output to");
    }

    String signingAlgorithm = standaloneConfig.getSigningAlgorithm();
    int days = standaloneConfig.getDays();
    String keyPairAlgorithm = standaloneConfig.getKeyPairAlgorithm();
    int keySize = standaloneConfig.getKeySize();

    File nifiCert = new File(baseDir, NIFI_CERT + ".pem");
    File nifiKey = new File(baseDir, NIFI_KEY + ".key");

    X509Certificate certificate;
    KeyPair caKeyPair;

    List<String> hostnames = standaloneConfig.getHostnames();
    if (logger.isInfoEnabled()) {
      logger.info("Running standalone certificate generation with output directory " + baseDir);
    }
    if (nifiCert.exists()) {
      if (!nifiKey.exists()) {
        throw new IOException(
            nifiCert
                + " exists already, but "
                + nifiKey
                + " does not, we need both certificate and key to continue with an existing CA.");
      }
      try (FileReader pemEncodedCertificate = new FileReader(nifiCert)) {
        certificate = TlsHelper.parseCertificate(pemEncodedCertificate);
      }
      try (FileReader pemEncodedKeyPair = new FileReader(nifiKey)) {
        caKeyPair = TlsHelper.parseKeyPair(pemEncodedKeyPair);
      }

      certificate.verify(caKeyPair.getPublic());
      if (!caKeyPair.getPublic().equals(certificate.getPublicKey())) {
        throw new IOException(
            "Expected " + nifiKey + " to correspond to CA certificate at " + nifiCert);
      }

      if (logger.isInfoEnabled()) {
        logger.info("Using existing CA certificate " + nifiCert + " and key " + nifiKey);
      }
    } else if (nifiKey.exists()) {
      throw new IOException(
          nifiKey
              + " exists already, but "
              + nifiCert
              + " does not, we need both certificate and key to continue with an existing CA.");
    } else {
      TlsCertificateAuthorityManager tlsCertificateAuthorityManager =
          new TlsCertificateAuthorityManager(standaloneConfig);
      KeyStore.PrivateKeyEntry privateKeyEntry =
          tlsCertificateAuthorityManager.getOrGenerateCertificateAuthority();
      certificate = (X509Certificate) privateKeyEntry.getCertificateChain()[0];
      caKeyPair = new KeyPair(certificate.getPublicKey(), privateKeyEntry.getPrivateKey());

      try (PemWriter pemWriter =
          new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiCert)))) {
        pemWriter.writeObject(new JcaMiscPEMGenerator(certificate));
      }

      try (PemWriter pemWriter =
          new PemWriter(new OutputStreamWriter(outputStreamFactory.create(nifiKey)))) {
        pemWriter.writeObject(new JcaMiscPEMGenerator(caKeyPair));
      }

      if (logger.isInfoEnabled()) {
        logger.info("Generated new CA certificate " + nifiCert + " and key " + nifiKey);
      }
    }

    List<String> keyStorePasswords = standaloneConfig.getKeyStorePasswords();
    List<String> keyPasswords = standaloneConfig.getKeyPasswords();
    List<String> trustStorePasswords = standaloneConfig.getTrustStorePasswords();
    NiFiPropertiesWriterFactory niFiPropertiesWriterFactory =
        standaloneConfig.getNiFiPropertiesWriterFactory();
    int httpsPort = standaloneConfig.getHttpsPort();
    boolean overwrite = standaloneConfig.isOverwrite();

    if (hostnames.isEmpty() && logger.isInfoEnabled()) {
      logger.info(
          "No "
              + TlsToolkitStandaloneCommandLine.HOSTNAMES_ARG
              + " specified, not generating any host certificates or configuration.");
    }
    for (int i = 0; i < hostnames.size(); i++) {
      String hostname = hostnames.get(i);
      File hostDir = new File(baseDir, hostname);

      TlsClientConfig tlsClientConfig = new TlsClientConfig(standaloneConfig);
      File keystore =
          new File(hostDir, "keystore." + tlsClientConfig.getKeyStoreType().toLowerCase());
      File truststore =
          new File(hostDir, "truststore." + tlsClientConfig.getTrustStoreType().toLowerCase());

      if (hostDir.exists()) {
        if (!hostDir.isDirectory()) {
          throw new IOException(hostDir + " exists but is not a directory.");
        } else if (overwrite) {
          if (logger.isInfoEnabled()) {
            logger.info("Overwriting any existing ssl configuration in " + hostDir);
          }
          keystore.delete();
          if (keystore.exists()) {
            throw new IOException(
                "Keystore " + keystore + " already exists and couldn't be deleted.");
          }
          truststore.delete();
          if (truststore.exists()) {
            throw new IOException(
                "Truststore " + truststore + " already exists and couldn't be deleted.");
          }
        } else {
          throw new IOException(hostDir + " exists and overwrite is not set.");
        }
      } else if (!hostDir.mkdirs()) {
        throw new IOException("Unable to make directory: " + hostDir.getAbsolutePath());
      } else if (logger.isInfoEnabled()) {
        logger.info("Writing new ssl configuration to " + hostDir);
      }

      tlsClientConfig.setKeyStore(keystore.getAbsolutePath());
      tlsClientConfig.setKeyStorePassword(keyStorePasswords.get(i));
      tlsClientConfig.setKeyPassword(keyPasswords.get(i));
      tlsClientConfig.setTrustStore(truststore.getAbsolutePath());
      tlsClientConfig.setTrustStorePassword(trustStorePasswords.get(i));
      TlsClientManager tlsClientManager = new TlsClientManager(tlsClientConfig);
      KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
      tlsClientManager.addPrivateKeyToKeyStore(
          keyPair,
          NIFI_KEY,
          CertificateUtils.generateIssuedCertificate(
              TlsConfig.calcDefaultDn(hostname),
              keyPair.getPublic(),
              certificate,
              caKeyPair,
              signingAlgorithm,
              days),
          certificate);
      tlsClientManager.setCertificateEntry(NIFI_CERT, certificate);
      tlsClientManager.addClientConfigurationWriter(
          new NifiPropertiesTlsClientConfigWriter(
              niFiPropertiesWriterFactory,
              outputStreamFactory,
              new File(hostDir, "nifi.properties"),
              hostname,
              httpsPort));
      tlsClientManager.write(outputStreamFactory);
      if (logger.isInfoEnabled()) {
        logger.info(
            "Successfully generated TLS configuration for "
                + hostname
                + ":"
                + httpsPort
                + " in "
                + hostDir);
      }
    }

    List<String> clientDns = standaloneConfig.getClientDns();
    if (standaloneConfig.getClientDns().isEmpty() && logger.isInfoEnabled()) {
      logger.info(
          "No "
              + TlsToolkitStandaloneCommandLine.CLIENT_CERT_DN_ARG
              + " specified, not generating any client certificates.");
    }

    List<String> clientPasswords = standaloneConfig.getClientPasswords();
    for (int i = 0; i < clientDns.size(); i++) {
      String reorderedDn = CertificateUtils.reorderDn(clientDns.get(i));
      String clientDnFile = getClientDnFile(reorderedDn);
      File clientCertFile = new File(baseDir, clientDnFile + ".p12");

      if (clientCertFile.exists()) {
        if (overwrite) {
          if (logger.isInfoEnabled()) {
            logger.info("Overwriting existing client cert " + clientCertFile);
          }
        } else {
          throw new IOException(clientCertFile + " exists and overwrite is not set.");
        }
      } else if (logger.isInfoEnabled()) {
        logger.info("Generating new client certificate " + clientCertFile);
      }
      KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
      X509Certificate clientCert =
          CertificateUtils.generateIssuedCertificate(
              reorderedDn, keyPair.getPublic(), certificate, caKeyPair, signingAlgorithm, days);
      KeyStore keyStore =
          KeyStore.getInstance(BaseTlsManager.PKCS_12, BouncyCastleProvider.PROVIDER_NAME);
      keyStore.load(null, null);
      keyStore.setKeyEntry(
          NIFI_KEY, keyPair.getPrivate(), null, new Certificate[] {clientCert, certificate});
      String password =
          TlsHelper.writeKeyStore(
              keyStore,
              outputStreamFactory,
              clientCertFile,
              clientPasswords.get(i),
              standaloneConfig.isClientPasswordsGenerated());

      try (FileWriter fileWriter = new FileWriter(new File(baseDir, clientDnFile + ".password"))) {
        fileWriter.write(password);
      }

      if (logger.isInfoEnabled()) {
        logger.info("Successfully generated client certificate " + clientCertFile);
      }
    }

    if (logger.isInfoEnabled()) {
      logger.info("tls-toolkit standalone completed successfully");
    }
  }