org.shredzone.acme4j.util.CSRBuilder Java Examples

The following examples show how to use org.shredzone.acme4j.util.CSRBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AcmeClient.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
private void doSetup() {
	messages.add("starting up...", LOG);

	Registration reg = loadOrCreateRegistration();
	if (reg == null) {
		return;
	}

	CSRBuilder csrb = createCSR(reg);
	if (csrb == null) {
		return;
	}

	messages.add("requesting certificate", LOG);
	Certificate certificate;
	try {
		certificate = reg.requestCertificate(csrb.getEncoded());
	} catch (Exception e) {
		String message = "unable to request certificate";
		messages.add(message);
		LOG.error(message, e);
		return;
	}

	downloadCertificate(certificate);
}
 
Example #2
Source File: CertGenerator.java    From spring-boot-starter-acme with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a certificate for the given domain. Also takes care of the registration
 * process.
 *
 * @param aDomain
 *            The name of the daomain to get a common certificate for
 */
public void generate (String aDomain) throws Exception {
  // Load the user key file. If there is no key file, create a new one.
  // Keep this key pair in a safe place! In a production environment, you will not be
  // able to access your account again if you should lose the key pair.
  KeyPair userKeyPair = loadOrCreateKeyPair(new File(config.getUserKeyFile()));

  // Create a session for Let's Encrypt.
  Session session = new Session(config.getEndpoint(), userKeyPair);

  // Get the Registration to the account.
  // If there is no account yet, create a new one.
  Registration reg = getOrCreateAccount(session);

  authorize(reg, aDomain);

  // Load or create a key pair for the domains. This should not be the userKeyPair!
  KeyPair domainKeyPair = loadOrCreateKeyPair(new File(config.getDomainKeyFile()));

  // Generate a CSR for all of the domains, and sign it with the domain key pair.
  CSRBuilder csrb = new CSRBuilder();
  csrb.addDomains(Arrays.asList(aDomain));
  csrb.sign(domainKeyPair);

  // Write the CSR to a file, for later use.
  try (Writer out = new FileWriter(new File(config.getDomainCsrFile()))) {
    csrb.write(out);
  }

  // Now request a signed certificate.
  Certificate certificate = reg.requestCertificate(csrb.getEncoded());

  logger.info("Success! The certificate for domain {} has been generated!", aDomain);
  logger.info("Certificate URL: {}", certificate.getLocation());

  // Download the leaf certificate and certificate chain.
  X509Certificate cert = certificate.download();
  X509Certificate[] chain = certificate.downloadChain();

  // Write a combined file containing the certificate and chain.
  try (FileWriter fw = new FileWriter(new File (config.getDomainChainFile()))) {
    CertificateUtils.writeX509CertificateChain(fw, cert, chain);
  }

  // convert the certificate format to PKS
  ProcessBuilder pbuilder = new ProcessBuilder("openssl","pkcs12","-export","-out",config.getKeyStoreFile(),"-inkey",config.getDomainKeyFile(),"-in",config.getDomainChainFile(),"-password","pass:" + config.getKeyStorePassword());
  pbuilder.redirectErrorStream(true);

  Process process = pbuilder.start();
  int errCode = process.waitFor();
  
  try(InputStream in = process.getInputStream(); StringWriter writer = new StringWriter()) {
    IOUtils.copy(in, writer, "ASCII");
    logger.debug("openssl finished with exit code {} \n{}",errCode, writer.toString());
  }
  
}
 
Example #3
Source File: AcmeClient.java    From blynk-server with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Generates a certificate for the given domains. Also takes care for the registration
 * process.
 *
 * @param domain
 *            Domains to get a common certificate for
 */
private void fetchCertificate(String contact, String domain) throws IOException, AcmeException {
    // Load the user key file. If there is no key file, create a new one.
    // Keep this key pair in a safe place! In a production environment, you will not be
    // able to access your account again if you should lose the key pair.
    KeyPair userKeyPair = loadOrCreateKeyPair(USER_KEY_FILE);

    Session session = new Session(letsEncryptUrl);

    // Get the Account.
    // If there is no account yet, create a new one.
    Account account = new AccountBuilder()
            .agreeToTermsOfService()
            .useKeyPair(userKeyPair)
            .addEmail(contact)
            .create(session);
    log.info("Registered a new user, URL: {}", account.getLocation());

    // Load or create a key pair for the domains. This should not be the userKeyPair!
    KeyPair domainKeyPair = loadOrCreateKeyPair(DOMAIN_KEY_FILE);

    // Order the certificate
    Order order = account.newOrder().domain(domain).create();

    // Perform all required authorizations
    for (Authorization auth : order.getAuthorizations()) {
        authorize(auth);
    }

    // Generate a CSR for all of the domains, and sign it with the domain key pair.
    CSRBuilder csrb = new CSRBuilder();
    csrb.addDomain(domain);
    csrb.setOrganization("Blynk Inc.");
    csrb.sign(domainKeyPair);

    // Order the certificate
    order.execute(csrb.getEncoded());

    // Wait for the order to complete
    try {
        int attempts = ATTEMPTS;
        while (order.getStatus() != Status.VALID && attempts-- > 0) {
            if (order.getStatus() == Status.INVALID) {
                throw new AcmeException("Order failed... Giving up.");
            }
            Thread.sleep(WAIT_MILLIS);
            order.update();
        }
    } catch (InterruptedException ex) {
        log.error("interrupted", ex);
    }

    Certificate certificate = order.getCertificate();

    if (certificate != null) {
        try (FileWriter fw = new FileWriter(DOMAIN_CHAIN_FILE)) {
            certificate.writeCertificate(fw);
        }
        log.info("Overriding certificate. Expiration date is : {}", certificate.getCertificate().getNotAfter());
    }
}