Search in sources :

Example 1 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project gravitee-access-management by gravitee-io.

the class CertificateServiceImpl method create.

@Override
public Single<Certificate> create(String domain, NewCertificate newCertificate, User principal) {
    LOGGER.debug("Create a new certificate {} for domain {}", newCertificate, domain);
    Single<Certificate> certificateSingle = certificatePluginService.getSchema(newCertificate.getType()).switchIfEmpty(Maybe.error(new CertificatePluginSchemaNotFoundException(newCertificate.getType()))).map(schema -> objectMapper.readValue(schema, CertificateSchema.class)).flatMapSingle(new Function<CertificateSchema, SingleSource<Certificate>>() {

        @Override
        public SingleSource<Certificate> apply(CertificateSchema certificateSchema) throws Exception {
            return Single.create(emitter -> {
                String certificateId = RandomString.generate();
                Certificate certificate = new Certificate();
                certificate.setId(certificateId);
                certificate.setDomain(domain);
                certificate.setName(newCertificate.getName());
                certificate.setType(newCertificate.getType());
                // handle file
                try {
                    JsonNode certificateConfiguration = objectMapper.readTree(newCertificate.getConfiguration());
                    certificateSchema.getProperties().entrySet().stream().filter(map -> map.getValue().getWidget() != null && "file".equals(map.getValue().getWidget())).map(map -> map.getKey()).forEach(key -> {
                        try {
                            JsonNode file = objectMapper.readTree(certificateConfiguration.get(key).asText());
                            byte[] data = Base64.getDecoder().decode(file.get("content").asText());
                            certificate.setMetadata(Collections.singletonMap(CertificateMetadata.FILE, data));
                            // update configuration to set the file name
                            ((ObjectNode) certificateConfiguration).put(key, file.get("name").asText());
                            newCertificate.setConfiguration(objectMapper.writeValueAsString(certificateConfiguration));
                        } catch (IOException ex) {
                            LOGGER.error("An error occurs while trying to create certificate binaries", ex);
                            emitter.onError(ex);
                        }
                    });
                    certificate.setConfiguration(newCertificate.getConfiguration());
                    certificate.setCreatedAt(new Date());
                    certificate.setUpdatedAt(certificate.getCreatedAt());
                } catch (Exception ex) {
                    LOGGER.error("An error occurs while trying to create certificate configuration", ex);
                    emitter.onError(ex);
                }
                emitter.onSuccess(certificate);
            });
        }
    });
    return certificateSingle.flatMap(certificate -> certificateRepository.create(certificate)).flatMap(certificate -> {
        Event event = new Event(Type.CERTIFICATE, new Payload(certificate.getId(), ReferenceType.DOMAIN, certificate.getDomain(), Action.CREATE));
        return eventService.create(event).flatMap(__ -> Single.just(certificate));
    }).doOnError(ex -> {
        LOGGER.error("An error occurs while trying to create a certificate", ex);
        throw new TechnicalManagementException("An error occurs while trying to create a certificate", ex);
    });
}
Also used : X509Certificate(java.security.cert.X509Certificate) KeyPair(java.security.KeyPair) Primary(org.springframework.context.annotation.Primary) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Type(io.gravitee.am.common.event.Type) CertificatePluginSchemaNotFoundException(io.gravitee.am.service.exception.CertificatePluginSchemaNotFoundException) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException) X500Name(org.bouncycastle.asn1.x500.X500Name) GeneralSecurityException(java.security.GeneralSecurityException) CertificateMetadata(io.gravitee.am.certificate.api.CertificateMetadata) User(io.gravitee.am.identityprovider.api.User) AuditBuilder(io.gravitee.am.service.reporter.builder.AuditBuilder) JsonNode(com.fasterxml.jackson.databind.JsonNode) ReferenceType(io.gravitee.am.model.ReferenceType) BigInteger(java.math.BigInteger) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) io.reactivex(io.reactivex) KeyPairGenerator(java.security.KeyPairGenerator) Action(io.gravitee.am.common.event.Action) CertificateNotFoundException(io.gravitee.am.service.exception.CertificateNotFoundException) CertificateWithApplicationsException(io.gravitee.am.service.exception.CertificateWithApplicationsException) KeyStore(java.security.KeyStore) EventType(io.gravitee.am.common.audit.EventType) RandomString(io.gravitee.am.common.utils.RandomString) NewCertificate(io.gravitee.am.service.model.NewCertificate) Base64(java.util.Base64) Payload(io.gravitee.am.model.common.event.Payload) Environment(org.springframework.core.env.Environment) Lazy(org.springframework.context.annotation.Lazy) Certificate(io.gravitee.am.model.Certificate) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ContentSigner(org.bouncycastle.operator.ContentSigner) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) BouncyCastleProviderSingleton(com.nimbusds.jose.crypto.bc.BouncyCastleProviderSingleton) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) Event(io.gravitee.am.model.common.event.Event) UpdateCertificate(io.gravitee.am.service.model.UpdateCertificate) CertificateSchema(io.gravitee.am.plugins.certificate.core.CertificateSchema) io.gravitee.am.service(io.gravitee.am.service) Logger(org.slf4j.Logger) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) Component(org.springframework.stereotype.Component) Function(io.reactivex.functions.Function) CertificateRepository(io.gravitee.am.repository.management.api.CertificateRepository) CertificateAuditBuilder(io.gravitee.am.service.reporter.builder.management.CertificateAuditBuilder) Collections(java.util.Collections) CertificatePluginSchemaNotFoundException(io.gravitee.am.service.exception.CertificatePluginSchemaNotFoundException) JsonNode(com.fasterxml.jackson.databind.JsonNode) RandomString(io.gravitee.am.common.utils.RandomString) IOException(java.io.IOException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificatePluginSchemaNotFoundException(io.gravitee.am.service.exception.CertificatePluginSchemaNotFoundException) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException) GeneralSecurityException(java.security.GeneralSecurityException) CertificateNotFoundException(io.gravitee.am.service.exception.CertificateNotFoundException) CertificateWithApplicationsException(io.gravitee.am.service.exception.CertificateWithApplicationsException) IOException(java.io.IOException) Date(java.util.Date) CertificateSchema(io.gravitee.am.plugins.certificate.core.CertificateSchema) Event(io.gravitee.am.model.common.event.Event) Payload(io.gravitee.am.model.common.event.Payload) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException) X509Certificate(java.security.cert.X509Certificate) NewCertificate(io.gravitee.am.service.model.NewCertificate) Certificate(io.gravitee.am.model.Certificate) UpdateCertificate(io.gravitee.am.service.model.UpdateCertificate)

