Search in sources :

Example 1 with Certificate

use of org.shredzone.acme4j.Certificate in project stdlib by petergeneric.

the class LetsEncryptService method generateOrRenewCertificate.

public LetsEncryptCertificateEntity generateOrRenewCertificate(final String domains) {
    LetsEncryptCertificateEntity entity = getCertificate(domains);
    // If we already have a keypair for these domains we shouldn't regenerate it, only regenerate the cert
    final KeyPair domainKeyPair;
    final boolean isNew;
    try {
        if (entity != null) {
            final ByteArrayInputStream bis = new ByteArrayInputStream(entity.getKeypair());
            final InputStreamReader isr = new InputStreamReader(bis, StandardCharsets.UTF_8);
            domainKeyPair = KeyPairUtils.readKeyPair(isr);
            isNew = false;
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            OutputStreamWriter osr = new OutputStreamWriter(bos, StandardCharsets.UTF_8);
            domainKeyPair = KeyPairUtils.createKeyPair(DOMAIN_KEY_SIZE);
            KeyPairUtils.writeKeyPair(domainKeyPair, osr);
            entity = new LetsEncryptCertificateEntity();
            entity.setId(domains);
            entity.setKeypair(bos.toByteArray());
            isNew = true;
        }
    } catch (IOException e) {
        throw new RuntimeException("Error serialising/deserialising keypair for domains " + domains, e);
    }
    final Registration registration = getRegistration();
    // Generate a CSR for the domains
    CSRBuilder csrb = new CSRBuilder();
    for (String domain : domains.split(",")) csrb.addDomain(domain);
    try {
        csrb.sign(domainKeyPair);
    } catch (IOException e) {
        throw new RuntimeException("Error signing CSR for " + domains + " with domains keypair!", e);
    }
    // Request a signed certificate
    final Certificate certificate;
    try {
        certificate = registration.requestCertificate(csrb.getEncoded());
        log.info("Success! The certificate for domains " + domains + " has been generated!");
        log.info("Certificate URI: " + certificate.getLocation());
    } catch (IOException e) {
        throw new RuntimeException("Failed to encode CSR request for " + domains, e);
    } catch (AcmeException e) {
        throw new RuntimeException("Failed to request certificate from Let's Encrypt for " + domains, e);
    }
    // Download the certificate
    final X509Certificate cert;
    final X509Certificate[] chain;
    try {
        cert = certificate.download();
        chain = certificate.downloadChain();
    } catch (AcmeException e) {
        throw new RuntimeException("Error downloading certificate information for " + domains + " " + certificate.getLocation(), e);
    }
    // Write certificate only
    final byte[] certBytes;
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStreamWriter osr = new OutputStreamWriter(bos, StandardCharsets.UTF_8);
        CertificateUtils.writeX509Certificate(cert, osr);
        certBytes = bos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException("Error serialising Cert for " + domains, e);
    }
    // Write chain only
    byte[] chainBytes;
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        OutputStreamWriter osr = new OutputStreamWriter(bos, StandardCharsets.UTF_8);
        CertificateUtils.writeX509CertificateChain(chain, osr);
        chainBytes = bos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException("Error serialising Cert for " + domains, e);
    }
    entity.setCert(certBytes);
    entity.setChain(chainBytes);
    entity.setExpires(new DateTime(cert.getNotAfter()));
    // Make sure a management token is assigned
    if (entity.getManagementToken() == null)
        entity.setManagementToken(SimpleId.alphanumeric(32));
    if (isNew) {
        certificateDao.save(entity);
    } else {
        certificateDao.update(entity);
    }
    return entity;
}
Also used : KeyPair(java.security.KeyPair) InputStreamReader(java.io.InputStreamReader) AcmeException(org.shredzone.acme4j.exception.AcmeException) LetsEncryptCertificateEntity(com.peterphi.servicemanager.service.db.entity.LetsEncryptCertificateEntity) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) DateTime(org.joda.time.DateTime) ByteArrayInputStream(java.io.ByteArrayInputStream) Registration(org.shredzone.acme4j.Registration) OutputStreamWriter(java.io.OutputStreamWriter) CSRBuilder(org.shredzone.acme4j.util.CSRBuilder) X509Certificate(java.security.cert.X509Certificate) Certificate(org.shredzone.acme4j.Certificate)

Example 2 with Certificate

use of org.shredzone.acme4j.Certificate in project webpieces by deanhiller.

the class AcmeClientProxy method finalizeOrder.

private XFuture<CertAndSigningRequest> finalizeOrder(ProxyOrder proxyOrder, String domain, String organization, KeyPair accountKeyPair) {
    try (StringWriter writer = new StringWriter()) {
        Order order = proxyOrder.getOrder();
        CSRBuilder csrb = new CSRBuilder();
        csrb.addDomain(domain);
        csrb.setOrganization(organization);
        csrb.sign(accountKeyPair);
        byte[] csr = csrb.getEncoded();
        // NEED to store the csr as base64 into the DB!!!
        order.execute(csr);
        while (order.getStatus() != Status.VALID) {
            Thread.sleep(3000L);
            order.update();
        }
        csrb.write(writer);
        Certificate cert = order.getCertificate();
        return XFuture.completedFuture(new CertAndSigningRequest(writer.toString(), cert.getCertificateChain()));
    } catch (AcmeException | IOException | InterruptedException e) {
        throw SneakyThrow.sneak(e);
    }
}
Also used : Order(org.shredzone.acme4j.Order) CertAndSigningRequest(org.webpieces.plugin.secure.sslcert.CertAndSigningRequest) StringWriter(java.io.StringWriter) AcmeException(org.shredzone.acme4j.exception.AcmeException) IOException(java.io.IOException) CSRBuilder(org.shredzone.acme4j.util.CSRBuilder) Certificate(org.shredzone.acme4j.Certificate)

