Example usage for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier

List of usage examples for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier.

Prototype

ASN1ObjectIdentifier subjectKeyIdentifier

To view the source code for org.bouncycastle.asn1.x509 Extension subjectKeyIdentifier.

Click Source Link

Document

Subject Key Identifier

Usage

From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java

License:Open Source License

private Set<ASN1ObjectIdentifier> getExensionTypes(final Certificate cert, final X509IssuerInfo issuerInfo,
        final Extensions requestedExtensions) {
    Set<ASN1ObjectIdentifier> types = new HashSet<>();
    // profile required extension types
    Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls();
    for (ASN1ObjectIdentifier oid : extensionControls.keySet()) {
        if (extensionControls.get(oid).isRequired()) {
            types.add(oid);//from   ww  w .j  a va2 s .  co m
        }
    }

    Set<ASN1ObjectIdentifier> wantedExtensionTypes = new HashSet<>();

    if (requestedExtensions != null) {
        Extension reqExtension = requestedExtensions
                .getExtension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions);
        if (reqExtension != null) {
            ExtensionExistence ee = ExtensionExistence.getInstance(reqExtension.getParsedValue());
            types.addAll(ee.getNeedExtensions());
            wantedExtensionTypes.addAll(ee.getWantExtensions());
        }
    }

    if (CollectionUtil.isEmpty(wantedExtensionTypes)) {
        return types;
    }

    // wanted extension types
    // Authority key identifier
    ASN1ObjectIdentifier type = Extension.authorityKeyIdentifier;
    if (wantedExtensionTypes.contains(type)) {
        types.add(type);
    }

    // Subject key identifier
    type = Extension.subjectKeyIdentifier;
    if (wantedExtensionTypes.contains(type)) {
        types.add(type);
    }

    // KeyUsage
    type = Extension.keyUsage;
    if (wantedExtensionTypes.contains(type)) {
        boolean required = false;
        if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) {
            required = true;
        }

        if (!required) {
            Set<KeyUsageControl> requiredKeyusage = getKeyusage(true);
            if (CollectionUtil.isNonEmpty(requiredKeyusage)) {
                required = true;
            }
        }

        if (required) {
            types.add(type);
        }
    }

    // CertificatePolicies
    type = Extension.certificatePolicies;
    if (wantedExtensionTypes.contains(type)) {
        if (certificatePolicies != null) {
            types.add(type);
        }
    }

    // Policy Mappings
    type = Extension.policyMappings;
    if (wantedExtensionTypes.contains(type)) {
        if (policyMappings != null) {
            types.add(type);
        }
    }

    // SubjectAltNames
    type = Extension.subjectAlternativeName;
    if (wantedExtensionTypes.contains(type)) {
        if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) {
            types.add(type);
        }
    }

    // IssuerAltName
    type = Extension.issuerAlternativeName;
    if (wantedExtensionTypes.contains(type)) {
        if (cert.getTBSCertificate().getExtensions().getExtension(Extension.subjectAlternativeName) != null) {
            types.add(type);
        }
    }

    // BasicConstraints
    type = Extension.basicConstraints;
    if (wantedExtensionTypes.contains(type)) {
        types.add(type);
    }

    // Name Constraints
    type = Extension.nameConstraints;
    if (wantedExtensionTypes.contains(type)) {
        if (nameConstraints != null) {
            types.add(type);
        }
    }

    // PolicyConstrains
    type = Extension.policyConstraints;
    if (wantedExtensionTypes.contains(type)) {
        if (policyConstraints != null) {
            types.add(type);
        }
    }

    // ExtendedKeyUsage
    type = Extension.extendedKeyUsage;
    if (wantedExtensionTypes.contains(type)) {
        boolean required = false;
        if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) {
            required = true;
        }

        if (!required) {
            Set<ExtKeyUsageControl> requiredExtKeyusage = getExtKeyusage(true);
            if (CollectionUtil.isNonEmpty(requiredExtKeyusage)) {
                required = true;
            }
        }

        if (required) {
            types.add(type);
        }
    }

    // CRLDistributionPoints
    type = Extension.cRLDistributionPoints;
    if (wantedExtensionTypes.contains(type)) {
        if (issuerInfo.getCrlUrls() != null) {
            types.add(type);
        }
    }

    // Inhibit anyPolicy
    type = Extension.inhibitAnyPolicy;
    if (wantedExtensionTypes.contains(type)) {
        if (inhibitAnyPolicy != null) {
            types.add(type);
        }
    }

    // FreshestCRL
    type = Extension.freshestCRL;
    if (wantedExtensionTypes.contains(type)) {
        if (issuerInfo.getDeltaCrlUrls() != null) {
            types.add(type);
        }
    }

    // AuthorityInfoAccess
    type = Extension.authorityInfoAccess;
    if (wantedExtensionTypes.contains(type)) {
        if (issuerInfo.getOcspUrls() != null) {
            types.add(type);
        }
    }

    // SubjectInfoAccess
    type = Extension.subjectInfoAccess;
    if (wantedExtensionTypes.contains(type)) {
        if (requestedExtensions != null && requestedExtensions.getExtension(type) != null) {
            types.add(type);
        }
    }

    // Admission
    type = ObjectIdentifiers.id_extension_admission;
    if (wantedExtensionTypes.contains(type)) {
        if (certProfile.getAdmission() != null) {
            types.add(type);
        }
    }

    // ocsp-nocheck
    type = ObjectIdentifiers.id_extension_pkix_ocsp_nocheck;
    if (wantedExtensionTypes.contains(type)) {
        types.add(type);
    }

    wantedExtensionTypes.removeAll(types);

    for (ASN1ObjectIdentifier oid : wantedExtensionTypes) {
        if (requestedExtensions != null && requestedExtensions.getExtension(oid) != null) {
            if (constantExtensions.containsKey(oid)) {
                types.add(oid);
            }
        }
    }

    return types;
}