Example 2 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project efm-integrasjonspunkt by felleslosninger.

the class CmsUtilTest method generateCertificate.

private Certificate generateCertificate(PublicKey subjectPublicKey, PrivateKey issuerPrivateKey) throws ParseException, OperatorCreationException, CertificateException, IOException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    X500Name issuer = new X500Name("CN=Issuer and subject (self signed)");
    BigInteger serial = new BigInteger("100");
    Date notBefore = df.parse("2010-01-01");
    Date notAfter = df.parse("2050-01-01");
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(subjectPublicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, publicKeyInfo);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(issuerPrivateKey);
    X509CertificateHolder holder = certBuilder.build(signer);
    CertificateFactory factory = CertificateFactory.getInstance("X.509");
    return factory.generateCertificate(new ByteArrayInputStream(holder.getEncoded()));
}
Also used : X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) SimpleDateFormat(java.text.SimpleDateFormat) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) CertificateFactory(java.security.cert.CertificateFactory) Date(java.util.Date)

Example 3 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project eblocker by eblocker.

the class OcspCache method getOcspResponderUrl.

private String getOcspResponderUrl(X509Certificate certificate) throws IOException {
    byte[] extensionValue = certificate.getExtensionValue(Extension.authorityInfoAccess.getId());
    if (extensionValue == null) {
        return null;
    }
    ASN1OctetString octetString = ASN1OctetString.getInstance(extensionValue);
    ASN1Primitive primitive = ASN1Primitive.fromByteArray(octetString.getOctets());
    AuthorityInformationAccess authorityInformationAccessExtension = AuthorityInformationAccess.getInstance(primitive);
    for (AccessDescription i : authorityInformationAccessExtension.getAccessDescriptions()) {
        if (i.getAccessMethod().equals(OCSPObjectIdentifiers.id_pkix_ocsp)) {
            return i.getAccessLocation().getName().toString();
        }
    }
    return null;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) AccessDescription(org.bouncycastle.asn1.x509.AccessDescription) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 4 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project interlok by adaptris.

