Search in sources :

Example 6 with AuthorityKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier in project credhub by cloudfoundry.

the class SignedCertificateGenerator method getSignedByIssuer.

private X509Certificate getSignedByIssuer(final X509Certificate issuerCertificate, final PrivateKey issuerKey, final X500Principal issuerDn, final SubjectKeyIdentifier caSubjectKeyIdentifier, final KeyPair keyPair, final CertificateGenerationParameters params) throws Exception {
    final Instant now = Instant.from(timeProvider.getInstant());
    final BigInteger certificateSerialNumber = serialNumberGenerator.generate();
    final JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(issuerDn, certificateSerialNumber, Date.from(now), Date.from(now.plus(Duration.ofDays(params.getDuration()))), params.getX500Principal(), keyPair.getPublic());
    certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, getSubjectKeyIdentifierFromKeyInfo(keyPair.getPublic()));
    if (params.getAlternativeNames() != null) {
        certificateBuilder.addExtension(Extension.subjectAlternativeName, false, params.getAlternativeNames());
    }
    if (params.getKeyUsage() != null) {
        certificateBuilder.addExtension(Extension.keyUsage, true, params.getKeyUsage());
    }
    if (params.getExtendedKeyUsage() != null) {
        certificateBuilder.addExtension(Extension.extendedKeyUsage, false, params.getExtendedKeyUsage());
    }
    if (caSubjectKeyIdentifier.getKeyIdentifier() != null) {
        AuthorityKeyIdentifier authorityKeyIdentifier;
        if (issuerCertificate != null) {
            authorityKeyIdentifier = new AuthorityKeyIdentifier(jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate).getKeyIdentifier());
        } else {
            authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(keyPair.getPublic());
        }
        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);
    }
    certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(params.isCa()));
    final ContentSigner contentSigner = jcaContentSignerBuilder.build(issuerKey);
    final X509CertificateHolder holder = certificateBuilder.build(contentSigner);
    return jcaX509CertificateConverter.getCertificate(holder);
}
Also used : Instant(java.time.Instant) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ContentSigner(org.bouncycastle.operator.ContentSigner) BigInteger(java.math.BigInteger) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 7 with AuthorityKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier in project credhub by cloudfoundry.

the class SignedCertificateGeneratorTest method getSignedByIssuer_withNonGeneratedSubjectKeyIdentifier_setsAuthorityKeyIdentifier.

@Test
public void getSignedByIssuer_withNonGeneratedSubjectKeyIdentifier_setsAuthorityKeyIdentifier() throws Exception {
    final X509Certificate caCertificate = new CertificateReader(TEST_CA_WITH_DIFFERENT_SKID).getCertificate();
    PrivateKey caPrivateKey = PrivateKeyReader.getPrivateKey(TEST_KEY_WITH_DIFFERENT_SKID);
    final X509Certificate generatedCert = subject.getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters, caCertificate, caPrivateKey);
    final byte[] authorityKeyIdDer = generatedCert.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    final AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(parseExtensionValue(authorityKeyIdDer));
    final byte[] subjectKeyIdDer = caCertificate.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier.getInstance(parseExtensionValue(subjectKeyIdDer));
    assertThat(authorityKeyIdentifier.getKeyIdentifier(), equalTo(subjectKeyIdentifier.getKeyIdentifier()));
}
Also used : PrivateKey(java.security.PrivateKey) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) CertificateReader(org.cloudfoundry.credhub.utils.CertificateReader) Test(org.junit.Test)

Example 8 with AuthorityKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier in project credhub by cloudfoundry.

the class SignedCertificateGeneratorTest method getSelfSigned_generatesACertificateWithTheRightValues.

@Test
public void getSelfSigned_generatesACertificateWithTheRightValues() throws Exception {
    final X509Certificate generatedCertificate = subject.getSelfSigned(generatedCertificateKeyPair, certificateGenerationParameters);
    assertThat(generatedCertificate.getIssuerDN().getName(), containsString("CN=my cert name"));
    assertThat(generatedCertificate.getSubjectDN().toString(), containsString("CN=my cert name"));
    generatedCertificate.verify(generatedCertificateKeyPair.getPublic());
    final byte[] authorityKeyIdDer = generatedCertificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    final AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(parseExtensionValue(authorityKeyIdDer));
    final byte[] authorityKeyId = authorityKeyIdentifier.getKeyIdentifier();
    expectedSubjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(generatedCertificateKeyPair.getPublic()).getKeyIdentifier();
    assertThat(authorityKeyId, equalTo(expectedSubjectKeyIdentifier));
    assertThat(generatedCertificate.getSerialNumber(), equalTo(BigInteger.valueOf(1337)));
}
Also used : AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 9 with AuthorityKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier in project credhub by cloudfoundry.

the class CertificateGenerateTest method certificateGeneration_shouldGenerateCorrectCertificate.

