Search in sources :

Example 21 with CertificateRequest

use of com.venafi.vcert.sdk.certificate.CertificateRequest in project vcert-java by Venafi.

the class CloudClient method main.

public static void main(String[] args) throws VCertException, CertificateEncodingException, NoSuchAlgorithmException, KeyManagementException {
    String url = System.getenv("CLOUDURL");
    String zone = System.getenv("CLOUDZONE");
    String appInfo = System.getenv("PRODUCT");
    String apiKey = System.getenv("APIKEY");
    if (zone == null) {
        // or by ID "38992cc0-0177-11ea-a3f0-2b5db8116980";
        zone = "My Project\\My Zone";
    }
    if (appInfo == null)
        appInfo = "My Application 1.0.0.0";
    if (apiKey == null)
        apiKey = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee";
    Config config = Config.builder().connectorType(ConnectorType.CLOUD).baseUrl(url).appInfo(appInfo).build();
    Authentication auth = Authentication.builder().apiKey(apiKey).build();
    VCertClient client = new VCertClient(config);
    client.authenticate(auth);
    ZoneConfiguration zoneConfiguration = client.readZoneConfiguration(zone);
    // Generate a certificate
    CertificateRequest certificateRequest = new CertificateRequest().subject(new CertificateRequest.PKIXName().commonName("vcert-java.venafi.example").organization(Collections.singletonList("Venafi, Inc.")).organizationalUnit(Arrays.asList("Product Management")).country(Collections.singletonList("US")).locality(Collections.singletonList("Salt Lake City")).province(Collections.singletonList("Utah"))).keyType(KeyType.RSA).keyLength(2048);
    certificateRequest = client.generateRequest(zoneConfiguration, certificateRequest);
    // Submit the certificate request
    client.requestCertificate(certificateRequest, zoneConfiguration);
    // Retrieve PEM collection from Venafi
    PEMCollection pemCollection = client.retrieveCertificate(certificateRequest);
    System.out.println(pemCollection.certificate());
}
Also used : PEMCollection(com.venafi.vcert.sdk.certificate.PEMCollection) Config(com.venafi.vcert.sdk.Config) Authentication(com.venafi.vcert.sdk.endpoint.Authentication) VCertClient(com.venafi.vcert.sdk.VCertClient) ZoneConfiguration(com.venafi.vcert.sdk.connectors.ZoneConfiguration) CertificateRequest(com.venafi.vcert.sdk.certificate.CertificateRequest)

Example 22 with CertificateRequest

use of com.venafi.vcert.sdk.certificate.CertificateRequest in project vcert-java by Venafi.

the class ZoneConfiguration method applyCertificateRequestDefaultSettingsIfNeeded.

/**
 * UpdateCertificateRequest updates a certificate request based on the zone configuration
 * retrieved from the remote endpoint
 */