the class X509Builder method build.

private X509Certificate build() throws NoSuchAlgorithmException, CertificateException, OperatorCreationException {
    X509Certificate result = null;
    if (privateKey == null) {
        createKeyPair();
    }
    // The certificate is self-signed, so use the current
    // subject as the issuer
    X500Name name = certificateParm.getSubjectInfo();
    // The certificate is self-signed, do we exactly care what
    // the serial number that uniquely identifies is
    BigInteger serial = BigInteger.valueOf(Integer.valueOf(SecurityUtil.getSecureRandom().nextInt(10000)).longValue());
    GregorianCalendar valid = new GregorianCalendar();
    Date notBefore = valid.getTime();
    valid.add(Calendar.MONTH, 12);
    Date notAfter = valid.getTime();
    SubjectPublicKeyInfo pubKeyInfo = SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(name, serial, notBefore, notAfter, name, pubKeyInfo);
    String alg = certificateParm.getSignatureAlgorithm();
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(alg);
    // build and sign the certificate
    X509CertificateHolder certHolder = certGen.build(builder.build(privateKey));
    result = new JcaX509CertificateConverter().getCertificate(certHolder);
    return result;
}
Also used : X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GregorianCalendar(java.util.GregorianCalendar) BigInteger(java.math.BigInteger) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date)

Example 5 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project kubernetes-client by fabric8io.

the class V1CertificateCrudTest method shouldListAndGetCertificate.

@Test
void shouldListAndGetCertificate() {
    Certificate certificate2 = new CertificateBuilder().withNewMetadata().withName("cert2").endMetadata().build();
    client.v1().certificates().inNamespace("ns2").create(certificate2);
    CertificateList certificateList = client.v1().certificates().inNamespace("ns2").list();
    assertNotNull(certificateList);
    assertEquals(1, certificateList.getItems().size());
}
Also used : CertificateBuilder(io.fabric8.certmanager.api.model.v1.CertificateBuilder) CertificateList(io.fabric8.certmanager.api.model.v1.CertificateList) Certificate(io.fabric8.certmanager.api.model.v1.Certificate) Test(org.junit.jupiter.api.Test)

Aggregations

IOException (java.io.IOException)242 X509Certificate (java.security.cert.X509Certificate)216 Date (java.util.Date)133 X500Name (org.bouncycastle.asn1.x500.X500Name)133 BigInteger (java.math.BigInteger)120 ContentSigner (org.bouncycastle.operator.ContentSigner)102 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)101 GeneralName (org.bouncycastle.asn1.x509.GeneralName)100 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)96 CertificateException (java.security.cert.CertificateException)95 ArrayList (java.util.ArrayList)90 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)85 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)82 SubjectPublicKeyInfo (org.bouncycastle.asn1.x509.SubjectPublicKeyInfo)78 GeneralSecurityException (java.security.GeneralSecurityException)69 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)62 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)62 Extension (org.bouncycastle.asn1.x509.Extension)61 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)60 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)59