Example 3 with Certificate

use of org.shredzone.acme4j.Certificate in project meecrowave by apache.

the class LetsEncryptReloadLifecycle method run.

@Override
public synchronized void run() {
    final KeyPair userKeyPair = loadOrCreateKeyPair(config.getUserKeySize(), config.getUserKeyLocation());
    final KeyPair domainKeyPair = loadOrCreateKeyPair(config.getDomainKeySize(), config.getDomainKey());
    final Session session = new Session(config.getEndpoint());
    try {
        final Account account = new AccountBuilder().agreeToTermsOfService().useKeyPair(userKeyPair).create(session);
        final Order order = account.newOrder().domains(config.getDomains().trim().split(",")).create();
        final boolean updated = order.getAuthorizations().stream().map(authorization -> {
            try {
                return authorize(authorization);
            } catch (final AcmeException e) {
                getLogger().error(e.getMessage(), e);
                return false;
            }
        }).reduce(false, (previous, val) -> previous || val);
        if (!updated) {
            return;
        }
        final CSRBuilder csrBuilder = new CSRBuilder();
        csrBuilder.addDomains(config.getDomains());
        csrBuilder.sign(domainKeyPair);
        try (final Writer writer = new BufferedWriter(new FileWriter(config.getDomainCertificate()))) {
            csrBuilder.write(writer);
        }
        order.execute(csrBuilder.getEncoded());
        try {
            int attempts = config.getRetryCount();
            while (order.getStatus() != Status.VALID && attempts-- > 0) {
                if (order.getStatus() == Status.INVALID) {
                    throw new AcmeException("Order failed... Giving up.");
                }
                Thread.sleep(config.getRetryTimeoutMs());
                order.update();
            }
        } catch (final InterruptedException ex) {
            getLogger().error(ex.getMessage());
            Thread.currentThread().interrupt();
            return;
        }
        final Certificate certificate = order.getCertificate();
        getLogger().info("Got new certificate " + certificate.getLocation() + " for domain(s) " + config.getDomains());
        try (final Writer writer = new BufferedWriter(new FileWriter(config.getDomainChain()))) {
            certificate.writeCertificate(writer);
        }
        protocol.reloadSslHostConfigs();
    } catch (final AcmeException | IOException ex) {
        getLogger().error(ex.getMessage(), ex);
    }
}
Also used : Order(org.shredzone.acme4j.Order) AccountBuilder(org.shredzone.acme4j.AccountBuilder) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) KeyPair(java.security.KeyPair) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) Http01Challenge(org.shredzone.acme4j.challenge.Http01Challenge) ScheduledFuture(java.util.concurrent.ScheduledFuture) AbstractHttp11Protocol(org.apache.coyote.http11.AbstractHttp11Protocol) Authorization(org.shredzone.acme4j.Authorization) Certificate(org.shredzone.acme4j.Certificate) AtomicReference(java.util.concurrent.atomic.AtomicReference) Order(org.shredzone.acme4j.Order) Status(org.shredzone.acme4j.Status) Challenge(org.shredzone.acme4j.challenge.Challenge) CSRBuilder(org.shredzone.acme4j.util.CSRBuilder) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) BiConsumer(java.util.function.BiConsumer) ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorService(java.util.concurrent.ExecutorService) KeyPairGenerator(java.security.KeyPairGenerator) LogFacade(org.apache.meecrowave.logging.tomcat.LogFacade) PEMParser(org.bouncycastle.openssl.PEMParser) Session(org.shredzone.acme4j.Session) BufferedWriter(java.io.BufferedWriter) Optional.ofNullable(java.util.Optional.ofNullable) FileWriter(java.io.FileWriter) IOException(java.io.IOException) Account(org.shredzone.acme4j.Account) File(java.io.File) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Stream(java.util.stream.Stream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Writer(java.io.Writer) CliOption(org.apache.meecrowave.runner.cli.CliOption) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) AcmeException(org.shredzone.acme4j.exception.AcmeException) FileReader(java.io.FileReader) Cli(org.apache.meecrowave.runner.Cli) Account(org.shredzone.acme4j.Account) KeyPair(java.security.KeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) AcmeException(org.shredzone.acme4j.exception.AcmeException) FileWriter(java.io.FileWriter) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) AccountBuilder(org.shredzone.acme4j.AccountBuilder) CSRBuilder(org.shredzone.acme4j.util.CSRBuilder) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer) Session(org.shredzone.acme4j.Session) Certificate(org.shredzone.acme4j.Certificate)

Aggregations

IOException (java.io.IOException)3 Certificate (org.shredzone.acme4j.Certificate)3 AcmeException (org.shredzone.acme4j.exception.AcmeException)3 CSRBuilder (org.shredzone.acme4j.util.CSRBuilder)3 KeyPair (java.security.KeyPair)2 Order (org.shredzone.acme4j.Order)2 LetsEncryptCertificateEntity (com.peterphi.servicemanager.service.db.entity.LetsEncryptCertificateEntity)1 BufferedWriter (java.io.BufferedWriter)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 FileReader (java.io.FileReader)1 FileWriter (java.io.FileWriter)1 InputStreamReader (java.io.InputStreamReader)1 OutputStreamWriter (java.io.OutputStreamWriter)1 StringWriter (java.io.StringWriter)1 Writer (java.io.Writer)1 KeyPairGenerator (java.security.KeyPairGenerator)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 X509Certificate (java.security.cert.X509Certificate)1