Search in sources :

Example 36 with AuthorityKeyIdentifier

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

the class PKCS12KeyStoreSpi 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(Extension.authorityKeyIdentifier.getId());
            if (bytes != null) {
                try {
                    ASN1InputStream aIn = new ASN1InputStream(bytes);
                    byte[] authBytes = ((ASN1OctetString) aIn.readObject()).getOctets();
                    aIn = new ASN1InputStream(authBytes);
                    AuthorityKeyIdentifier id = AuthorityKeyIdentifier.getInstance(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)

Example 37 with AuthorityKeyIdentifier

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

the class AuthorityKeyIdentifierKeyIdExtensionField 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 AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(exValue);
    byte[] keyId = aki.getKeyIdentifier();
    ///CLOVER:OFF
    if (keyId == null) {
        if (isRequired())
            throw new PolicyRequiredException("Extention " + getExtentionIdentifier().getDisplay() + " is marked as required by is not present.");
        else {
            this.policyValue = PolicyValueFactory.getInstance("");
            return;
        }
    }
    ///CLOVER:ON
    this.policyValue = PolicyValueFactory.getInstance(PolicyUtils.createByteStringRep(keyId));
}
Also used : PolicyRequiredException(org.nhindirect.policy.PolicyRequiredException) DERObject(org.bouncycastle.asn1.DERObject) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier)

Example 38 with AuthorityKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.AuthorityKeyIdentifier in project poi by apache.

the class PkiTestUtils method generateCertificate.

static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore, Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag, int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage) throws IOException, OperatorCreationException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X500Name issuerName;
    if (issuerCertificate != null) {
        issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer();
    } else {
        issuerName = new X500Name(subjectDn);
    }
    RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey;
    RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(), rsaPubKey.getPublicExponent());
    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec);
    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build().get(CertificateID.HASH_SHA1);
    X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName, new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn), subjectPublicKeyInfo);
    X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc);
    SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
    AuthorityKeyIdentifier autKeyId = (issuerCertificate != null) ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded())) : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo);
    certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId);
    certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId);
    if (caFlag) {
        BasicConstraints bc;
        if (-1 == pathLength) {
            bc = new BasicConstraints(true);
        } else {
            bc = new BasicConstraints(pathLength);
        }
        certificateGenerator.addExtension(Extension.basicConstraints, false, bc);
    }
    if (null != crlUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        DERIA5String crlUriDer = new DERIA5String(crlUri);
        GeneralName gn = new GeneralName(uri, crlUriDer);
        DERSequence gnDer = new DERSequence(gn);
        GeneralNames gns = GeneralNames.getInstance(gnDer);
        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        DERSequence distpDer = new DERSequence(distp);
        certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer);
    }
    if (null != ocspUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        GeneralName ocspName = new GeneralName(uri, ocspUri);
        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(X509ObjectIdentifiers.ocspAccessMethod, ocspName);
        certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }
    if (null != keyUsage) {
        certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage);
    }
    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);
    signerBuilder.setProvider("BC");
    X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey));
    //                        .getEncoded()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
Also used : AuthorityInformationAccess(org.bouncycastle.asn1.x509.AuthorityInformationAccess) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) DigestCalculator(org.bouncycastle.operator.DigestCalculator) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERSequence(org.bouncycastle.asn1.DERSequence) RSAPublicKey(java.security.interfaces.RSAPublicKey) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) DistributionPointName(org.bouncycastle.asn1.x509.DistributionPointName) SecureRandom(java.security.SecureRandom) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) JcaDigestCalculatorProviderBuilder(org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 39 with AuthorityKeyIdentifier

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

the class SignedCertificateGenerator method getSignedByIssuer.

private X509Certificate getSignedByIssuer(X509Certificate issuerCertificate, PrivateKey issuerKey, X500Principal issuerDn, SubjectKeyIdentifier caSubjectKeyIdentifier, KeyPair keyPair, CertificateGenerationParameters params) throws Exception {
    Instant now = timeProvider.getNow().toInstant();
    BigInteger certificateSerialNumber = serialNumberGenerator.generate();
    BigInteger caSerialNumber = issuerCertificate != null ? issuerCertificate.getSerialNumber() : certificateSerialNumber;
    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) {
        PublicKey issuerPublicKey = issuerCertificate != null ? issuerCertificate.getPublicKey() : keyPair.getPublic();
        AuthorityKeyIdentifier authorityKeyIdentifier = jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerPublicKey, issuerDn, caSerialNumber);
        certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);
    }
    certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(params.isCa()));
    ContentSigner contentSigner = jcaContentSignerBuilder.build(issuerKey);
    X509CertificateHolder holder = certificateBuilder.build(contentSigner);
    return jcaX509CertificateConverter.getCertificate(holder);
}
Also used : PublicKey(java.security.PublicKey) 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 40 with AuthorityKeyIdentifier

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

the class SignedCertificateGeneratorTest method getSelfSigned_generatesACertificateWithTheRightValues.

@Test
public void getSelfSigned_generatesACertificateWithTheRightValues() throws Exception {
    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());
    byte[] authorityKeyIdDer = generatedCertificate.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    AuthorityKeyIdentifier authorityKeyIdentifier = AuthorityKeyIdentifier.getInstance(parseExtensionValue(authorityKeyIdDer));
    byte[] authorityKeyId = authorityKeyIdentifier.getKeyIdentifier();
    expectedSubjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(generatedCertificateKeyPair.getPublic()).getKeyIdentifier();
    assertThat(authorityKeyId, equalTo(expectedSubjectKeyIdentifier));
    assertThat(generatedCertificate.getSerialNumber(), equalTo(BigInteger.valueOf(1337)));
    assertThat(authorityKeyIdentifier.getAuthorityCertSerialNumber(), equalTo(BigInteger.valueOf(1337)));
}
Also used : AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

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