Search in sources :

Example 31 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project dubbo-spi-extensions by apache.

the class IstioCitadelCertificateSigner method generateCsr.

private String generateCsr(PublicKey publicKey, ContentSigner signer) throws IOException {
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { new GeneralName(6, istioEnv.getCsrHost()) });
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, true, subjectAltNames);
    PKCS10CertificationRequest request = new JcaPKCS10CertificationRequestBuilder(new X500Name("O=" + istioEnv.getTrustDomain()), publicKey).addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate()).build(signer);
    String csr = generatePemKey("CERTIFICATE REQUEST", request.getEncoded());
    if (logger.isDebugEnabled()) {
        logger.debug("CSR Request to Istio Citadel. \n" + csr);
    }
    return csr;
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X500Name(org.bouncycastle.asn1.x500.X500Name) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 32 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project conformance-suite by openid-certification.

the class ValidateMTLSCertificatesAsX509 method verifyECPrivateKey.

private void verifyECPrivateKey(String certString, String keyString, byte[] decodedKey, X509Certificate certificate) {
    PrivateKey privateKey;
    try {
        // try to generate private key is PKCS8
        KeySpec kspec = new PKCS8EncodedKeySpec(decodedKey);
        privateKey = KeyFactory.getInstance("EC", "BC").generatePrivate(kspec);
    } catch (InvalidKeySpecException e) {
        try {
            // try to generate private key isn't PKCS8
            ASN1Sequence seq = ASN1Sequence.getInstance(decodedKey);
            org.bouncycastle.asn1.sec.ECPrivateKey pKey = org.bouncycastle.asn1.sec.ECPrivateKey.getInstance(seq);
            AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, pKey.getParameters());
            byte[] server_pkcs8 = new PrivateKeyInfo(algId, pKey).getEncoded();
            privateKey = KeyFactory.getInstance("EC", "BC").generatePrivate(new PKCS8EncodedKeySpec(server_pkcs8));
        } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException ex) {
            throw error("Couldn't generate private key", e, args("key", keyString));
        }
    } catch (NoSuchProviderException | NoSuchAlgorithmException e) {
        throw error("Provider or Algorithm of KeyFactory is invalid", e);
    }
    // TODO: Need to check that the private key and the certificate match
    // This check isn't sure yet
    ECPublicKey ecPublicKey = (ECPublicKey) certificate.getPublicKey();
    if (!((ECPrivateKey) privateKey).getParameters().equals(ecPublicKey.getParameters())) {
        throw error("MTLS Private Key and Cert do not match", args("cert", certString, "key", keyString));
    }
}
Also used : ECPrivateKey(org.bouncycastle.jce.interfaces.ECPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) ECPrivateKey(org.bouncycastle.jce.interfaces.ECPrivateKey) PrivateKey(java.security.PrivateKey) KeySpec(java.security.spec.KeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ECPublicKey(org.bouncycastle.jce.interfaces.ECPublicKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) NoSuchProviderException(java.security.NoSuchProviderException) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 33 with Certificate

use of com.github.zhenwei.core.asn1.x509.Certificate in project conformance-suite by openid-certification.

the class GenerateMTLSCertificateFromJWKs method evaluate.

@Override
@PreEnvironment(required = "client_jwks", strings = "client_name")
@PostEnvironment(required = "mutual_tls_authentication")
public Environment evaluate(Environment env) {
    JWKSet jwks;
    try {
        jwks = JWKSet.parse(env.getObject("client_jwks").toString());
    } catch (ParseException e) {
        throw error("Failed to parse JWKs", e);
    }
    JWK jwk = jwks.getKeys().get(0);
    KeyPair keyPair = toKeyPair(jwk);
    String clientName = env.getString("client_name");
    long now = System.currentTimeMillis();
    Date notBefore = new Date(now);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(notBefore);
    calendar.add(Calendar.YEAR, 1);
    Date notAfter = calendar.getTime();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(now));
    certGen.setSubjectDN(new X500Principal("cn=" + clientName));
    certGen.setIssuerDN(new X500Principal("cn=" + clientName));
    certGen.setNotBefore(notBefore);
    certGen.setNotAfter(notAfter);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(getSigningAlgorithm(jwk));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    X509Certificate cert;
    try {
        cert = certGen.generate(keyPair.getPrivate(), "BC");
    } catch (CertificateEncodingException | InvalidKeyException | IllegalStateException | NoSuchProviderException | NoSuchAlgorithmException | SignatureException e) {
        throw error("Failed to generate certificate", e);
    }
    JsonObject mtls = new JsonObject();
    try {
        mtls.addProperty("cert", Base64.getEncoder().encodeToString(cert.getEncoded()));
    } catch (CertificateEncodingException e) {
        throw error("Error encoding certificate", e);
    }
    mtls.addProperty("key", Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
    env.putObject("mutual_tls_authentication", mtls);
    logSuccess("Generated client MTLS certificate", args("mutual_tls_authentication", mtls));
    return env;
}
Also used : KeyPair(java.security.KeyPair) Calendar(java.util.Calendar) JsonObject(com.google.gson.JsonObject) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) JWKSet(com.nimbusds.jose.jwk.JWKSet) X500Principal(javax.security.auth.x500.X500Principal) ParseException(java.text.ParseException) NoSuchProviderException(java.security.NoSuchProviderException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) JWK(com.nimbusds.jose.jwk.JWK) PostEnvironment(net.openid.conformance.condition.PostEnvironment) PreEnvironment(net.openid.conformance.condition.PreEnvironment)