From source file:org.xipki.pki.ca.server.impl.IdentifiedX509Certprofile.java

License:Open Source License

public ExtensionValues getExtensions(@NonNull final X500Name requestedSubject,
        @NonNull final X500Name grantedSubject, @Nullable final Extensions requestedExtensions,
        @NonNull final SubjectPublicKeyInfo publicKeyInfo, @NonNull final PublicCaInfo publicCaInfo,
        @Nullable final X509Certificate crlSignerCert, @NonNull final Date notBefore,
        @NonNull final Date notAfter) throws CertprofileException, BadCertTemplateException {
    ParamUtil.requireNonNull("publicKeyInfo", publicKeyInfo);
    ExtensionValues values = new ExtensionValues();

    Map<ASN1ObjectIdentifier, ExtensionControl> controls = new HashMap<>(certprofile.getExtensionControls());

    Set<ASN1ObjectIdentifier> neededExtTypes = new HashSet<>();
    Set<ASN1ObjectIdentifier> wantedExtTypes = new HashSet<>();
    if (requestedExtensions != null) {
        Extension reqExtension = requestedExtensions
                .getExtension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions);
        if (reqExtension != null) {
            ExtensionExistence ee = ExtensionExistence.getInstance(reqExtension.getParsedValue());
            neededExtTypes.addAll(ee.getNeedExtensions());
            wantedExtTypes.addAll(ee.getWantExtensions());
        }/*from w  w w. j a va2s.  c o m*/

        for (ASN1ObjectIdentifier oid : neededExtTypes) {
            if (wantedExtTypes.contains(oid)) {
                wantedExtTypes.remove(oid);
            }

            if (!controls.containsKey(oid)) {
                throw new BadCertTemplateException("could not add needed extension " + oid.getId());
            }
        }
    }

    // SubjectKeyIdentifier
    ASN1ObjectIdentifier extType = Extension.subjectKeyIdentifier;
    ExtensionControl extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        byte[] encodedSpki = publicKeyInfo.getPublicKeyData().getBytes();
        byte[] skiValue = HashAlgoType.SHA1.hash(encodedSpki);
        SubjectKeyIdentifier value = new SubjectKeyIdentifier(skiValue);
        addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
    }

    // Authority key identifier
    extType = Extension.authorityKeyIdentifier;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        byte[] ikiValue = publicCaInfo.getSubjectKeyIdentifer();
        AuthorityKeyIdentifier value = null;
        if (ikiValue != null) {
            if (certprofile.includeIssuerAndSerialInAki()) {
                GeneralNames x509CaSubject = new GeneralNames(new GeneralName(publicCaInfo.getX500Subject()));
                value = new AuthorityKeyIdentifier(ikiValue, x509CaSubject, publicCaInfo.getSerialNumber());
            } else {
                value = new AuthorityKeyIdentifier(ikiValue);
            }
        }

        addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
    }

    // IssuerAltName
    extType = Extension.issuerAlternativeName;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        GeneralNames value = publicCaInfo.getSubjectAltName();
        addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
    }

    // AuthorityInfoAccess
    extType = Extension.authorityInfoAccess;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        AuthorityInfoAccessControl aiaControl = certprofile.getAiaControl();

        List<String> caIssuers = null;
        if (aiaControl == null || aiaControl.includesCaIssuers()) {
            caIssuers = publicCaInfo.getCaCertUris();
        }

        List<String> ocspUris = null;
        if (aiaControl == null || aiaControl.includesOcsp()) {
            ocspUris = publicCaInfo.getOcspUris();
        }

        if (CollectionUtil.isNonEmpty(caIssuers) || CollectionUtil.isNonEmpty(ocspUris)) {
            AuthorityInformationAccess value = CaUtil.createAuthorityInformationAccess(caIssuers, ocspUris);
            addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
        }
    }

    if (controls.containsKey(Extension.cRLDistributionPoints) || controls.containsKey(Extension.freshestCRL)) {
        X500Name crlSignerSubject = (crlSignerCert == null) ? null
                : X500Name.getInstance(crlSignerCert.getSubjectX500Principal().getEncoded());
        X500Name x500CaPrincipal = publicCaInfo.getX500Subject();

        // CRLDistributionPoints
        extType = Extension.cRLDistributionPoints;
        extControl = controls.remove(extType);
        if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
            if (CollectionUtil.isNonEmpty(publicCaInfo.getCrlUris())) {
                CRLDistPoint value = CaUtil.createCrlDistributionPoints(publicCaInfo.getCrlUris(),
                        x500CaPrincipal, crlSignerSubject);
                addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
            }
        }

        // FreshestCRL
        extType = Extension.freshestCRL;
        extControl = controls.remove(extType);
        if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
            if (CollectionUtil.isNonEmpty(publicCaInfo.getDeltaCrlUris())) {
                CRLDistPoint value = CaUtil.createCrlDistributionPoints(publicCaInfo.getDeltaCrlUris(),
                        x500CaPrincipal, crlSignerSubject);
                addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
            }
        }
    }

    // BasicConstraints
    extType = Extension.basicConstraints;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        BasicConstraints value = CaUtil.createBasicConstraints(certprofile.getCertLevel(),
                certprofile.getPathLenBasicConstraint());
        addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
    }

    // KeyUsage
    extType = Extension.keyUsage;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        Set<KeyUsage> usages = new HashSet<>();
        Set<KeyUsageControl> usageOccs = certprofile.getKeyUsage();
        for (KeyUsageControl k : usageOccs) {
            if (k.isRequired()) {
                usages.add(k.getKeyUsage());
            }
        }

        // the optional KeyUsage will only be set if requested explicitly
        if (requestedExtensions != null && extControl.isRequest()) {
            addRequestedKeyusage(usages, requestedExtensions, usageOccs);
        }

        org.bouncycastle.asn1.x509.KeyUsage value = X509Util.createKeyUsage(usages);
        addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
    }

    // ExtendedKeyUsage
    extType = Extension.extendedKeyUsage;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        List<ASN1ObjectIdentifier> usages = new LinkedList<>();
        Set<ExtKeyUsageControl> usageOccs = certprofile.getExtendedKeyUsages();
        for (ExtKeyUsageControl k : usageOccs) {
            if (k.isRequired()) {
                usages.add(k.getExtKeyUsage());
            }
        }

        // the optional ExtKeyUsage will only be set if requested explicitly
        if (requestedExtensions != null && extControl.isRequest()) {
            addRequestedExtKeyusage(usages, requestedExtensions, usageOccs);
        }

        if (extControl.isCritical() && usages.contains(ObjectIdentifiers.id_anyExtendedKeyUsage)) {
            extControl = new ExtensionControl(false, extControl.isRequired(), extControl.isRequest());
        }

        ExtendedKeyUsage value = X509Util.createExtendedUsage(usages);
        addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
    }

    // ocsp-nocheck
    extType = ObjectIdentifiers.id_extension_pkix_ocsp_nocheck;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        // the extension ocsp-nocheck will only be set if requested explicitly
        DERNull value = DERNull.INSTANCE;
        addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
    }

    // SubjectInfoAccess
    extType = Extension.subjectInfoAccess;
    extControl = controls.remove(extType);
    if (extControl != null && addMe(extType, extControl, neededExtTypes, wantedExtTypes)) {
        ASN1Sequence value = null;
        if (requestedExtensions != null && extControl.isRequest()) {
            value = createSubjectInfoAccess(requestedExtensions, certprofile.getSubjectInfoAccessModes());
        }
        addExtension(values, extType, value, extControl, neededExtTypes, wantedExtTypes);
    }

    ExtensionValues subvalues = certprofile.getExtensions(Collections.unmodifiableMap(controls),
            requestedSubject, grantedSubject, requestedExtensions, notBefore, notAfter);

    Set<ASN1ObjectIdentifier> extTypes = new HashSet<>(controls.keySet());
    for (ASN1ObjectIdentifier type : extTypes) {
        extControl = controls.remove(type);
        boolean addMe = addMe(type, extControl, neededExtTypes, wantedExtTypes);
        if (addMe) {
            ExtensionValue value = null;
            if (requestedExtensions != null && extControl.isRequest()) {
                Extension reqExt = requestedExtensions.getExtension(type);
                if (reqExt != null) {
                    value = new ExtensionValue(reqExt.isCritical(), reqExt.getParsedValue());
                }
            }

            if (value == null) {
                value = subvalues.getExtensionValue(type);
            }

            addExtension(values, type, value, extControl, neededExtTypes, wantedExtTypes);
        }
    }

    Set<ASN1ObjectIdentifier> unprocessedExtTypes = new HashSet<>();
    for (ASN1ObjectIdentifier type : controls.keySet()) {
        if (controls.get(type).isRequired()) {
            unprocessedExtTypes.add(type);
        }
    }

    if (CollectionUtil.isNonEmpty(unprocessedExtTypes)) {
        throw new CertprofileException("could not add required extensions " + toString(unprocessedExtTypes));
    }

    if (CollectionUtil.isNonEmpty(neededExtTypes)) {
        throw new BadCertTemplateException("could not add requested extensions " + toString(neededExtTypes));
    }

    return values;
}

