Search in sources :

Example 51 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project ref-GemLibPki by gematik.

the class TspInformationProvider method verifyAkiMatchesSki.

/**
 * Verify AKI (authority key identifier - an X.509 v3 certificate extension - derived from the public key of the given issuer certificate) must match with
 * SKI (subject key identifier - an X.509 v3 certificate extension - derived from the public key of the given end-entity certificate).
 *
 * @param x509EeCert     end-entity certificate
 * @param x509IssuerCert issuer certificate determined from TSL file
 * @return true when aki matches ski otherwise false
 */
private static boolean verifyAkiMatchesSki(final X509Certificate x509EeCert, @NonNull final X509Certificate x509IssuerCert) {
    final byte[] subjectKeyIdentifier = x509IssuerCert.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    final Optional<ASN1OctetString> skiAsOctet = Optional.ofNullable(ASN1OctetString.getInstance(subjectKeyIdentifier));
    if (skiAsOctet.isEmpty()) {
        log.debug("Extension SUBJECT_KEY_IDENTIFIER_OID: {} konnte in {} nicht gefunden werden.", Extension.subjectKeyIdentifier.getId(), x509EeCert.getSubjectX500Principal());
        return false;
    }
    final SubjectKeyIdentifier subKeyIdentifier = SubjectKeyIdentifier.getInstance(skiAsOctet.get().getOctets());
    final byte[] authorityKeyIdentifier = x509EeCert.getExtensionValue(Extension.authorityKeyIdentifier.getId());
    final Optional<ASN1OctetString> akiAsOctet = Optional.ofNullable(ASN1OctetString.getInstance(authorityKeyIdentifier));
    if (akiAsOctet.isEmpty()) {
        log.debug("Extension AUTHORITY_KEY_IDENTIFIER_OID: {} konnte in {} nicht gefunden werden.", Extension.authorityKeyIdentifier.getId(), x509EeCert.getSubjectX500Principal());
        return false;
    }
    final ASN1Primitive akiSequenceAsOctet;
    try {
        akiSequenceAsOctet = ASN1Primitive.fromByteArray(akiAsOctet.get().getOctets());
    } catch (final IOException e) {
        log.debug("Octets des AUTHORITY_KEY_IDENTIFIER konnten in {} nicht gefunden werden.", x509EeCert.getSubjectX500Principal());
        log.trace(e.toString());
        return false;
    }
    final AuthorityKeyIdentifier authKeyIdentifier = AuthorityKeyIdentifier.getInstance(akiSequenceAsOctet);
    return Arrays.equals(subKeyIdentifier.getKeyIdentifier(), authKeyIdentifier.getKeyIdentifier());
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) IOException(java.io.IOException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 52 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project kas-fleetshard by bf2fc6cc711aee1a0c2a.

the class SecurityUtils method generate.

private static X509Certificate generate(final KeyPair keyPair, final String hashAlgorithm, final String domain, final int days) throws OperatorCreationException, CertificateException, CertIOException {
    final Instant now = Instant.now();
    final Date notBefore = Date.from(now);
    final Date notAfter = Date.from(now.plus(Duration.ofDays(days)));
    final X500Name x500Issuer = new X500Name("CN=" + domain);
    final X500Name x500Name = new X500Name("CN=*." + domain);
    final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    final DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
    final SubjectKeyIdentifier subject = new X509ExtensionUtils(digCalc).createSubjectKeyIdentifier(publicKeyInfo);
    final AuthorityKeyIdentifier authority = new X509ExtensionUtils(digCalc).createAuthorityKeyIdentifier(publicKeyInfo);
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(x500Issuer, BigInteger.valueOf(now.toEpochMilli()), notBefore, notAfter, x500Name, keyPair.getPublic());
    certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, subject);
    certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, authority);
    certificateBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    final ContentSigner contentSigner = new JcaContentSignerBuilder(hashAlgorithm).build(keyPair.getPrivate());
    return new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(certificateBuilder.build(contentSigner));
}
Also used : BcDigestCalculatorProvider(org.bouncycastle.operator.bc.BcDigestCalculatorProvider) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Instant(java.time.Instant) DigestCalculator(org.bouncycastle.operator.DigestCalculator) ContentSigner(org.bouncycastle.operator.ContentSigner) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) X500Name(org.bouncycastle.asn1.x500.X500Name) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) SubjectPublicKeyInfo(org.bouncycastle.asn1.x509.SubjectPublicKeyInfo) Date(java.util.Date) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509ExtensionUtils(org.bouncycastle.cert.X509ExtensionUtils) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 53 with SubjectKeyIdentifier

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

the class BurpCertificateBuilder method generateX509Certificate.

/**
 * Creates a X.509v3 Certificate. The values of "this" object are used for
 * the building process.
 *
 * @param privateKey
 *            which signes the certificates
 * @return certificate object
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchAlgorithmException
 * @throws SignatureException
 * @throws IOException
 */