Example 34 with Certificate

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

the class CertificatesTest method testUploadTypedCertificatesWithDaysBeforeRenewal.

@Test
@Parameters({ "acme", "manual" })
public void testUploadTypedCertificatesWithDaysBeforeRenewal(String type) throws Exception {
    configureAndStartServer();
    int port = server.getLocalPort();
    DynamicCertificatesManager dynCertsMan = server.getDynamicCertificatesManager();
    KeyPair endUserKeyPair = KeyPairUtils.createKeyPair(DEFAULT_KEYPAIRS_SIZE);
    Certificate[] chain = generateSampleChain(endUserKeyPair, false);
    byte[] chainData = createKeystore(chain, endUserKeyPair.getPrivate());
    try (RawHttpClient client = new RawHttpClient("localhost", DEFAULT_ADMIN_PORT)) {
        // Create
        HttpResponse resp = uploadCertificate("localhost2", "type=" + type + "&daysbeforerenewal=10", chainData, client, credentials);
        if (type.equals("manual")) {
            assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' available for type 'acme' only"));
        } else {
            CertificateData data = dynCertsMan.getCertificateDataForDomain("localhost2");
            assertNotNull(data);
            assertEquals(10, data.getDaysBeforeRenewal());
        }
        // negative value
        resp = uploadCertificate("localhost-negative", "type=" + type + "&daysbeforerenewal=-10", chainData, client, credentials);
        if (type.equals("manual")) {
            assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' available for type 'acme' only"));
        } else {
            assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' has to be a positive number"));
        }
        // default value
        uploadCertificate("localhost-default", "type=" + type, chainData, client, credentials);
        CertificateData data = dynCertsMan.getCertificateDataForDomain("localhost-default");
        assertNotNull(data);
        assertEquals(type.equals("manual") ? 0 : DEFAULT_DAYS_BEFORE_RENEWAL, data.getDaysBeforeRenewal());
        // Update
        uploadCertificate("localhost2", "type=" + type + "&daysbeforerenewal=45", chainData, client, credentials);
        if (type.equals("manual")) {
            assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' available for type 'acme' only"));
        } else {
            data = dynCertsMan.getCertificateDataForDomain("localhost2");
            assertNotNull(data);
            assertEquals(45, data.getDaysBeforeRenewal());
        }
        // negative value
        resp = uploadCertificate("localhost2", "type=" + type + "&daysbeforerenewal=-10", chainData, client, credentials);
        if (type.equals("manual")) {
            assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' available for type 'acme' only"));
        } else {
            assertTrue(resp.getBodyString().contains("ERROR: param 'daysbeforerenewal' has to be a positive number"));
        }
        // default value
        uploadCertificate("localhost2", "type=" + type, chainData, client, credentials);
        data = dynCertsMan.getCertificateDataForDomain("localhost2");
        assertNotNull(data);
        assertEquals(type.equals("manual") ? 0 : DEFAULT_DAYS_BEFORE_RENEWAL, data.getDaysBeforeRenewal());
        // changing the type (acme <-> manual)
        String other = type.equals("manual") ? "acme" : "manual";
        uploadCertificate("localhost2", "type=" + other, chainData, client, credentials);
        data = dynCertsMan.getCertificateDataForDomain("localhost2");
        assertNotNull(data);
        assertEquals(other.equals("manual") ? 0 : DEFAULT_DAYS_BEFORE_RENEWAL, data.getDaysBeforeRenewal());
        SSLCertificateConfiguration config = server.getCurrentConfiguration().getCertificates().get("localhost2");
        assertEquals(other.equals("manual") ? 0 : DEFAULT_DAYS_BEFORE_RENEWAL, config.getDaysBeforeRenewal());
        // checking for "certificate.X.daysbeforerenewal" property delete
        ConfigurationStore store = server.getDynamicConfigurationStore();
        assertEquals(other.equals("acme"), store.anyPropertyMatches((k, v) -> {
            if (k.matches("certificate\\.[0-9]+\\.hostname") && v.equals("localhost2")) {
                return store.getProperty(k.replace("hostname", "daysbeforerenewal"), null) != null;
            }
            return false;
        }));
    }
}
Also used : RawHttpClient(org.carapaceproxy.utils.RawHttpClient) X509Certificate(java.security.cert.X509Certificate) KeyPair(java.security.KeyPair) Arrays(java.util.Arrays) OcspStaplingManager(org.carapaceproxy.server.certificates.ocsp.OcspStaplingManager) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) ConfigurationStore(org.carapaceproxy.configstore.ConfigurationStore) CertificatesUtils.createKeystore(org.carapaceproxy.utils.CertificatesUtils.createKeystore) Order(org.shredzone.acme4j.Order) UseAdminServer(org.carapaceproxy.api.UseAdminServer) JUnitParamsRunner(junitparams.JUnitParamsRunner) WireMock.aResponse(com.github.tomakehurst.wiremock.client.WireMock.aResponse) RawHttpClient(org.carapaceproxy.utils.RawHttpClient) BasicOCSPRespBuilder(org.bouncycastle.cert.ocsp.BasicOCSPRespBuilder) List(java.util.List) Base64(java.util.Base64) Certificate(java.security.cert.Certificate) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) Assert.assertFalse(org.junit.Assert.assertFalse) OCSPRespBuilder(org.bouncycastle.cert.ocsp.OCSPRespBuilder) Login(org.shredzone.acme4j.Login) ExtendedSSLSession(javax.net.ssl.ExtendedSSLSession) Mockito.mock(org.mockito.Mockito.mock) Parameters(junitparams.Parameters) KeyPairUtils(org.shredzone.acme4j.util.KeyPairUtils) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Whitebox(org.powermock.reflect.Whitebox) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) HttpResponse(org.carapaceproxy.utils.RawHttpClient.HttpResponse) CertificatesUtils(org.carapaceproxy.utils.CertificatesUtils) CertificatesTestUtils.uploadCertificate(org.carapaceproxy.utils.CertificatesTestUtils.uploadCertificate) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) RunWith(org.junit.runner.RunWith) BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) WireMockRule(com.github.tomakehurst.wiremock.junit.WireMockRule) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) DEFAULT_KEYPAIRS_SIZE(org.carapaceproxy.server.certificates.DynamicCertificatesManager.DEFAULT_KEYPAIRS_SIZE) CertificateData(org.carapaceproxy.configstore.CertificateData) CertificatesTestUtils.generateSampleChain(org.carapaceproxy.utils.CertificatesTestUtils.generateSampleChain) HttpTestUtils(org.carapaceproxy.utils.HttpTestUtils) SSLCertificateConfiguration(org.carapaceproxy.server.config.SSLCertificateConfiguration) WireMock.get(com.github.tomakehurst.wiremock.client.WireMock.get) Properties(java.util.Properties) CertificateStatus(org.bouncycastle.cert.ocsp.CertificateStatus) TestUtils(org.carapaceproxy.utils.TestUtils) Assert.assertNotNull(org.junit.Assert.assertNotNull) VALID(org.shredzone.acme4j.Status.VALID) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) Assert.assertTrue(org.junit.Assert.assertTrue) DEFAULT_ADMIN_PORT(org.carapaceproxy.api.UseAdminServer.DEFAULT_ADMIN_PORT) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) CertificateException(java.security.cert.CertificateException) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) Rule(org.junit.Rule) DigestCalculatorProvider(org.bouncycastle.operator.DigestCalculatorProvider) WireMock.stubFor(com.github.tomakehurst.wiremock.client.WireMock.stubFor) WireMock.urlEqualTo(com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo) DEFAULT_DAYS_BEFORE_RENEWAL(org.carapaceproxy.server.certificates.DynamicCertificatesManager.DEFAULT_DAYS_BEFORE_RENEWAL) Assert.assertEquals(org.junit.Assert.assertEquals) KeyPair(java.security.KeyPair) ConfigurationStore(org.carapaceproxy.configstore.ConfigurationStore) HttpResponse(org.carapaceproxy.utils.RawHttpClient.HttpResponse) SSLCertificateConfiguration(org.carapaceproxy.server.config.SSLCertificateConfiguration) CertificateData(org.carapaceproxy.configstore.CertificateData) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) CertificatesTestUtils.uploadCertificate(org.carapaceproxy.utils.CertificatesTestUtils.uploadCertificate) Parameters(junitparams.Parameters) Test(org.junit.Test)

