Search in sources :

Example 16 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project credhub by cloudfoundry-incubator.

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 17 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project credhub by cloudfoundry-incubator.

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 18 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project vcert-java by Venafi.

the class PEMCollection method toPkcs12.

public byte[] toPkcs12(String password) throws PKCSException {
    try {
        SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(certificate.getPublicKey());
        OutputEncryptor encOut = new JcePKCSPBEOutputEncryptorBuilder(NISTObjectIdentifiers.id_aes128_CBC).setProvider("BC").build(password.toCharArray());
        ArrayList<PKCS12SafeBag> safeBags = new ArrayList<>();
        safeBags.ensureCapacity(chain.size() + 2);
        safeBags.add(new JcaPKCS12SafeBagBuilder((X509Certificate) certificate).addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId).build());
        for (Certificate intermediateCert : chain) {
            safeBags.add(new JcaPKCS12SafeBagBuilder((X509Certificate) intermediateCert).build());
        }
        safeBags.add(new JcaPKCS12SafeBagBuilder(privateKey, encOut).addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId).build());
        PKCS12PfxPduBuilder builder = new PKCS12PfxPduBuilder();
        builder.addEncryptedData(new JcePKCSPBEOutputEncryptorBuilder(PKCSObjectIdentifiers.pbeWithSHAAnd128BitRC2_CBC).setProvider("BC").build(password.toCharArray()), safeBags.toArray(new PKCS12SafeBag[] {}));
        PKCS12PfxPdu pfx = builder.build(new JcePKCS12MacCalculatorBuilder(NISTObjectIdentifiers.id_sha256), password.toCharArray());
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        out.write(pfx.getEncoded(ASN1Encoding.DL));
        out.close();
        return out.toByteArray();
    } catch (IOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new RuntimeException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) ArrayList(java.util.ArrayList) JcePKCSPBEOutputEncryptorBuilder(org.bouncycastle.pkcs.jcajce.JcePKCSPBEOutputEncryptorBuilder) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) X509Certificate(java.security.cert.X509Certificate) JcePKCS12MacCalculatorBuilder(org.bouncycastle.pkcs.jcajce.JcePKCS12MacCalculatorBuilder) PKCS12SafeBag(org.bouncycastle.pkcs.PKCS12SafeBag) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) PKCS12PfxPdu(org.bouncycastle.pkcs.PKCS12PfxPdu) OutputEncryptor(org.bouncycastle.operator.OutputEncryptor) JcaPKCS12SafeBagBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS12SafeBagBuilder) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) PKCS12PfxPduBuilder(org.bouncycastle.pkcs.PKCS12PfxPduBuilder)

Example 19 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project keystore-explorer by kaikramer.

the class X509Ext method getSubjectKeyIndentifierStringValue.

private static String getSubjectKeyIndentifierStringValue(byte[] value) throws IOException {
    // @formatter:off
    /*
		 * SubjectKeyIdentifier ::= KeyIdentifier
		 *
		 * KeyIdentifier ::= OCTET STRING
		 */
    // @formatter:on
    StringBuilder sb = new StringBuilder();
    SubjectKeyIdentifier subjectKeyIdentifier = SubjectKeyIdentifier.getInstance(value);
    // Get key identifier from octet string
    byte[] keyIdentifierBytes = subjectKeyIdentifier.getKeyIdentifier();
    sb.append(MessageFormat.format(res.getString("SubjectKeyIdentifier"), HexUtil.getHexString(keyIdentifierBytes)));
    sb.append(NEWLINE);
    return sb.toString();
}
Also used : SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier)

Example 20 with SubjectKeyIdentifier

use of com.beanit.asn1bean.compiler.pkix1implicit88.SubjectKeyIdentifier in project jruby-openssl by jruby.

the class X509Utils method checkIfIssuedBy.

/*
     * c: X509_check_issued + x509_likely_issued + x509_signing_allowed
     */
static int checkIfIssuedBy(final X509AuxCertificate issuer, final X509AuxCertificate subject) throws IOException {
    if (!issuer.getSubjectX500Principal().equals(subject.getIssuerX500Principal())) {
        return V_ERR_SUBJECT_ISSUER_MISMATCH;
    }
    if (subject.getExtensionValue("2.5.29.35") != null) {
        // authorityKeyID
        // I hate ASN1 and DER
        Object key = get(subject.getExtensionValue("2.5.29.35"));
        if (!(key instanceof ASN1Sequence))
            key = get((DEROctetString) key);
        final ASN1Sequence seq = (ASN1Sequence) key;
        final AuthorityKeyIdentifier sakid;
        if (seq.size() == 1 && (seq.getObjectAt(0) instanceof ASN1OctetString)) {
            sakid = AuthorityKeyIdentifier.getInstance(new DLSequence(new DERTaggedObject(0, seq.getObjectAt(0))));
        } else {
            sakid = AuthorityKeyIdentifier.getInstance(seq);
        }
        if (sakid.getKeyIdentifier() != null) {
            if (issuer.getExtensionValue("2.5.29.14") != null) {
                DEROctetString der = (DEROctetString) get(issuer.getExtensionValue("2.5.29.14"));
                SubjectKeyIdentifier iskid = SubjectKeyIdentifier.getInstance(get(der.getOctets()));
                if (iskid.getKeyIdentifier() != null) {
                    if (!Arrays.equals(sakid.getKeyIdentifier(), iskid.getKeyIdentifier())) {
                        return V_ERR_AKID_SKID_MISMATCH;
                    }
                }
            }
        }
        final BigInteger serialNumber = sakid.getAuthorityCertSerialNumber();
        if (serialNumber != null && !serialNumber.equals(issuer.getSerialNumber())) {
            return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
        }
        if (sakid.getAuthorityCertIssuer() != null) {
            GeneralName[] gens = sakid.getAuthorityCertIssuer().getNames();
            X500Name x500Name = null;
            for (int i = 0; i < gens.length; i++) {
                if (gens[i].getTagNo() == GeneralName.directoryName) {
                    ASN1Encodable name = gens[i].getName();
                    if (name instanceof X500Name) {
                        x500Name = (X500Name) name;
                    } else if (name instanceof ASN1Sequence) {
                        x500Name = X500Name.getInstance((ASN1Sequence) name);
                    } else {
                        throw new RuntimeException("unknown name type: " + name);
                    }
                    break;
                }
            }
            if (x500Name != null) {
                if (!new Name(x500Name).equalTo(issuer.getIssuerX500Principal())) {
                    return V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
                }
            }
        }
    }
    final boolean[] keyUsage = issuer.getKeyUsage();
    if (subject.getExtensionValue("1.3.6.1.5.5.7.1.14") != null) {
        if (keyUsage != null && !keyUsage[0]) {
            // KU_DIGITAL_SIGNATURE
            return V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
        }
    } else if (keyUsage != null && !keyUsage[5]) {
        // KU_KEY_CERT_SIGN
        return V_ERR_KEYUSAGE_NO_CERTSIGN;
    }
    return V_OK;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) DEROctetString(org.bouncycastle.asn1.DEROctetString) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X500Name(org.bouncycastle.asn1.x500.X500Name) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DLSequence(org.bouncycastle.asn1.DLSequence) BigInteger(java.math.BigInteger) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable)

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