public void applyCertificateRequestDefaultSettingsIfNeeded(CertificateRequest request) {
    CertificateRequest.PKIXName subject = request.subject();
    subject.organization(Entity.of(subject.organization(), organization).resolve());
    if (Is.blank(subject.organizationalUnit()) && !Is.blank(organizationalUnit)) {
        subject.organizationalUnit(organizationalUnit);
    }
    subject.country(Entity.of(subject.country(), country).resolve());
    subject.province(Entity.of(subject.province(), province).resolve());
    subject.locality(Entity.of(subject.locality(), locality).resolve());
    // apply defaults for settings that weren't specified and then make sure they comply with policy
    if (request.keyType() == null) {
        request.keyType(keyConfig != null && keyConfig.keyType() != null ? keyConfig.keyType() : KeyType.defaultKeyType());
    }
    switch(request.keyType()) {
        case ECDSA:
            if (request.keyCurve() == null) {
                request.keyCurve(EllipticCurve.ellipticCurveDefault());
            }
            if (request.signatureAlgorithm() == SignatureAlgorithm.UnknownSignatureAlgorithm) {
                request.signatureAlgorithm(SignatureAlgorithm.ECDSAWithSHA256);
            }
            break;
        default:
            if (request.keyLength() < KeyType.defaultRsaLength()) {
                request.keyLength(keyConfig != null && !Is.blank(keyConfig.keySizes()) && keyConfig.keySizes().get(0) >= KeyType.defaultRsaLength() ? keyConfig.keySizes().get(0) : KeyType.defaultRsaLength());
            }
            if (request.signatureAlgorithm() == SignatureAlgorithm.UnknownSignatureAlgorithm) {
                request.signatureAlgorithm(SignatureAlgorithm.SHA256WithRSA);
            }
            break;
    }
    if (!Is.blank(policy.allowedKeyConfigurations())) {
        for (AllowedKeyConfiguration keyConf : policy.allowedKeyConfigurations()) {
            if (keyConf.keyType() == request.keyType()) {
                switch(request.keyType()) {
                    case ECDSA:
                        {
                            if (!Is.blank(keyConf.keyCurves())) {
                                if (!keyConf.keyCurves().contains(request.keyCurve())) {
                                    request.keyCurve(keyConf.keyCurves().get(0));
                                }
                            }
                            break;
                        }
                    case RSA:
                        {
                            if (!Is.blank(keyConf.keySizes())) {
                                boolean sizeOK = false;
                                for (Integer size : keyConf.keySizes()) {
                                    if (size.equals(request.keyLength())) {
                                        sizeOK = true;
                                    }
                                }
                                if (!sizeOK) {
                                    request.keyLength(keyConf.keySizes().get(0));
                                }
                            }
                            break;
                        }
                }
            }
        }
    }
}
Also used : AllowedKeyConfiguration(com.venafi.vcert.sdk.endpoint.AllowedKeyConfiguration) CertificateRequest(com.venafi.vcert.sdk.certificate.CertificateRequest)

Example 23 with CertificateRequest

use of com.venafi.vcert.sdk.certificate.CertificateRequest in project vcert-java by Venafi.

the class CloudConnector method renewCertificate.