From source file:org.xipki.pki.ca.server.impl.X509CrlSignerEntryWrapper.java

License:Open Source License

public void initSigner(final SecurityFactory securityFactory)
        throws XiSecurityException, OperationException, InvalidConfException {
    ParamUtil.requireNonNull("securityFactory", securityFactory);
    if (signer != null) {
        return;//from  w ww  .j av a 2 s  .  c o m
    }

    if (dbEntry == null) {
        throw new XiSecurityException("dbEntry is null");
    }

    if ("CA".equals(dbEntry.getType())) {
        return;
    }

    dbEntry.setConfFaulty(true);

    X509Certificate responderCert = dbEntry.getCertificate();
    try {
        signer = securityFactory.createSigner(dbEntry.getType(), new SignerConf(dbEntry.getConf()),
                responderCert);
    } catch (ObjectCreationException ex1) {
        throw new XiSecurityException("signer without certificate is not allowed");
    }

    X509Certificate signerCert = signer.getCertificate();
    if (signerCert == null) {
        throw new XiSecurityException("signer without certificate is not allowed");
    }

    if (dbEntry.getBase64Cert() == null) {
        dbEntry.setCertificate(signerCert);
    }

    byte[] encodedSkiValue = signerCert.getExtensionValue(Extension.subjectKeyIdentifier.getId());
    if (encodedSkiValue == null) {
        throw new OperationException(ErrorCode.INVALID_EXTENSION,
                "CA certificate does not have required extension SubjectKeyIdentifier");
    }

    ASN1OctetString ski;
    try {
        ski = (ASN1OctetString) X509ExtensionUtil.fromExtensionValue(encodedSkiValue);
    } catch (IOException ex) {
        throw new OperationException(ErrorCode.INVALID_EXTENSION, ex);
    }
    this.subjectKeyIdentifier = ski.getOctets();

    if (!X509Util.hasKeyusage(signerCert, KeyUsage.cRLSign)) {
        throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CRL signer does not have keyusage cRLSign");
    }
    dbEntry.setConfFaulty(false);
}