@Test
public void certificateGeneration_shouldGenerateCorrectCertificate() throws Exception {
    final MockHttpServletRequestBuilder caPost = post("/api/v1/data").header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content("{\n" + "  \"name\" : \"picard\",\n" + "  \"type\" : \"certificate\",\n" + "  \"parameters\" : {\n" + "    \"common_name\" : \"federation\",\n" + "    \"is_ca\" : true,\n" + "    \"self_sign\" : true,\n" + "    \"duration\" : 1 \n" + "  }\n" + "}");
    final String caResult = this.mockMvc.perform(caPost).andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    JSONObject result = new JSONObject(caResult);
    final String picardCert = result.getJSONObject("value").getString("certificate");
    final String picardCA = result.getJSONObject("value").getString("ca");
    assertThat(picardCert, equalTo(picardCA));
    final String expiryDate = result.getString("expiry_date");
    final String truncatedExpiryDate = expiryDate.substring(0, expiryDate.indexOf('T'));
    final Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, 1);
    final String expectedTime = calendar.getTime().toInstant().truncatedTo(ChronoUnit.SECONDS).toString();
    final String truncatedExpected = expectedTime.substring(0, expectedTime.indexOf('T'));
    assertThat(truncatedExpiryDate, equalTo(truncatedExpected));
    assertThat(result.getBoolean("certificate_authority"), equalTo(true));
    assertThat(result.getBoolean("self_signed"), equalTo(true));
    assertThat(result.getBoolean("generated"), equalTo(true));
    assertThat(picardCert, notNullValue());
    final MockHttpServletRequestBuilder certPost = post("/api/v1/data").header("Authorization", "Bearer " + ALL_PERMISSIONS_TOKEN).accept(APPLICATION_JSON).contentType(APPLICATION_JSON).content("{\n" + "  \"name\" : \"riker\",\n" + "  \"type\" : \"certificate\",\n" + "  \"parameters\" : {\n" + "    \"common_name\" : \"federation\",\n" + "    \"ca\" : \"picard\"\n" + "  }\n" + "}");
    final String certResult = this.mockMvc.perform(certPost).andDo(print()).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
    final String certCa = (new JSONObject(certResult)).getJSONObject("value").getString("ca");
    final String cert = (new JSONObject(certResult)).getJSONObject("value").getString("certificate");
    assertThat(certCa, equalTo(picardCert));
    final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    final X509Certificate caPem = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(picardCert.getBytes(UTF_8)));
    final X509Certificate certPem = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert.getBytes(UTF_8)));
    final byte[] subjectKeyIdDer = caPem.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    final SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier.getInstance(JcaX509ExtensionUtils.parseExtensionValue(subjectKeyIdDer));
    final byte[] subjectKeyId = subjectKeyIdentifier.getKeyIdentifier();
    final byte[] authorityKeyIdDer = certPem.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    final AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(JcaX509ExtensionUtils.parseExtensionValue(authorityKeyIdDer));
    final byte[] authKeyId = authorityKeyIdentifier.getKeyIdentifier();
    assertThat(subjectKeyId, equalTo(authKeyId));
}
Also used : JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) MockHttpServletRequestBuilder(org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder) Calendar(java.util.Calendar) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 10 with AuthorityKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier in project XobotOS by xamarin.

the class JDKPKCS12KeyStore method engineGetCertificateChain.

public Certificate[] engineGetCertificateChain(String alias) {
    if (alias == null) {
        throw new IllegalArgumentException("null alias passed to getCertificateChain.");
    }
    if (!engineIsKeyEntry(alias)) {
        return null;
    }
    Certificate c = engineGetCertificate(alias);
    if (c != null) {
        Vector cs = new Vector();
        while (c != null) {
            X509Certificate x509c = (X509Certificate) c;
            Certificate nextC = null;
            byte[] bytes = x509c.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
            if (bytes != null) {
                try {
                    ASN1InputStream aIn = new ASN1InputStream(bytes);
                    byte[] authBytes = ((ASN1OctetString) aIn.readObject()).getOctets();
                    aIn = new ASN1InputStream(authBytes);
                    AuthorityKeyIdentifier id = new AuthorityKeyIdentifier((ASN1Sequence) aIn.readObject());
                    if (id.getKeyIdentifier() != null) {
                        nextC = (Certificate) chainCerts.get(new CertId(id.getKeyIdentifier()));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e.toString());
                }
            }
            if (nextC == null) {
                //
                // no authority key id, try the Issuer DN
                //
                Principal i = x509c.getIssuerDN();
                Principal s = x509c.getSubjectDN();
                if (!i.equals(s)) {
                    Enumeration e = chainCerts.keys();
                    while (e.hasMoreElements()) {
                        X509Certificate crt = (X509Certificate) chainCerts.get(e.nextElement());
                        Principal sub = crt.getSubjectDN();
                        if (sub.equals(i)) {
                            try {
                                x509c.verify(crt.getPublicKey());
                                nextC = crt;
                                break;
                            } catch (Exception ex) {
                            // continue
                            }
                        }
                    }
                }
            }
            cs.addElement(c);
            if (// self signed - end of the chain
            nextC != c) {
                c = nextC;
            } else {
                c = null;
            }
        }
        Certificate[] certChain = new Certificate[cs.size()];
        for (int i = 0; i != certChain.length; i++) {
            certChain[i] = (Certificate) cs.elementAt(i);
        }
        return certChain;
    }
    return null;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

AuthorityKeyIdentifier (org.bouncycastle.asn1.x509.AuthorityKeyIdentifier)49 BigInteger (java.math.BigInteger)24 X509Certificate (java.security.cert.X509Certificate)21 IOException (java.io.IOException)17 GeneralName (org.bouncycastle.asn1.x509.GeneralName)16 Test (org.junit.Test)16 SubjectKeyIdentifier (org.bouncycastle.asn1.x509.SubjectKeyIdentifier)15 Date (java.util.Date)14 X500Name (org.bouncycastle.asn1.x500.X500Name)13 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)13 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)13 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)11 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)10 DEROctetString (org.bouncycastle.asn1.DEROctetString)9 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)9 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)8 X509v2CRLBuilder (org.bouncycastle.cert.X509v2CRLBuilder)8 ContentSigner (org.bouncycastle.operator.ContentSigner)8 HashSet (java.util.HashSet)7 Extension (org.bouncycastle.asn1.x509.Extension)7