Example 35 with Certificate

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

the class CertificatesTestUtils method generateSampleChain.

public static Certificate[] generateSampleChain(KeyPair endUserKeypair, boolean expired) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    // Create self signed Root CA certificate
    KeyPair rootCAKeyPair = KeyPairUtils.createKeyPair(DEFAULT_KEYPAIRS_SIZE);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(// issuer authority
    new X500Name("CN=rootCA"), // serial number of certificate
    BigInteger.valueOf(new Random().nextInt()), // start of validity
    new Date(), // end of certificate validity
    new Date(), // subject name of certificate
    new X500Name("CN=rootCA"), rootCAKeyPair.getPublic());
    // public key of certificate
    // Key usage restrictions
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
    // Root certificate
    X509Certificate rootCA = new JcaX509CertificateConverter().getCertificate(builder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(// private key of signing authority , here it is self signed
    rootCAKeyPair.getPrivate())));
    // Create Intermediate CA cert signed by Root CA
    KeyPair intermedCAKeyPair = createKeyPair(DEFAULT_KEYPAIRS_SIZE);
    builder = new JcaX509v3CertificateBuilder(// here rootCA is issuer authority
    rootCA, BigInteger.valueOf(new Random().nextInt()), new Date(), new Date(), new X500Name("CN=IntermedCA"), intermedCAKeyPair.getPublic());
    // Key usage restrictions
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
    // Intermediate certificate
    X509Certificate intermediateCA = new JcaX509CertificateConverter().getCertificate(builder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(// private key of signing authority , here it is signed by rootCA
    rootCAKeyPair.getPrivate())));
    // create end user cert signed by Intermediate CA
    // yesterday/tomorrow
    int offset = 1000 * 60 * 60 * 24;
    Date expiringDate = new Date(System.currentTimeMillis() + (expired ? -offset : +offset));
    builder = new JcaX509v3CertificateBuilder(// here intermedCA is issuer authority
    intermediateCA, BigInteger.valueOf(new Random().nextInt()), new Date(System.currentTimeMillis() - offset), expiringDate, new X500Name("CN=endUserCert"), endUserKeypair.getPublic());
    // Key usage restrictions
    builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
    builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
    // End-user certificate
    X509Certificate endUserCert = new JcaX509CertificateConverter().getCertificate(builder.build(new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(// private key of signing authority , here it is signed by intermedCA
    intermedCAKeyPair.getPrivate())));
    return new X509Certificate[] { endUserCert, intermediateCA, rootCA };
}
Also used : KeyPair(java.security.KeyPair) KeyPairUtils.createKeyPair(org.shredzone.acme4j.util.KeyPairUtils.createKeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) Random(java.util.Random) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

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