org.shredzone.acme4j.Certificate Java Examples

The following examples show how to use org.shredzone.acme4j.Certificate. 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: GenerateCertificateCommand.java    From acme_client with MIT License 6 votes vote down vote up
private void generateCertificate(Order order){
    try {
        List<Certificate> certificateList = getNotExpiredCertificates();
        if(certificateList==null){
            certificateList = new LinkedList<>();
        }

        CertificateManager certificateManager = new CertificateManager(order.getCertificate());
        certificateList.add(certificateManager.getCertificate());
        writeCertificate(certificateManager, "");

        error = error || !writeCertificateList(certificateList);
    } catch (Exception e) {
        LOG.error("Cannot get certificate. Check if your domains of the certificate are verified", e);
        error = true;
    }

}
 
Example #3
Source File: CertificateCommand.java    From acme_client with MIT License 5 votes vote down vote up
boolean writeCertificateList(List<Certificate> certificateList) {
    try {
        List<String> certificateLocationList = new LinkedList<>();
        for(Certificate certificate : certificateList){
            certificateLocationList.add(certificate.getLocation().toString());
        }
        IOManager.writeString(CERTIFICATE_FILE_PATH,
                getGson().toJson(certificateLocationList, urlsListTokenType));
    } catch (IOException e) {
        LOG.error("Cannot write certificate list to file: " + Paths.get(getParameters().getWorkDir(),
                Parameters.CERTIFICATE_URI_LIST).toString() + "\n Please check permissions of the file.", e);
        return false;
    }
    return true;
}
 
Example #4
Source File: CertificateExpireComparator.java    From acme_client with MIT License 5 votes vote down vote up
@Override
public int compare(Certificate c1, Certificate c2) {
    long c1expire = c1.getCertificate().getNotAfter().getTime();
    long c2expire = c2.getCertificate().getNotAfter().getTime();

    if (c1expire > c2expire) {
        return -1;
    } else if (c1expire < c2expire) {
        return 1;
    }
    return Integer.compare(c1.hashCode(), c2.hashCode());
}
 
Example #5
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 #6
Source File: CertificateManager.java    From acme_client with MIT License 4 votes vote down vote up
public CertificateManager(Certificate certificate) {
    this.certificate = certificate;
}
 
Example #7
Source File: CertificateManager.java    From acme_client with MIT License 4 votes vote down vote up
public Certificate getCertificate() {
    return this.certificate;
}
 
Example #8
Source File: CertificateManager.java    From acme_client with MIT License 4 votes vote down vote up
public static void revokeCertificate(Session session, KeyPair domainKeyPair, X509Certificate cert, RevocationReason reason)
        throws AcmeException {
    Certificate.revoke(session, domainKeyPair, cert, reason);
}
 
Example #9
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());
    }
}