org.shredzone.acme4j.Session Java Examples

The following examples show how to use org.shredzone.acme4j.Session. 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: CertGenerator.java    From spring-boot-starter-acme with Apache License 2.0 6 votes vote down vote up
/**
 * Finds your {@link Registration} at the ACME server. It will be found by your user's
 * public key. If your key is not known to the server yet, a new registration will be
 * created.
 * <p>
 * This is a simple way of finding your {@link Registration}. A better way is to get
 * the URL of your new registration with {@link Registration#getLocation()} and store
 * it somewhere. If you need to get access to your account later, reconnect to it via
 * {@link Registration#bind(Session, URL)} by using the stored location.
 *
 * @param session
 *            {@link Session} to bind with
 * @return {@link Registration} connected to your account
 */
private Registration getOrCreateAccount(Session session) throws AcmeException {

  Registration reg;

  try {
    // Try to create a new Registration.
    reg = new RegistrationBuilder().create(session);
    logger.info("Registered a new user, URL: " + reg.getLocation());

    // This is a new account. Let the user accept the Terms of Service.
    // We won't be able to authorize domains until the ToS is accepted.
    URI agreement = reg.getAgreement();
    logger.info("Terms of Service: " + agreement);
    acceptAgreement(reg, agreement);

  } catch (AcmeConflictException ex) {
    // The Key Pair is already registered. getLocation() contains the
    // URL of the existing registration's location. Bind it to the session.
    reg = Registration.bind(session, ex.getLocation());
    logger.info("Account does already exist, URL: " + reg.getLocation(), ex);
  }

  return reg;
}
 
Example #2
Source File: AcmeClient.java    From r2cloud with Apache License 2.0 6 votes vote down vote up
private Registration loadOrRegisterAccount(Session session) throws AcmeException {
	Registration reg;
	try {
		messages.add("registering new user", LOG);
		reg = new RegistrationBuilder().create(session);
		URI agreement = reg.getAgreement();
		messages.add("accepting terms of service", LOG);

		EditableRegistration editableReg = reg.modify();
		editableReg.setAgreement(agreement);
		editableReg.addContact("mailto:" + config.getProperty("server.login"));
		editableReg.commit();
	} catch (AcmeConflictException ex) {
		messages.add("account already exists. use it", LOG);
		reg = Registration.bind(session, ex.getLocation());
	}
	return reg;
}
 
Example #3
Source File: AccountManager.java    From acme_client with MIT License 5 votes vote down vote up
public AccountManager(KeyPair keyPair, Session session, boolean agreeToTermsOfService)
        throws AcmeException {
    AccountBuilder accountBuilder = new AccountBuilder().useKeyPair(keyPair);
    if(agreeToTermsOfService){
        accountBuilder = accountBuilder.agreeToTermsOfService();
    }
    this.login = accountBuilder.createLogin(session);
    this.account = this.login.getAccount();
}
 
Example #4
Source File: AccountManager.java    From acme_client with MIT License 5 votes vote down vote up
public AccountManager(KeyPair keyPair, Session session, String keyIdentifier,
                      SecretKey macKey, boolean agreeToTermsOfService)
        throws AcmeException {
    AccountBuilder accountBuilder = new AccountBuilder()
            .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair);
    if(agreeToTermsOfService){
        accountBuilder = accountBuilder.agreeToTermsOfService();
    }
    this.login = accountBuilder.createLogin(session);
    this.account = this.login.getAccount();
}
 
Example #5
Source File: AccountManager.java    From acme_client with MIT License 5 votes vote down vote up
public AccountManager(KeyPair keyPair, Session session, String keyIdentifier,
                      String macKey, boolean agreeToTermsOfService)
        throws AcmeException {
    AccountBuilder accountBuilder = new AccountBuilder()
            .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair);
    if(agreeToTermsOfService){
        accountBuilder = accountBuilder.agreeToTermsOfService();
    }
    this.login = accountBuilder.createLogin(session);
    this.account = this.login.getAccount();
}
 
Example #6
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 #7
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 #8
Source File: AccountManager.java    From acme_client with MIT License 4 votes vote down vote up
public AccountManager(KeyPair keyPair, Session session, URL accountLocationUrl) {
    this.login = session.login(accountLocationUrl, keyPair);
    this.account = this.login.getAccount();
}
 
Example #9
Source File: ACMECommand.java    From acme_client with MIT License 4 votes vote down vote up
public ACMECommand(Parameters parameters) {
    this.parameters = parameters;
    this.session = new Session(this.parameters.getAcmeServerUrl());
}
 
Example #10
Source File: ACMECommand.java    From acme_client with MIT License 4 votes vote down vote up
protected Session getSession() {
    return this.session;
}
 
Example #11
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());
    }
}