Search in sources :

Example 1 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project solarnetwork-node by SolarNetwork.

the class PKITestUtils method generateNewCACert.

public static X509Certificate generateNewCACert(PublicKey publicKey, String subject, X509Certificate issuer, PrivateKey issuerKey, String caDN) throws Exception {
    final X500Name issuerDn = (issuer == null ? new X500Name(subject) : JcaX500NameUtil.getSubject(issuer));
    final X500Name subjectDn = new X500Name(subject);
    final BigInteger serial = getNextSerialNumber();
    final Date notBefore = new Date();
    final Date notAfter = new Date(System.currentTimeMillis() + 1000L * 60L * 60L);
    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerDn, serial, notBefore, notAfter, subjectDn, publicKey);
    // add "CA" extension
    BasicConstraints basicConstraints;
    if (issuer == null) {
        basicConstraints = new BasicConstraints(true);
    } else {
        int issuerPathLength = issuer.getBasicConstraints();
        basicConstraints = new BasicConstraints(issuerPathLength - 1);
    }
    builder.addExtension(X509Extension.basicConstraints, true, basicConstraints);
    // add subjectKeyIdentifier
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    SubjectKeyIdentifier ski = utils.createSubjectKeyIdentifier(publicKey);
    builder.addExtension(X509Extension.subjectKeyIdentifier, false, ski);
    // add authorityKeyIdentifier
    GeneralNames issuerName = new GeneralNames(new GeneralName(GeneralName.directoryName, caDN));
    AuthorityKeyIdentifier aki = utils.createAuthorityKeyIdentifier(publicKey);
    aki = new AuthorityKeyIdentifier(aki.getKeyIdentifier(), issuerName, serial);
    builder.addExtension(X509Extension.authorityKeyIdentifier, false, aki);
    // add keyUsage
    X509KeyUsage keyUsage = new X509KeyUsage(X509KeyUsage.cRLSign | X509KeyUsage.digitalSignature | X509KeyUsage.keyCertSign | X509KeyUsage.nonRepudiation);
    builder.addExtension(X509Extension.keyUsage, true, keyUsage);
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSA");
    ContentSigner signer = signerBuilder.build(issuerKey);
    X509CertificateHolder holder = builder.build(signer);
    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    return converter.getCertificate(holder);
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) Date(java.util.Date) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509KeyUsage(org.bouncycastle.jce.X509KeyUsage)

Example 2 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project ca3sCore by kuehne-trustable-de.

the class CertificateUtilIntTest method testAKIandSKIGeneration.