From source file:org.xipki.pki.scep.util.ScepUtil.java

License:Open Source License

private static byte[] extractSki(final X509Certificate cert) throws CertificateEncodingException {
    byte[] extValue = getCoreExtValue(cert, Extension.subjectKeyIdentifier);
    if (extValue == null) {
        return null;
    }/*w w  w.j av  a2 s.com*/

    try {
        return ASN1OctetString.getInstance(extValue).getOctets();
    } catch (IllegalArgumentException ex) {
        throw new CertificateEncodingException(ex.getMessage());
    }
}

From source file:org.xwiki.crypto.pkix.internal.extension.DefaultX509ExtensionBuilder.java

License:Open Source License

@Override
public X509ExtensionBuilder addSubjectKeyIdentifier(PublicKeyParameters subject) {
    if (subject == null) {
        return this;
    }/*  ww w.j  a v a2  s  .  co m*/

    return addExtension(Extension.subjectKeyIdentifier, false,
            new BcX509ExtensionUtils().createSubjectKeyIdentifier(BcUtils.getSubjectPublicKeyInfo(subject)));
}

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

License:Apache License

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return/*from   w w  w  . j  a  v a 2  s .  co  m*/
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Security.addProvider(new BouncyCastleProvider());
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth,
                KeyPurposeId.anyExtendedKeyUsage };
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE,
                new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

