Search in sources :

Example 6 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier 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 SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier 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 SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier 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 9 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project nhin-d by DirectProject.

the class SubjectKeyIdentifierExtensionField method injectReferenceValue.

/**
	 * {@inheritDoc}
	 */
@Override
public void injectReferenceValue(X509Certificate value) throws PolicyProcessException {
    this.certificate = value;
    final DERObject exValue = getExtensionValue(value);
    if (exValue == null) {
        if (isRequired())
            throw new PolicyRequiredException("Extention " + getExtentionIdentifier().getDisplay() + " is marked as required by is not present.");
        else {
            this.policyValue = PolicyValueFactory.getInstance("");
            return;
        }
    }
    final SubjectKeyIdentifier keyId = SubjectKeyIdentifier.getInstance(exValue);
    keyId.getKeyIdentifier();
    this.policyValue = PolicyValueFactory.getInstance(PolicyUtils.createByteStringRep(keyId.getKeyIdentifier()));
}
Also used : PolicyRequiredException(org.nhindirect.policy.PolicyRequiredException) DERObject(org.bouncycastle.asn1.DERObject) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier)

Example 10 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project zaproxy by zaproxy.

the class SslCertificateServiceImpl method createCertForHost.

@Override
public KeyStore createCertForHost(String hostname) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
    if (hostname == null) {
        throw new IllegalArgumentException("Error, 'hostname' is not allowed to be null!");
    }
    if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
        throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
    }
    final KeyPair mykp = this.createKeyPair();
    final PrivateKey privKey = mykp.getPrivate();
    final PublicKey pubKey = mykp.getPublic();
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, hostname);
    namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
    namebld.addRDN(BCStyle.O, "OWASP");
    namebld.addRDN(BCStyle.C, "xx");
    namebld.addRDN(BCStyle.EmailAddress, "owasp-zed-attack-proxy@lists.owasp.org");
    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + 100 * (1000L * 60 * 60 * 24 * 30)), namebld.build(), pubKey);
    certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
    certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
    certGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.dNSName, hostname)));
    ContentSigner sigGen;
    try {
        sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
    } catch (OperatorCreationException e) {
        throw new CertificateException(e);
    }
    final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(caPubKey);
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    final Certificate[] chain = new Certificate[2];
    chain[1] = this.caCert;
    chain[0] = cert;
    ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
    return ks;
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateException(java.security.cert.CertificateException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

SubjectKeyIdentifier (org.bouncycastle.asn1.x509.SubjectKeyIdentifier)34 AuthorityKeyIdentifier (org.bouncycastle.asn1.x509.AuthorityKeyIdentifier)17 X509Certificate (java.security.cert.X509Certificate)14 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)14 IOException (java.io.IOException)12 X500Name (org.bouncycastle.asn1.x500.X500Name)10 GeneralName (org.bouncycastle.asn1.x509.GeneralName)10 ContentSigner (org.bouncycastle.operator.ContentSigner)10 BigInteger (java.math.BigInteger)9 Date (java.util.Date)9 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)9 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)9 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)8 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)8 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)8 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)7 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 CertificateException (java.security.cert.CertificateException)6