@Override
public String renewCertificate(RenewalRequest request) throws VCertException {
    String certificateRequestId = null;
    if (isNotBlank(request.thumbprint())) {
        Cloud.CertificateSearchResponse result = this.searchCertificatesByFingerprint(request.thumbprint());
        Set<String> requestIds = result.certificates().stream().map(c -> c.certificateRequestId()).collect(Collectors.toSet());
        if (requestIds.size() > 1) {
            throw new MoreThanOneCertificateRequestIdException(request.thumbprint());
        } else if (requestIds.size() == 0) {
            throw new CertificateNotFoundByThumbprintException(request.thumbprint());
        }
        certificateRequestId = requestIds.iterator().next();
    } else if (isNotBlank(request.certificateDN())) {
        certificateRequestId = request.certificateDN();
    } else {
        throw new CertificateDNOrThumbprintWasNotProvidedException();
    }
    final CertificateStatus status = cloud.certificateStatus(certificateRequestId, auth.apiKey());
    String certificateId = status.certificateIds().get(0);
    CertificateDetails certDetails = cloud.certificateDetails(certificateId, auth.apiKey());
    if (!certDetails.certificateRequestId().equals(certificateRequestId)) {
        final StringBuilder errorStr = new StringBuilder();
        errorStr.append("Certificate under requestId %s ");
        errorStr.append(isNotBlank(request.thumbprint()) ? String.format("with thumbprint %s ", request.thumbprint()) : "");
        errorStr.append("is not the latest under ManagedCertificateId %s. The latest request is %s. ");
        errorStr.append("This error may happen when revoked certificate is requested to be renewed.");
        throw new VCertException(String.format(errorStr.toString(), certificateRequestId, certDetails.id(), certDetails.certificateRequestId()));
    }
    final CertificateRequestsPayload certificateRequest = new CertificateRequestsPayload();
    certificateRequest.existingCertificateId(certDetails.id());
    certificateRequest.applicationId(status.applicationId());
    certificateRequest.certificateIssuingTemplateId(status.certificateIssuingTemplateId());
    // add client information
    VCertUtils.addApiClientInformation(certificateRequest);
    certificateRequest.reuseCSR(!(Objects.nonNull(request.request()) && request.request().csr().length > 0));
    if (!certificateRequest.reuseCSR) {
        certificateRequest.csr(Strings.fromByteArray(request.request().csr()));
    } else {
        throw new CSRNotProvidedException();
    }
    CertificateRequestsResponse response = cloud.certificateRequest(auth.apiKey(), certificateRequest);
    return response.certificateRequests().get(0).id();
}
Also used : ImportResponse(com.venafi.vcert.sdk.certificate.ImportResponse) CertificateStatus(com.venafi.vcert.sdk.certificate.CertificateStatus) SshCertRetrieveDetails(com.venafi.vcert.sdk.certificate.SshCertRetrieveDetails) StringUtils(org.apache.commons.lang3.StringUtils) CsrOriginOption(com.venafi.vcert.sdk.certificate.CsrOriginOption) CharStreams(com.google.common.io.CharStreams) com.venafi.vcert.sdk.connectors.cloud.domain(com.venafi.vcert.sdk.connectors.cloud.domain) SshCertificateRequest(com.venafi.vcert.sdk.certificate.SshCertificateRequest) SshConfig(com.venafi.vcert.sdk.certificate.SshConfig) ConnectorType(com.venafi.vcert.sdk.endpoint.ConnectorType) Collection(java.util.Collection) Set(java.util.Set) UUID(java.util.UUID) Instant(java.time.Instant) SerializedName(com.google.gson.annotations.SerializedName) Collectors(java.util.stream.Collectors) VCertException(com.venafi.vcert.sdk.VCertException) CertificateRequest(com.venafi.vcert.sdk.certificate.CertificateRequest) String.format(java.lang.String.format) CloudPolicy(com.venafi.vcert.sdk.policy.api.domain.CloudPolicy) Objects(java.util.Objects) PolicySpecification(com.venafi.vcert.sdk.policy.domain.PolicySpecification) Base64(java.util.Base64) List(java.util.List) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) OffsetDateTime(java.time.OffsetDateTime) ConnectorException(com.venafi.vcert.sdk.connectors.ConnectorException) ZERO(java.time.Duration.ZERO) Connector(com.venafi.vcert.sdk.connectors.Connector) Pattern(java.util.regex.Pattern) KeystoreRequest(com.venafi.vcert.sdk.connectors.cloud.endpoint.KeystoreRequest) Getter(lombok.Getter) RenewalRequest(com.venafi.vcert.sdk.certificate.RenewalRequest) ZoneConfiguration(com.venafi.vcert.sdk.connectors.ZoneConfiguration) PEMCollection(com.venafi.vcert.sdk.certificate.PEMCollection) ArrayList(java.util.ArrayList) SshCaTemplateRequest(com.venafi.vcert.sdk.certificate.SshCaTemplateRequest) Authentication(com.venafi.vcert.sdk.endpoint.Authentication) VCertUtils(com.venafi.vcert.sdk.utils.VCertUtils) Strings(org.bouncycastle.util.Strings) Response(feign.Response) CloudPolicySpecificationConverter(com.venafi.vcert.sdk.policy.converter.CloudPolicySpecificationConverter) Policy(com.venafi.vcert.sdk.connectors.Policy) IOException(java.io.IOException) TimeUnit(java.util.concurrent.TimeUnit) ImportRequest(com.venafi.vcert.sdk.certificate.ImportRequest) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) Data(lombok.Data) RevocationRequest(com.venafi.vcert.sdk.certificate.RevocationRequest) InputStream(java.io.InputStream) CertificateStatus(com.venafi.vcert.sdk.certificate.CertificateStatus) VCertException(com.venafi.vcert.sdk.VCertException)

Example 24 with CertificateRequest

use of com.venafi.vcert.sdk.certificate.CertificateRequest in project vcert-java by Venafi.

the class Examples method main.