From source file:se.tillvaxtverket.tsltrust.webservice.daemon.ca.RootCAFactory.java

License:Open Source License

private static AaaCertificate createRootCertificate(X500Name subjectIssuer, PublicKey publicKey,
        PrivateKey privateKey, String algorithm, List<Extension> extensions)
        throws OperatorCreationException, IOException, CertificateException {

    CertRequestModel reqMod = new CertRequestModel();
    reqMod.setSubjectDN(subjectIssuer);/*from w  ww .  j ava 2  s.  com*/
    reqMod.setIssuerDN(subjectIssuer);
    reqMod.setSerialNumber(BigInteger.ONE);
    reqMod.setPublicKey(publicKey);

    //Add Signer
    ContentSigner rooSigner = new JcaContentSignerBuilder(algorithm).build(privateKey);
    reqMod.setSigner(rooSigner);

    // ensure that EE certs are in the validity period of CA certs
    GregorianCalendar notBefore = new GregorianCalendar();
    GregorianCalendar notAfter = new GregorianCalendar();
    notBefore.add(Calendar.YEAR, -2);
    notAfter.add(Calendar.YEAR, 5);
    reqMod.setNotBefore(notBefore.getTime());
    reqMod.setNotAfter(notAfter.getTime());

    X509ExtensionUtils extUtil = CertUtils.getX509ExtensionUtils();
    SubjectKeyIdentifier ski = extUtil.createSubjectKeyIdentifier(CertUtils.getPublicKeyInfo(publicKey));
    extensions.add(new Extension(Extension.subjectKeyIdentifier, false, ski.getEncoded("DER")));

    reqMod.setExtensionList(extensions);

    AaaCertificate cert = new AaaCertificate(reqMod);
    return cert;
}

From source file:support.revocation.RevocationInfo.java

License:Apache License

/**
 * Creates a new <code>RevocationInfo</code> instance based on the given
 * certificate/* w w w  .j  a v  a2s .  c om*/
 * @param certificate
 */
public RevocationInfo(Certificate certificate) {
    if (certificate instanceof X509Certificate)
        try {
            X509Certificate x509cert = (X509Certificate) certificate;

            // process Authority Information Access extension
            // to determine OCSP services
            AuthorityInformationAccess info = AuthorityInformationAccess
                    .getInstance(certificateExtension(x509cert, Extension.authorityInfoAccess.getId()));

            if (info != null)
                for (AccessDescription desc : info.getAccessDescriptions())
                    if (desc.getAccessMethod().equals(AccessDescription.id_ad_ocsp)) {
                        String url = urlFromGeneralName(desc.getAccessLocation());
                        if (url != null)
                            ocsp.add(url);
                    }

            ocsp = Collections.unmodifiableList(ocsp);

            // process CRL Distribution Points extension
            // to determine CRL services
            CRLDistPoint points = CRLDistPoint
                    .getInstance(certificateExtension(x509cert, Extension.cRLDistributionPoints.getId()));

            if (points != null)
                for (DistributionPoint point : points.getDistributionPoints()) {
                    // no support for CRLs issued from another CA
                    GeneralNames crlIssuer = point.getCRLIssuer();
                    if (crlIssuer != null && !crlIssuer.equals(DERNull.INSTANCE))
                        continue;

                    // no support for partial CRLs
                    ReasonFlags reasons = point.getReasons();
                    if (reasons != null && !reasons.equals(DERNull.INSTANCE))
                        continue;

                    // use all distribution points
                    ASN1Encodable names = point.getDistributionPoint().getName();
                    if (names instanceof GeneralNames)
                        for (GeneralName name : ((GeneralNames) names).getNames()) {
                            String url = urlFromGeneralName(name);
                            if (url != null)
                                crl.add(url);
                        }
                }

            crl = Collections.unmodifiableList(crl);

            // Authority Key Identifier
            AuthorityKeyIdentifier authorityKeyId = AuthorityKeyIdentifier
                    .getInstance(certificateExtension(x509cert, Extension.authorityKeyIdentifier.getId()));

            if (authorityKeyId != null) {
                byte[] keyidentifier = authorityKeyId.getKeyIdentifier();
                if (keyidentifier != null) {
                    authorityKeyIdentifier = new ArrayList<>(keyidentifier.length);
                    for (byte value : keyidentifier)
                        authorityKeyIdentifier.add(value);
                    authorityKeyIdentifier = Collections.unmodifiableList(authorityKeyIdentifier);
                }

                BigInteger serial = authorityKeyId.getAuthorityCertSerialNumber();
                if (serial != null)
                    authoritySerial = serial.toString();
            }

            // Subject Key Identifier
            SubjectKeyIdentifier subjectKeyId = SubjectKeyIdentifier
                    .getInstance(certificateExtension(x509cert, Extension.subjectKeyIdentifier.getId()));

            if (subjectKeyId != null) {
                byte[] keyidentifier = subjectKeyId.getKeyIdentifier();
                if (keyidentifier != null) {
                    subjectKeyIdentifier = new ArrayList<>(keyidentifier.length);
                    for (byte value : keyidentifier)
                        subjectKeyIdentifier.add(value);
                    subjectKeyIdentifier = Collections.unmodifiableList(subjectKeyIdentifier);
                }
            }

        } catch (ClassCastException | IllegalArgumentException e) {
            e.printStackTrace();
        }
}