@Test
public void testAKIandSKIGeneration() throws GeneralSecurityException {
    X509Certificate x509Cert = CryptoUtil.convertPemToCertificate(testCert);
    assertNotNull(x509Cert);
    JcaX509ExtensionUtils util = new JcaX509ExtensionUtils();
    SubjectKeyIdentifier ski = util.createSubjectKeyIdentifier(x509Cert.getPublicKey());
    String b46Ski = Base64.encodeBase64String(ski.getKeyIdentifier());
    assertNotNull(b46Ski);
    AuthorityKeyIdentifier aki = util.createAuthorityKeyIdentifier(x509Cert.getPublicKey());
    String b46Aki = Base64.encodeBase64String(aki.getKeyIdentifier());
    assertNotNull(b46Aki);
    assertEquals(b46Ski, b46Aki);
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 3 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project identity-credential by google.

the class CertificateGenerator method generateCertificate.

static X509Certificate generateCertificate(DataMaterial data, CertificateMaterial certMaterial, KeyMaterial keyMaterial) throws CertIOException, CertificateException, OperatorCreationException {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    Optional<X509Certificate> issuerCert = keyMaterial.issuerCertificate();
    X500Name subjectDN = new X500Name(data.subjectDN());
    // doesn't work, get's reordered
    // issuerCert.isPresent() ? new X500Name(issuerCert.get().getSubjectX500Principal().getName()) : subjectDN;
    X500Name issuerDN = new X500Name(data.issuerDN());
    ContentSigner contentSigner = new JcaContentSignerBuilder(keyMaterial.signingAlgorithm()).build(keyMaterial.signingKey());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, certMaterial.serialNumber(), certMaterial.startDate(), certMaterial.endDate(), subjectDN, keyMaterial.publicKey());
    // Extensions --------------------------
    JcaX509ExtensionUtils jcaX509ExtensionUtils;
    try {
        jcaX509ExtensionUtils = new JcaX509ExtensionUtils();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    if (issuerCert.isPresent()) {
        try {
            // adds 3 more fields, not present in other cert
            // AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert.get());
            AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCert.get().getPublicKey());
            certBuilder.addExtension(Extension.authorityKeyIdentifier, NOT_CRITICAL, authorityKeyIdentifier);
        } catch (IOException e) {
            // CertificateEncodingException |
            throw new RuntimeException(e);
        }
    }
    SubjectKeyIdentifier subjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyMaterial.publicKey());
    certBuilder.addExtension(Extension.subjectKeyIdentifier, NOT_CRITICAL, subjectKeyIdentifier);
    KeyUsage keyUsage = new KeyUsage(certMaterial.keyUsage());
    certBuilder.addExtension(Extension.keyUsage, CRITICAL, keyUsage);
    // IssuerAlternativeName
    Optional<String> issuerAlternativeName = data.issuerAlternativeName();
    if (issuerAlternativeName.isPresent()) {
        GeneralNames issuerAltName = new GeneralNames(new GeneralName(GeneralName.uniformResourceIdentifier, issuerAlternativeName.get()));
        certBuilder.addExtension(Extension.issuerAlternativeName, NOT_CRITICAL, issuerAltName);
    }
    // Basic Constraints
    int pathLengthConstraint = certMaterial.pathLengthConstraint();
    if (pathLengthConstraint != CertificateMaterial.PATHLENGTH_NOT_A_CA) {
        // TODO doesn't work for certificate chains != 2 in size
        BasicConstraints basicConstraints = new BasicConstraints(pathLengthConstraint);
        certBuilder.addExtension(Extension.basicConstraints, CRITICAL, basicConstraints);
    }
    Optional<String> extendedKeyUsage = certMaterial.extendedKeyUsage();
    if (extendedKeyUsage.isPresent()) {
        KeyPurposeId keyPurpose = KeyPurposeId.getInstance(new ASN1ObjectIdentifier(extendedKeyUsage.get()));
        ExtendedKeyUsage extKeyUsage = new ExtendedKeyUsage(new KeyPurposeId[] { keyPurpose });
        certBuilder.addExtension(Extension.extendedKeyUsage, CRITICAL, extKeyUsage);
    }
    // DEBUG setProvider(bcProvider) removed before getCertificate
    return new JcaX509CertificateConverter().getCertificate(certBuilder.build(contentSigner));
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) ContentSigner(org.bouncycastle.operator.ContentSigner) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Provider(java.security.Provider) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 4 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.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 5 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.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)

Aggregations

SubjectKeyIdentifier (org.bouncycastle.asn1.x509.SubjectKeyIdentifier)34 AuthorityKeyIdentifier (org.bouncycastle.asn1.x509.AuthorityKeyIdentifier)14 X509Certificate (java.security.cert.X509Certificate)13 IOException (java.io.IOException)10 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)10 X500Name (org.bouncycastle.asn1.x500.X500Name)9 JcaX509ExtensionUtils (org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils)9 GeneralName (org.bouncycastle.asn1.x509.GeneralName)8 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)8 Date (java.util.Date)7 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)7 ContentSigner (org.bouncycastle.operator.ContentSigner)7 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)7 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)6 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)6 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)6 PrivateKey (java.security.PrivateKey)5 CertificateException (java.security.cert.CertificateException)5 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)5