public static void main(String... args) throws VCertException, CertificateEncodingException {
    final Config config = Config.builder().connectorType(ConnectorType.CLOUD).zone("Default").build();
    final VCertClient client = new VCertClient(config);
    final Authentication auth = Authentication.builder().apiKey("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").build();
    client.authenticate(auth);
    final ZoneConfiguration zoneConfiguration = client.readZoneConfiguration("My Project\\My Zone");
    // Generate a certificate
    CertificateRequest certificateRequest = new CertificateRequest().subject(new CertificateRequest.PKIXName().commonName("cert.test").organization(Collections.singletonList("Venafi, Inc.")).organizationalUnit(Arrays.asList("Engineering")).country(Collections.singletonList("US")).locality(Collections.singletonList("SLC")).province(Collections.singletonList("Utah"))).keyType(KeyType.RSA);
    certificateRequest = client.generateRequest(zoneConfiguration, certificateRequest);
    // Submit the certificate request
    String newCertId = client.requestCertificate(certificateRequest, zoneConfiguration);
    // Retrieve PEM collection from Venafi
    final CertificateRequest pickupRequest = new CertificateRequest().pickupId(newCertId);
    PEMCollection pemCollection = client.retrieveCertificate(pickupRequest);
    System.out.println(pemCollection.certificate());
    // Renew the certificate
    X509Certificate cert = (X509Certificate) pemCollection.certificate();
    String thumbprint = DigestUtils.sha1Hex(cert.getEncoded()).toUpperCase();
    final CertificateRequest certificateRequestToRenew = new CertificateRequest().subject(new CertificateRequest.PKIXName().commonName("cert.test").organization(Collections.singletonList("Venafi, Inc.")).organizationalUnit(Arrays.asList("Engineering")).country(Collections.singletonList("US")).locality(Collections.singletonList("SLC")).province(Collections.singletonList("Utah")));
    client.generateRequest(zoneConfiguration, certificateRequestToRenew);
    final RenewalRequest renewalRequest = new RenewalRequest().thumbprint(thumbprint).request(certificateRequestToRenew);
    final String renewedCertificate = client.renewCertificate(renewalRequest);
    // Retrieve PEM collection from Venafi
    final CertificateRequest renewPickupRequest = new CertificateRequest().pickupId(renewedCertificate);
    PEMCollection pemCollectionRenewed = client.retrieveCertificate(pickupRequest);
    System.out.println(pemCollectionRenewed.certificate());
}
Also used : PEMCollection(com.venafi.vcert.sdk.certificate.PEMCollection) RenewalRequest(com.venafi.vcert.sdk.certificate.RenewalRequest) Authentication(com.venafi.vcert.sdk.endpoint.Authentication) ZoneConfiguration(com.venafi.vcert.sdk.connectors.ZoneConfiguration) CertificateRequest(com.venafi.vcert.sdk.certificate.CertificateRequest) X509Certificate(java.security.cert.X509Certificate)

Example 25 with CertificateRequest

use of com.venafi.vcert.sdk.certificate.CertificateRequest in project vcert-java by Venafi.

the class VCertClientTest method generateRequestWithServerError.

@Test
@DisplayName("Generate request with server error")
void generateRequestWithServerError() throws VCertException {
    final ZoneConfiguration zoneConfiguration = mock(ZoneConfiguration.class);
    final CertificateRequest certificateRequest = mock(CertificateRequest.class);
    doThrow(new FeignException.InternalServerError("Error", request, "".getBytes())).when(connector).generateRequest(zoneConfiguration, certificateRequest);
    assertThrows(VCertException.class, () -> classUnderTest.generateRequest(zoneConfiguration, certificateRequest));
}
Also used : ZoneConfiguration(com.venafi.vcert.sdk.connectors.ZoneConfiguration) FeignException(feign.FeignException) CertificateRequest(com.venafi.vcert.sdk.certificate.CertificateRequest) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Aggregations

CertificateRequest (com.venafi.vcert.sdk.certificate.CertificateRequest)53 Test (org.junit.jupiter.api.Test)44 ZoneConfiguration (com.venafi.vcert.sdk.connectors.ZoneConfiguration)43 DisplayName (org.junit.jupiter.api.DisplayName)24 PEMCollection (com.venafi.vcert.sdk.certificate.PEMCollection)20 RenewalRequest (com.venafi.vcert.sdk.certificate.RenewalRequest)9 Authentication (com.venafi.vcert.sdk.endpoint.Authentication)8 StringReader (java.io.StringReader)8 FeignException (feign.FeignException)7 X509Certificate (java.security.cert.X509Certificate)7 RevocationRequest (com.venafi.vcert.sdk.certificate.RevocationRequest)6 VCertException (com.venafi.vcert.sdk.VCertException)5 IOException (java.io.IOException)5 ArrayList (java.util.ArrayList)5 PEMParser (org.bouncycastle.openssl.PEMParser)5 CsrOriginOption (com.venafi.vcert.sdk.certificate.CsrOriginOption)4 DataFormat (com.venafi.vcert.sdk.certificate.DataFormat)4 Instant (java.time.Instant)4 BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)4 PKCS10CertificationRequest (org.bouncycastle.pkcs.PKCS10CertificationRequest)4