From source file:uk.ac.cam.gpe21.droidssl.mitm.crypto.cert.CertificateGenerator.java

License:Apache License

public X509CertificateHolder generate(String cn, String[] sans) {
    try {//  ww  w. java 2 s . c om
        /* basic certificate structure */
        //serial = serial.add(BigInteger.ONE);
        // TODO: temporary workaround as reusing serial numbers makes Firefox complain
        serial = new BigInteger(Long.toString(System.currentTimeMillis()));

        Calendar notBefore = new GregorianCalendar(UTC);
        notBefore.add(Calendar.HOUR, -1);

        Calendar notAfter = new GregorianCalendar(UTC);
        notAfter.add(Calendar.HOUR, 24);

        X500Name subject = new X500NameBuilder().addRDN(BCStyle.CN, cn).build();

        BcX509ExtensionUtils utils = new BcX509ExtensionUtils();
        X509v3CertificateBuilder builder = new BcX509v3CertificateBuilder(ca.getCertificate(), serial,
                notBefore.getTime(), notAfter.getTime(), subject, keyPair.getPublic());

        /* subjectAlernativeName extension */
        if (sans.length > 0) {
            GeneralName[] names = new GeneralName[sans.length];
            for (int i = 0; i < names.length; i++) {
                names[i] = new GeneralName(GeneralName.dNSName, sans[i]);
            }
            builder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(names));
        }

        /* basicConstraints extension */
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));

        /* subjectKeyIdentifier extension */
        builder.addExtension(Extension.subjectKeyIdentifier, false,
                utils.createSubjectKeyIdentifier(keyPair.getPublic()));

        /* authorityKeyIdentifier extension */
        builder.addExtension(Extension.authorityKeyIdentifier, false,
                utils.createAuthorityKeyIdentifier(ca.getPublicKey()));

        /* keyUsage extension */
        int usage = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.keyAgreement;
        builder.addExtension(Extension.keyUsage, true, new KeyUsage(usage));

        /* extendedKeyUsage extension */
        KeyPurposeId[] usages = { KeyPurposeId.id_kp_serverAuth };
        builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(usages));

        /* create the signer */
        AlgorithmIdentifier signatureAlgorithm = new DefaultSignatureAlgorithmIdentifierFinder()
                .find("SHA1withRSA");
        AlgorithmIdentifier digestAlgorithm = new DefaultDigestAlgorithmIdentifierFinder()
                .find(signatureAlgorithm);
        ContentSigner signer = new BcRSAContentSignerBuilder(signatureAlgorithm, digestAlgorithm)
                .build(ca.getPrivateKey());

        /* build and sign the certificate */
        return builder.build(signer);
    } catch (IOException | OperatorCreationException ex) {
        throw new CertificateGenerationException(ex);
    }
}