private X509Certificate generateX509Certificate(PrivateKey privateKey) throws CertificateEncodingException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, IOException {
    if (version != 3) {
        throw new UnsupportedOperationException("Not implemented yet.");
    }
    certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.setSerialNumber(serial);
    certificateGenerator.setIssuerDN(this.issuer);
    certificateGenerator.setNotBefore(notBefore);
    certificateGenerator.setNotAfter(notAfter);
    certificateGenerator.setSubjectDN(subject);
    certificateGenerator.setSignatureAlgorithm(signatureAlgorithm);
    certificateGenerator.setPublicKey(publicKey);
    if (hasBasicConstraints) {
        if (isCA && hasNoPathLimit) {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
        } else if (isCA && !hasNoPathLimit) {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(pathLimit));
        } else {
            certificateGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        }
    }
    if (keyUsage.size() > 0) {
        int allKeyUsages = 0;
        for (int i : keyUsage) {
            allKeyUsages |= i;
        }
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(allKeyUsages));
    }
    if (extendedKeyUsage.size() > 0) {
        ASN1EncodableVector allExtendedKeyUsages = new ASN1EncodableVector();
        for (KeyPurposeId i : extendedKeyUsage) {
            allExtendedKeyUsages.add(i);
        }
        certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(allExtendedKeyUsages));
    }
    if (subjectAlternativeName.size() > 0) {
        GeneralNames generalNames = new GeneralNames(subjectAlternativeName.toArray(new GeneralName[subjectAlternativeName.size()]));
        certificateGenerator.addExtension(X509Extensions.SubjectAlternativeName, true, generalNames);
    }
    if (setSubjectKeyIdentifier == true) {
        JcaX509ExtensionUtils j = new JcaX509ExtensionUtils();
        certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, j.createSubjectKeyIdentifier(publicKey));
    }
    if (!subjectKeyIdentifier.isEmpty() && setSubjectKeyIdentifier == false) {
        byte[] ski = CertificateHelper.hexStringToByteArray(subjectKeyIdentifier);
        SubjectKeyIdentifier aKI = new SubjectKeyIdentifier(ski);
        certificateGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, true, aKI);
    }
    if (issuerAlternativeName.size() > 0) {
        GeneralNames generalNames = new GeneralNames(issuerAlternativeName.toArray(new GeneralName[issuerAlternativeName.size()]));
        certificateGenerator.addExtension(X509Extensions.IssuerAlternativeName, true, generalNames);
    }
    if (setAuthorityKeyIdentifier == true && issuerCertificate != null) {
        JcaX509ExtensionUtils j = new JcaX509ExtensionUtils();
        certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, true, j.createAuthorityKeyIdentifier(issuerCertificate));
    }
    if (!authorityKeyIdentifier.isEmpty() && setAuthorityKeyIdentifier == false) {
        byte[] aki = CertificateHelper.hexStringToByteArray(authorityKeyIdentifier);
        AuthorityKeyIdentifier aKI = new AuthorityKeyIdentifier(aki);
        certificateGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, true, aKI);
    }
    for (BurpCertificateExtension e : burpCertificateExtensions) {
        // http://bouncycastle.sourcearchive.com/documentation/1.43/classorg_1_1bouncycastle_1_1x509_1_1X509V3CertificateGenerator_fd5118a4eaa4870e5fbf6efc02f10c00.html#fd5118a4eaa4870e5fbf6efc02f10c00
        // Finally!!!
        ASN1Encodable extension = X509ExtensionUtil.fromExtensionValue(e.getExtensionValue());
        certificateGenerator.addExtension(e.getOid(), e.isCritical(), extension);
    }
    return certificateGenerator.generate(privateKey);
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) X509V3CertificateGenerator(org.bouncycastle.x509.X509V3CertificateGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) BurpCertificateExtension(model.BurpCertificateExtension) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) GeneralName(org.bouncycastle.asn1.x509.GeneralName) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Example 54 with SubjectKeyIdentifier

use of com.github.zhenwei.core.asn1.x509.SubjectKeyIdentifier in project IDS-Messaging-Services by International-Data-Spaces-Association.

the class OrbiterTokenManagerService method createCSR.

/**
 * Generate a CSR which is sent to the Orbiter DAPS to register a Client.
 *
 * @return a generated CSR
 * @throws OperatorCreationException when the ContentSigner
 * cannot be created
 * @throws IOException when the Extensions cannot be added to the CSR
 */
private PKCS10CertificationRequest createCSR() throws IOException, OperatorCreationException {
    // create csr builder with principal
    final var p10Builder = new JcaPKCS10CertificationRequestBuilder(new X500Principal("C=DE, ST=Bonn, L=NRW, O=truzzt, CN=*.truzzt.org"), generatedKeyPair.getPublic());
    // add extensions
    final var extensionsGenerator = new ExtensionsGenerator();
    // basic constraints = false
    extensionsGenerator.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
    // add subject alternative names
    final var sans = new ASN1Encodable[] { new GeneralName(GeneralName.dNSName, "*.truzzt.org"), new GeneralName(GeneralName.dNSName, "*.truzzt.com") };
    final var sansExtension = new DERSequence(sans);
    extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, sansExtension);
    // TODO add SKI extension but currently working without it)
    // extensionsGenerator.addExtension(Extension.subjectKeyIdentifier,
    // true, new SubjectKeyIdentifier());
    final var extensions = extensionsGenerator.generate();
    p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions);
    // create csBuilder for signing the request
    final var csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
    final var signer = csBuilder.build(generatedKeyPair.getPrivate());
    // build and return the csr
    return p10Builder.build(signer);
}
Also used : JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) DERSequence(org.bouncycastle.asn1.DERSequence) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) X500Principal(javax.security.auth.x500.X500Principal) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtensionsGenerator(org.bouncycastle.asn1.x509.ExtensionsGenerator)

Example 55 with SubjectKeyIdentifier

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

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)

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