Example usage for org.bouncycastle.asn1.x509 X509Extension getValue

List of usage examples for org.bouncycastle.asn1.x509 X509Extension getValue

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Extension getValue.

Prototype

public ASN1OctetString getValue() 

Source Link

Usage

From source file:chapter6.PKCS10CertCreateExample.java

public static X509Certificate[] buildChain() throws Exception {
    // Create the certification request
    KeyPair pair = Utils.generateRSAKeyPair();

    PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair);

    // Create a root certificate
    KeyPair rootPair = Utils.generateRSAKeyPair();
    X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair);

    // Validate the certification request
    if (request.verify("BC") == false) {
        System.out.println("Request failed to verify!!");
        System.exit(1);//  w w w .  j ava 2s. c om
    }

    // Create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded()));
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    // Extract the extension request attribute
    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i < attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        // Process extension request
        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }
        }
    }

    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}

From source file:ec.rubrica.util.BouncyCastleUtils.java

License:Open Source License

public static boolean certificateHasPolicy(X509Certificate cert, String sOid) {
    try {//ww  w .  j  ava 2  s  . c o  m
        logger.fine("Read cert policies: " + cert.getSerialNumber().toString());

        ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
        ASN1InputStream aIn = new ASN1InputStream(bIn);
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
        X509CertificateStructure obj = new X509CertificateStructure(seq);
        TBSCertificateStructure tbsCert = obj.getTBSCertificate();
        if (tbsCert.getVersion() == 3) {
            X509Extensions ext = tbsCert.getExtensions();
            if (ext != null) {
                Enumeration en = ext.oids();
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
                    X509Extension extVal = ext.getExtension(oid);
                    ASN1OctetString oct = extVal.getValue();
                    ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));

                    if (oid.equals(X509Extension.certificatePolicies)) {
                        ASN1Sequence cp = (ASN1Sequence) extIn.readObject();
                        for (int i = 0; i != cp.size(); i++) {
                            PolicyInformation pol = PolicyInformation.getInstance(cp.getObjectAt(i));
                            DERObjectIdentifier dOid = pol.getPolicyIdentifier();
                            String soid2 = dOid.getId();

                            logger.fine("Policy: " + soid2);
                            if (soid2.startsWith(sOid))
                                return true;
                        }
                    }
                }
            }

        }
    } catch (Exception ex) {
        logger.severe("Error reading cert policies: " + ex);
    }
    return false;
}

From source file:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java

License:Open Source License

/**
 * Method to get NONCE array from responce
 * @param basResp/*from   w ww .  j  a v a2 s . co  m*/
 * @return OCSP nonce value
 */
private byte[] getNonce(BasicOCSPResp basResp) {
    if (basResp != null) {
        X509Extensions ext = basResp.getResponseData().getResponseExtensions();
        X509Extension ex1 = ext.getExtension(new DERObjectIdentifier(nonceOid));
        byte[] nonce2 = ex1.getValue().getOctets();

        return nonce2;
    } else
        return null;
}

From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java

License:Apache License

public static X509Certificate[] buildChain() throws Exception {
    // create the certification request
    KeyPair pair = Utils.generateRSAKeyPair();

    PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair);

    // create a root certificate
    KeyPair rootPair = Utils.generateRSAKeyPair();
    X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair);

    // validate the certification request
    if (!request.verify("BC")) {
        System.out.println("request failed to verify!");
        System.exit(1);/*from   w  w  w. j  av  a2  s  . c o m*/
    }

    // create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    // extract the extension request attribute
    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i != attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        // process extension request
        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }
        }
    }

    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}

From source file:org.cagrid.gaards.pki.BouncyCastleCertProcessingFactory.java

License:Open Source License

/**
 * Creates a proxy certificate. A set of X.509 extensions can be optionally
 * included in the new proxy certificate. <BR>
 * If a GSI-2 proxy is created, the serial number of the proxy certificate
 * will be the same as of the issuing certificate. Also, none of the
 * extensions in the issuing certificate will be copied into the proxy
 * certificate.<BR>/*from   w  w  w  . j  a v a2 s  .com*/
 * If a GSI-3 proxy is created, the serial number of the proxy certificate
 * will be picked randomly. If the issuing certificate contains a
 * <i>KeyUsage</i> extension, the extension will be copied into the proxy
 * certificate with <i>keyCertSign</i> and <i>nonRepudiation</i> bits
 * turned off. No other extensions are currently copied.
 * 
 * @param issuerCert
 *            the issuing certificate
 * @param issuerKey
 *            private key matching the public key of issuer certificate. The
 *            new proxy certificate will be signed by that key.
 * @param publicKey
 *            the public key of the new certificate
 * @param lifetime
 *            lifetime of the new certificate in seconds. If 0 (or less
 *            then) the new certificate will have the same lifetime as the
 *            issuing certificate.
 * @param proxyType
 *            can be one of {@link GSIConstants#DELEGATION_LIMITED
 *            GSIConstants.DELEGATION_LIMITED},
 *            {@link GSIConstants#DELEGATION_FULL
 *            GSIConstants.DELEGATION_FULL},
 *            {@link GSIConstants#GSI_2_LIMITED_PROXY
 *            GSIConstants.GSI_2_LIMITED_PROXY},
 *            {@link GSIConstants#GSI_2_PROXY GSIConstants.GSI_2_PROXY},
 *            {@link GSIConstants#GSI_3_IMPERSONATION_PROXY
 *            GSIConstants.GSI_3_IMPERSONATION_PROXY},
 *            {@link GSIConstants#GSI_3_LIMITED_PROXY
 *            GSIConstants.GSI_3_LIMITED_PROXY},
 *            {@link GSIConstants#GSI_3_INDEPENDENT_PROXY
 *            GSIConstants.GSI_3_INDEPENDENT_PROXY},
 *            {@link GSIConstants#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.GSI_3_RESTRICTED_PROXY}. If
 *            {@link GSIConstants#DELEGATION_LIMITED
 *            GSIConstants.DELEGATION_LIMITED} and if
 *            {@link CertUtil#isGsi3Enabled() CertUtil.isGsi3Enabled}
 *            returns true then a GSI-3 limited proxy will be created. If
 *            not, a GSI-2 limited proxy will be created. If
 *            {@link GSIConstants#DELEGATION_FULL
 *            GSIConstants.DELEGATION_FULL} and if
 *            {@link CertUtil#isGsi3Enabled() CertUtil.isGsi3Enabled}
 *            returns true then a GSI-3 impersonation proxy will be created.
 *            If not, a GSI-2 full proxy will be created.
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy
 *            certificate. Can be null. If delegation mode is
 *            {@link GSIConstants#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.GSI_3_RESTRICTED_PROXY} then
 *            {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension 
 *            ProxyCertInfoExtension} must be present in the extension set.
 * @param cnValue
 *            the value of the CN component of the subject of the new
 *            certificate. If null, the defaults will be used depending on
 *            the proxy certificate type created.
 * @return <code>X509Certificate</code> the new proxy certificate.
 * @exception GeneralSecurityException
 *                if a security error occurs.
 */
public X509Certificate createProxyCertificate(String provider, X509Certificate issuerCert, PrivateKey issuerKey,
        PublicKey publicKey, int lifetime, int proxyType, X509ExtensionSet extSet, String cnValue,
        String signatureAlgorithm) throws GeneralSecurityException {

    if (proxyType == GSIConstants.DELEGATION_LIMITED) {
        int type = BouncyCastleUtil.getCertificateType(issuerCert);
        if (CertUtil.isGsi4Proxy(type)) {
            proxyType = GSIConstants.GSI_4_LIMITED_PROXY;
        } else if (CertUtil.isGsi3Proxy(type)) {
            proxyType = GSIConstants.GSI_3_LIMITED_PROXY;
        } else if (CertUtil.isGsi2Proxy(type)) {
            proxyType = GSIConstants.GSI_2_LIMITED_PROXY;
        } else {
            // default to Globus OID
            proxyType = (CertUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_LIMITED_PROXY
                    : GSIConstants.GSI_2_LIMITED_PROXY;
        }
    } else if (proxyType == GSIConstants.DELEGATION_FULL) {
        int type = BouncyCastleUtil.getCertificateType(issuerCert);
        if (CertUtil.isGsi4Proxy(type)) {
            proxyType = GSIConstants.GSI_4_IMPERSONATION_PROXY;
        } else if (CertUtil.isGsi3Proxy(type)) {
            proxyType = GSIConstants.GSI_3_IMPERSONATION_PROXY;
        } else if (CertUtil.isGsi2Proxy(type)) {
            proxyType = GSIConstants.GSI_2_PROXY;
        } else {
            // Default to Globus OID
            proxyType = (CertUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_IMPERSONATION_PROXY
                    : GSIConstants.GSI_2_PROXY;
        }
    }

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    org.globus.gsi.X509Extension x509Ext = null;
    BigInteger serialNum = null;
    String delegDN = null;

    if (CertUtil.isGsi3Proxy(proxyType) || CertUtil.isGsi4Proxy(proxyType)) {
        Random rand = new Random();
        delegDN = String.valueOf(Math.abs(rand.nextInt()));
        serialNum = new BigInteger(20, rand);

        if (extSet != null) {
            x509Ext = extSet.get(ProxyCertInfo.OID.getId());
            if (x509Ext == null) {
                x509Ext = extSet.get(ProxyCertInfo.OLD_OID.getId());
            }
        }

        if (x509Ext == null) {
            // create ProxyCertInfo extension
            ProxyPolicy policy = null;
            if (CertUtil.isLimitedProxy(proxyType)) {
                policy = new ProxyPolicy(ProxyPolicy.LIMITED);
            } else if (CertUtil.isIndependentProxy(proxyType)) {
                policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT);
            } else if (CertUtil.isImpersonationProxy(proxyType)) {
                // since limited has already been checked, this should work.
                policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION);
            } else if ((proxyType == GSIConstants.GSI_3_RESTRICTED_PROXY)
                    || (proxyType == GSIConstants.GSI_4_RESTRICTED_PROXY)) {
                throw new IllegalArgumentException("Restricted proxy requires ProxyCertInfo extension");
            } else {
                throw new IllegalArgumentException("Invalid proxyType");
            }

            ProxyCertInfo proxyCertInfo = new ProxyCertInfo(policy);
            x509Ext = new ProxyCertInfoExtension(proxyCertInfo);
            if (CertUtil.isGsi4Proxy(proxyType)) {
                // RFC compliant OID
                x509Ext = new ProxyCertInfoExtension(proxyCertInfo);
            } else {
                // old OID
                x509Ext = new GlobusProxyCertInfoExtension(proxyCertInfo);
            }
        }

        try {
            // add ProxyCertInfo extension to the new cert
            certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue());

            // handle KeyUsage in issuer cert
            TBSCertificateStructure crt = BouncyCastleUtil.getTBSCertificateStructure(issuerCert);

            X509Extensions extensions = crt.getExtensions();
            if (extensions != null) {
                X509Extension ext;

                // handle key usage ext
                ext = extensions.getExtension(X509Extensions.KeyUsage);
                if (ext != null) {

                    // TBD: handle this better
                    if (extSet != null && (extSet.get(X509Extensions.KeyUsage.getId()) != null)) {
                        throw new GeneralSecurityException("KeyUsage extension present in X509ExtensionSet "
                                + "and in issuer certificate.");
                    }

                    DERBitString bits = (DERBitString) BouncyCastleUtil.getExtensionObject(ext);

                    byte[] bytes = bits.getBytes();

                    // make sure they are disabled
                    if ((bytes[0] & KeyUsage.nonRepudiation) != 0) {
                        bytes[0] ^= KeyUsage.nonRepudiation;
                    }

                    if ((bytes[0] & KeyUsage.keyCertSign) != 0) {
                        bytes[0] ^= KeyUsage.keyCertSign;
                    }

                    bits = new DERBitString(bytes, bits.getPadBits());

                    certGen.addExtension(X509Extensions.KeyUsage, ext.isCritical(), bits);
                }
            }

        } catch (IOException e) {
            // but this should not happen
            throw new GeneralSecurityException(e.getMessage());
        }

    } else if (proxyType == GSIConstants.GSI_2_LIMITED_PROXY) {
        delegDN = "limited proxy";
        serialNum = issuerCert.getSerialNumber();
    } else if (proxyType == GSIConstants.GSI_2_PROXY) {
        delegDN = "proxy";
        serialNum = issuerCert.getSerialNumber();
    } else {
        throw new IllegalArgumentException("Unsupported proxyType : " + proxyType);
    }

    // add specified extensions
    if (extSet != null) {
        Iterator iter = extSet.oidSet().iterator();
        while (iter.hasNext()) {
            String oid = (String) iter.next();
            // skip ProxyCertInfo extension
            if (oid.equals(ProxyCertInfo.OID.getId()) || oid.equals(ProxyCertInfo.OLD_OID.getId())) {
                continue;
            }
            x509Ext = (org.globus.gsi.X509Extension) extSet.get(oid);
            certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue());
        }
    }

    X509Name issuerDN = (X509Name) issuerCert.getSubjectDN();

    X509NameHelper issuer = new X509NameHelper(issuerDN);

    X509NameHelper subject = new X509NameHelper(issuerDN);
    subject.add(X509Name.CN, (cnValue == null) ? delegDN : cnValue);

    certGen.setSubjectDN(subject.getAsName());
    certGen.setIssuerDN(issuer.getAsName());

    certGen.setSerialNumber(serialNum);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm(signatureAlgorithm);

    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    /* Allow for a five minute clock skew here. */
    date.add(Calendar.MINUTE, -5);
    certGen.setNotBefore(date.getTime());

    /* If hours = 0, then cert lifetime is set to user cert */
    if (lifetime <= 0) {
        certGen.setNotAfter(issuerCert.getNotAfter());
    } else {
        date.add(Calendar.MINUTE, 5);
        date.add(Calendar.SECOND, lifetime);
        certGen.setNotAfter(date.getTime());
    }

    /**
     * FIXME: Copy appropriate cert extensions - this should NOT be done the
     * last time we talked to Doug E. This should investigated more.
     */

    return certGen.generateX509Certificate(issuerKey, provider);
}

From source file:org.candlepin.util.X509CRLStreamWriter.java

License:Open Source License

protected void writeToEmptyCrl(OutputStream out) throws IOException {
    ASN1InputStream asn1in = null;
    try {// ww w .ja  va 2s  .  co  m
        asn1in = new ASN1InputStream(crlIn);
        DERSequence certListSeq = (DERSequence) asn1in.readObject();
        CertificateList certList = new CertificateList(certListSeq);
        X509CRLHolder oldCrl = new X509CRLHolder(certList);

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(oldCrl.getIssuer(), new Date());
        crlBuilder.addCRL(oldCrl);

        Date now = new Date();
        Date oldNextUpdate = certList.getNextUpdate().getDate();
        Date oldThisUpdate = certList.getThisUpdate().getDate();

        Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime()));
        crlBuilder.setNextUpdate(nextUpdate);

        for (Object o : oldCrl.getExtensionOIDs()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o;
            X509Extension ext = oldCrl.getExtension(oid);

            if (oid.equals(X509Extension.cRLNumber)) {
                DEROctetString octet = (DEROctetString) ext.getValue().getDERObject();
                DERInteger currentNumber = (DERInteger) DERTaggedObject.fromByteArray(octet.getOctets());
                DERInteger nextNumber = new DERInteger(currentNumber.getValue().add(BigInteger.ONE));

                crlBuilder.addExtension(oid, ext.isCritical(), nextNumber);
            } else if (oid.equals(X509Extension.authorityKeyIdentifier)) {
                crlBuilder.addExtension(oid, ext.isCritical(),
                        new AuthorityKeyIdentifierStructure(ext.getValue().getDEREncoded()));
            }
        }

        for (DERSequence entry : newEntries) {
            // XXX: This is all a bit messy considering the user already passed in the serial, date
            // and reason.
            BigInteger serial = ((DERInteger) entry.getObjectAt(0)).getValue();
            Date revokeDate = ((Time) entry.getObjectAt(1)).getDate();
            int reason = CRLReason.unspecified;
            if (entry.size() == 3) {
                X509Extensions extensions = (X509Extensions) entry.getObjectAt(2);
                X509Extension reasonExt = extensions.getExtension(X509Extension.reasonCode);

                if (reasonExt != null) {
                    reason = ((DEREnumerated) reasonExt.getParsedValue()).getValue().intValue();
                }
            }
            crlBuilder.addCRLEntry(serial, revokeDate, reason);
        }

        RSAKeyParameters keyParams = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());

        signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm();
        digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg);

        ContentSigner s;
        try {
            s = new BcRSAContentSignerBuilder(signingAlg, digestAlg).build(keyParams);
            X509CRLHolder newCrl = crlBuilder.build(s);
            out.write(newCrl.getEncoded());
        } catch (OperatorCreationException e) {
            throw new IOException("Could not sign CRL", e);
        }
    } finally {
        IOUtils.closeQuietly(asn1in);
    }
}

From source file:org.candlepin.util.X509CRLStreamWriter.java

License:Open Source License

/**
 * This method updates the crlNumber and authorityKeyIdentifier extensions.  Any
 * other extensions are copied over unchanged.
 * @param extensions/*from w  ww .j av a 2s  .  c  om*/
 * @return
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
protected byte[] updateExtensions(byte[] obj) throws IOException {
    DERTaggedObject taggedExts = (DERTaggedObject) DERTaggedObject.fromByteArray(obj);
    DERSequence seq = (DERSequence) taggedExts.getObject();
    ASN1EncodableVector modifiedExts = new ASN1EncodableVector();

    // Now we need to read the extensions and find the CRL number and increment it,
    // and determine if its length changed.
    Enumeration objs = seq.getObjects();
    while (objs.hasMoreElements()) {
        DERSequence ext = (DERSequence) objs.nextElement();
        DERObjectIdentifier oid = (DERObjectIdentifier) ext.getObjectAt(0);
        if (X509Extension.cRLNumber.equals(oid)) {
            DEROctetString s = (DEROctetString) ext.getObjectAt(1);
            DERInteger i = (DERInteger) DERTaggedObject.fromByteArray(s.getOctets());
            DERInteger newCrlNumber = new DERInteger(i.getValue().add(BigInteger.ONE));

            X509Extension newNumberExt = new X509Extension(false,
                    new DEROctetString(newCrlNumber.getDEREncoded()));

            ASN1EncodableVector crlNumber = new ASN1EncodableVector();
            crlNumber.add(X509Extension.cRLNumber);
            crlNumber.add(newNumberExt.getValue());
            modifiedExts.add(new DERSequence(crlNumber));
        } else if (X509Extension.authorityKeyIdentifier.equals(oid)) {
            X509Extension newAuthorityKeyExt = new X509Extension(false,
                    new DEROctetString(akiStructure.getDEREncoded()));

            ASN1EncodableVector aki = new ASN1EncodableVector();
            aki.add(X509Extension.authorityKeyIdentifier);
            aki.add(newAuthorityKeyExt.getValue());
            modifiedExts.add(new DERSequence(aki));
        } else {
            modifiedExts.add(ext);
        }
    }

    DERSequence seqOut = new DERSequence(modifiedExts);
    DERTaggedObject out = new DERTaggedObject(true, 0, seqOut);
    return out.getDEREncoded();
}

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

License:Open Source License

private BasicOCSPRespGenerator createOcspResponseGenerator(OCSPReq req, X509Certificate respondercert,
        int respIdType) throws OCSPException, NotSupportedException {
    if (null == req) {
        throw new IllegalArgumentException();
    }/*from   w w  w.j  a va 2 s. c  o  m*/
    BasicOCSPRespGenerator res = null;
    if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
        res = new BasicOCSPRespGenerator(new RespID(respondercert.getSubjectX500Principal()));
    } else {
        res = new BasicOCSPRespGenerator(respondercert.getPublicKey());
    }
    X509Extensions reqexts = req.getRequestExtensions();
    if (reqexts != null) {
        X509Extension ext = reqexts.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_response);
        if (null != ext) {
            // log.debug("Found extension AcceptableResponses");
            ASN1OctetString oct = ext.getValue();
            try {
                ASN1Sequence seq = ASN1Sequence.getInstance(
                        new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
                @SuppressWarnings("unchecked")
                Enumeration<DERObjectIdentifier> en = seq.getObjects();
                boolean supportsResponseType = false;
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = en.nextElement();
                    // log.debug("Found oid: "+oid.getId());
                    if (oid.equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) {
                        // This is the response type we support, so we are happy! Break the loop.
                        supportsResponseType = true;
                        log.debug("Response type supported: " + oid.getId());
                        continue;
                    }
                }
                if (!supportsResponseType) {
                    throw new NotSupportedException(
                            "Required response type not supported, this responder only supports id-pkix-ocsp-basic.");
                }
            } catch (IOException e) {
            }
        }
    }
    return res;
}

From source file:org.ejbca.core.ejb.ca.sign.RSASignSessionBean.java

License:Open Source License

@Override
public IResponseMessage createCertificate(Admin admin, IRequestMessage req, Class responseClass,
        UserDataVO suppliedUserData) throws EjbcaException {
    if (log.isTraceEnabled()) {
        log.trace(">createCertificate(IRequestMessage)");
    }/*from  ww  w  .ja v a  2 s  .c  om*/
    // Get CA that will receive request
    UserDataVO data = null;
    IResponseMessage ret = null;
    CA ca;
    if (suppliedUserData == null) {
        ca = getCAFromRequest(admin, req);
    } else {
        ca = caSession.getCA(admin, suppliedUserData.getCAId()); // Take the CAId from the supplied userdata, if any
    }
    try {
        CATokenContainer catoken = ca.getCAToken();

        // See if we need some key material to decrypt request
        if (req.requireKeyInfo()) {
            // You go figure...scep encrypts message with the public CA-cert
            req.setKeyInfo(ca.getCACertificate(), catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN),
                    catoken.getJCEProvider());
        }
        // Verify the request
        if (req.verify() == false) {
            String msg = intres.getLocalizedMessage("signsession.popverificationfailed");
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestSignatureException(msg);
        }

        if (ca.isUseUserStorage() && req.getUsername() == null) {
            String msg = intres.getLocalizedMessage("signsession.nouserinrequest", req.getRequestDN());
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestException(msg);
            //ret.setFailInfo(FailInfo.BAD_REQUEST);
            //ret.setStatus(ResponseStatus.FAILURE);
        } else if (ca.isUseUserStorage() && req.getPassword() == null) {
            String msg = intres.getLocalizedMessage("signsession.nopasswordinrequest");
            logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(), req.getUsername(),
                    null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, msg);
            throw new SignRequestException(msg);
        } else {
            ResponseStatus status = ResponseStatus.SUCCESS;
            FailInfo failInfo = null;
            String failText = null;
            Certificate cert = null;
            try {
                // If we haven't done so yet, authenticate user. (Only if we store UserData for this CA.)
                if (ca.isUseUserStorage()) {
                    data = authUser(admin, req.getUsername(), req.getPassword());
                } else {
                    data = suppliedUserData;
                }
                PublicKey reqpk = req.getRequestPublicKey();
                if (reqpk == null) {
                    logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                            req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE,
                            intres.getLocalizedMessage("signsession.nokeyinrequest"));
                    throw new InvalidKeyException("Key is null!");
                }
                // We need to make sure we use the users registered CA here
                if (data.getCAId() != ca.getCAId()) {
                    failText = intres.getLocalizedMessage("signsession.wrongauthority",
                            Integer.valueOf(ca.getCAId()), Integer.valueOf(data.getCAId()));
                    status = ResponseStatus.FAILURE;
                    failInfo = FailInfo.WRONG_AUTHORITY;
                    logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                            req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText);
                }

                if (status.equals(ResponseStatus.SUCCESS)) {
                    Date notBefore = req.getRequestValidityNotBefore(); // Optionally requested validity
                    Date notAfter = req.getRequestValidityNotAfter(); // Optionally requested validity
                    X509Extensions exts = req.getRequestExtensions(); // Optionally requested extensions
                    int keyusage = -1;
                    if (exts != null) {
                        if (log.isDebugEnabled()) {
                            log.debug(
                                    "we have extensions, see if we can override KeyUsage by looking for a KeyUsage extension in request");
                        }
                        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
                        if (ext != null) {
                            ASN1OctetString os = ext.getValue();
                            ByteArrayInputStream bIs = new ByteArrayInputStream(os.getOctets());
                            ASN1InputStream dIs = new ASN1InputStream(bIs);
                            DERObject dob = dIs.readObject();
                            DERBitString bs = DERBitString.getInstance(dob);
                            keyusage = bs.intValue();
                            if (log.isDebugEnabled()) {
                                log.debug("We have a key usage request extension: " + keyusage);
                            }
                        }
                    }
                    String sequence = null;
                    byte[] ki = req.getRequestKeyInfo();
                    if ((ki != null) && (ki.length > 0)) {
                        sequence = new String(ki);
                    }
                    cert = createCertificate(admin, data, req.getRequestX509Name(), ca, reqpk, keyusage,
                            notBefore, notAfter, exts, sequence);
                }
            } catch (ObjectNotFoundException oe) {
                // If we didn't find the entity return error message
                log.error("User not found: ", oe);
                failText = intres.getLocalizedMessage("signsession.nosuchuser", req.getUsername());
                status = ResponseStatus.FAILURE;
                failInfo = FailInfo.INCORRECT_DATA;
                logSession.log(admin, ca.getCAId(), LogConstants.MODULE_CA, new java.util.Date(),
                        req.getUsername(), null, LogConstants.EVENT_ERROR_CREATECERTIFICATE, failText);
            }

            //Create the response message with all nonces and checks etc
            ret = req.createResponseMessage(responseClass, req, ca.getCACertificate(),
                    catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), catoken.getProvider());

            if ((cert == null) && (status == ResponseStatus.SUCCESS)) {
                status = ResponseStatus.FAILURE;
                failInfo = FailInfo.BAD_REQUEST;
            } else {
                ret.setCertificate(cert);
            }
            ret.setStatus(status);
            if (failInfo != null) {
                ret.setFailInfo(failInfo);
                ret.setFailText(failText);
            }
        }
        ret.create();
        // Call authentication session and tell that we are finished with this user. (Only if we store UserData for this CA.)
        if (ca.isUseUserStorage() && data != null) {
            finishUser(ca, data);
        }
    } catch (NoUniqueCertSerialNumberIndexException e) {
        cleanUserCertDataSN(data);
        throw e.ejbcaException;
    } catch (IllegalKeyException ke) {
        log.error("Key is of unknown type: ", ke);
        throw ke;
    } catch (CATokenOfflineException ctoe) {
        String msg = intres.getLocalizedMessage("error.catokenoffline", ca.getSubjectDN());
        CATokenOfflineException ex = new CATokenOfflineException(msg);
        ex.initCause(ctoe);
        throw ex;
        //} catch (EjbcaException e) {
        //    throw e;
    } catch (NoSuchProviderException e) {
        log.error("NoSuchProvider provider: ", e);
    } catch (InvalidKeyException e) {
        log.error("Invalid key in request: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("No such algorithm: ", e);
    } catch (IOException e) {
        log.error("Cannot create response message: ", e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<createCertificate(IRequestMessage)");
    }
    return ret;
}

From source file:org.ejbca.core.model.ca.caadmin.X509CA.java

License:Open Source License

/**
 * sequence is ignored by X509CA//from  w ww  .  j  a  va2 s .  c om
 */
public Certificate generateCertificate(UserDataVO subject, X509Name requestX509Name, PublicKey publicKey,
        int keyusage, Date notBefore, Date notAfter, CertificateProfile certProfile, X509Extensions extensions,
        String sequence, PublicKey caPublicKey, PrivateKey caPrivateKey, String provider) throws Exception {

    // We must only allow signing to take place if the CA itself if on line, even if the token is on-line.
    // We have to allow expired as well though, so we can renew expired CAs
    if ((getStatus() != SecConst.CA_ACTIVE) && ((getStatus() != SecConst.CA_EXPIRED))) {
        String msg = intres.getLocalizedMessage("error.caoffline", getName(), getStatus());
        if (log.isDebugEnabled()) {
            log.debug(msg); // This is something we handle so no need to log with higher priority
        }
        throw new CAOfflineException(msg);
    }

    final String sigAlg;
    if (certProfile.getSignatureAlgorithm() == null) {
        sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm();
    } else {
        sigAlg = certProfile.getSignatureAlgorithm();
    }
    final X509Certificate cacert = (X509Certificate) getCACertificate();
    String dn = subject.getCertificateDN();
    // Check if this is a root CA we are creating
    final boolean isRootCA = certProfile.getType() == CertificateProfile.TYPE_ROOTCA;

    // Get certificate validity time notBefore and notAfter
    final CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert,
            isRootCA);

    final X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();
    {
        // Serialnumber is either random bits, where random generator is initialized by the serno generator.
        // Or a custom serial number defined in the end entity object
        final ExtendedInformation ei = subject.getExtendedinformation();
        BigInteger customSN = ei != null ? ei.certificateSerialNumber() : null;
        if (customSN != null) {
            if (!certProfile.getAllowCertSerialNumberOverride()) {
                final String msg = intres.getLocalizedMessage(
                        "signsession.certprof_not_allowing_cert_sn_override_using_normal",
                        customSN.toString(16));
                log.info(msg);
                customSN = null;
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Using custom serial number: " + customSN.toString(16));
                }
            }
        }
        final BigInteger serno = customSN != null ? customSN : SernoGenerator.instance().getSerno();
        certgen.setSerialNumber(serno);
    }
    certgen.setNotBefore(val.getNotBefore());
    certgen.setNotAfter(val.getNotAfter());
    certgen.setSignatureAlgorithm(sigAlg);

    // Make DNs
    if (certProfile.getUseSubjectDNSubSet()) {
        dn = certProfile.createSubjectDNSubSet(dn);
    }

    if (certProfile.getUseCNPostfix()) {
        dn = CertTools.insertCNPostfix(dn, certProfile.getCNPostfix());
    }

    X509NameEntryConverter converter = null;
    if (getUsePrintableStringSubjectDN()) {
        converter = new PrintableStringEntryConverter();
    } else {
        converter = new X509DefaultEntryConverter();
    }
    // Will we use LDAP DN order (CN first) or X500 DN order (CN last) for the subject DN
    boolean ldapdnorder = true;
    if ((getUseLdapDNOrder() == false) || (certProfile.getUseLdapDnOrder() == false)) {
        ldapdnorder = false;
    }
    X509Name subjectDNName = CertTools.stringToBcX509Name(dn, converter, ldapdnorder);
    if (certProfile.getAllowDNOverride() && (requestX509Name != null)) {
        subjectDNName = requestX509Name;
        if (log.isDebugEnabled()) {
            log.debug("Using X509Name from request instead of user's registered.");
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Using subjectDN: " + subjectDNName.toString());
    }
    certgen.setSubjectDN(subjectDNName);
    // We must take the issuer DN directly from the CA-certificate otherwise we risk re-ordering the DN
    // which many applications do not like.
    if (isRootCA) {
        // This will be an initial root CA, since no CA-certificate exists
        // Or it is a root CA, since the cert is self signed. If it is a root CA we want to use the same encoding for subject and issuer,
        // it might have changed over the years.
        if (log.isDebugEnabled()) {
            log.debug("Using subject DN also as issuer DN, because it is a root CA");
        }
        certgen.setIssuerDN(subjectDNName);
    } else {
        javax.security.auth.x500.X500Principal issuerPrincipal = cacert.getSubjectX500Principal();
        if (log.isDebugEnabled()) {
            log.debug("Using issuer DN directly from the CA certificate: " + issuerPrincipal.getName());
        }
        certgen.setIssuerDN(issuerPrincipal);
    }
    certgen.setPublicKey(publicKey);

    //
    // X509 Certificate Extensions
    //

    // Extensions we will add to the certificate, later when we have filled the structure with 
    // everything we want.
    X509ExtensionsGenerator extgen = new X509ExtensionsGenerator();

    // First we check if there is general extension override, and add all extensions from 
    // the request in that case
    if (certProfile.getAllowExtensionOverride() && extensions != null) {
        Enumeration en = extensions.oids();
        while (en != null && en.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (log.isDebugEnabled()) {
                log.debug("Overriding extension with oid: " + oid);
            }
            extgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
        }
    }

    // Second we see if there is Key usage override
    X509Extensions overridenexts = extgen.generate();
    if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) {
        if (log.isDebugEnabled()) {
            log.debug("AllowKeyUsageOverride=true. Using KeyUsage from parameter: " + keyusage);
        }
        if ((certProfile.getUseKeyUsage() == true) && (keyusage >= 0)) {
            X509KeyUsage ku = new X509KeyUsage(keyusage);
            // We don't want to try to add custom extensions with the same oid if we have already added them 
            // from the request, if AllowExtensionOverride is enabled.
            // Two extensions with the same oid is not allowed in the standard.
            if (overridenexts.getExtension(X509Extensions.KeyUsage) == null) {
                extgen.addExtension(X509Extensions.KeyUsage, certProfile.getKeyUsageCritical(), ku);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "KeyUsage was already overridden by an extension, not using KeyUsage from parameter.");
                }
            }
        }
    }

    // Third, check for standard Certificate Extensions that should be added.
    // Standard certificate extensions are defined in CertificateProfile and CertificateExtensionFactory
    // and implemented in package org.ejbca.core.model.certextensions.standard
    CertificateExtensionFactory fact = CertificateExtensionFactory.getInstance();
    List<String> usedStdCertExt = certProfile.getUsedStandardCertificateExtensions();
    Iterator<String> certStdExtIter = usedStdCertExt.iterator();
    overridenexts = extgen.generate();
    while (certStdExtIter.hasNext()) {
        String oid = certStdExtIter.next();
        // We don't want to try to add standard extensions with the same oid if we have already added them 
        // from the request, if AllowExtensionOverride is enabled.
        // Two extensions with the same oid is not allowed in the standard.
        if (overridenexts.getExtension(new DERObjectIdentifier(oid)) == null) {
            CertificateExtension certExt = fact.getStandardCertificateExtension(oid, certProfile);
            if (certExt != null) {
                byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey);
                if (value != null) {
                    extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(),
                            value);
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Extension with oid " + oid
                        + " has been overridden, standard extension will not be added.");
            }
        }
    }

    // Fourth, check for custom Certificate Extensions that should be added.
    // Custom certificate extensions is defined in certextensions.properties
    fact = CertificateExtensionFactory.getInstance();
    List<Integer> usedCertExt = certProfile.getUsedCertificateExtensions();
    Iterator<Integer> certExtIter = usedCertExt.iterator();
    while (certExtIter.hasNext()) {
        Integer id = certExtIter.next();
        CertificateExtension certExt = fact.getCertificateExtensions(id);
        if (certExt != null) {
            // We don't want to try to add custom extensions with the same oid if we have already added them 
            // from the request, if AllowExtensionOverride is enabled.
            // Two extensions with the same oid is not allowed in the standard.
            if (overridenexts.getExtension(new DERObjectIdentifier(certExt.getOID())) == null) {
                byte[] value = certExt.getValueEncoded(subject, this, certProfile, publicKey, caPublicKey);
                if (value != null) {
                    extgen.addExtension(new DERObjectIdentifier(certExt.getOID()), certExt.isCriticalFlag(),
                            value);
                }
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("Extension with oid " + certExt.getOID()
                            + " has been overridden, custom extension will not be added.");
                }
            }
        }
    }

    // Finally add extensions to certificate generator
    X509Extensions exts = extgen.generate();
    Enumeration en = exts.oids();
    while (en.hasMoreElements()) {
        DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
        X509Extension ext = exts.getExtension(oid);
        certgen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
    }

    //
    // End of extensions
    //

    X509Certificate cert;
    if (log.isTraceEnabled()) {
        log.trace(">certgen.generate");
    }
    cert = certgen.generate(caPrivateKey, provider);
    if (log.isTraceEnabled()) {
        log.trace("<certgen.generate");
    }

    // Verify using the CA certificate before returning
    // If we can not verify the issued certificate using the CA certificate we don't want to issue this cert
    // because something is wrong...
    PublicKey verifyKey;
    // We must use the configured public key if this is a rootCA, because then we can renew our own certificate, after changing
    // the keys. In this case the _new_ key will not match the current CA certificate.
    if ((cacert != null) && (!isRootCA)) {
        verifyKey = cacert.getPublicKey();
    } else {
        verifyKey = caPublicKey;
    }
    cert.verify(verifyKey);

    // If we have a CA-certificate, verify that we have all path verification stuff correct
    if (cacert != null) {
        byte[] aki = CertTools.getAuthorityKeyId(cert);
        byte[] ski = CertTools.getSubjectKeyId(isRootCA ? cert : cacert);
        if ((aki != null) && (ski != null)) {
            boolean eq = Arrays.equals(aki, ski);
            if (!eq) {
                String akistr = new String(Hex.encode(aki));
                String skistr = new String(Hex.encode(ski));
                log.error(intres.getLocalizedMessage("signsession.errorpathverifykeyid", akistr, skistr));
            }
        }
        Principal issuerDN = cert.getIssuerX500Principal();
        Principal subjectDN = cacert.getSubjectX500Principal();
        if ((issuerDN != null) && (subjectDN != null)) {
            boolean eq = issuerDN.equals(subjectDN);
            if (!eq) {
                log.error(intres.getLocalizedMessage("signsession.errorpathverifydn", issuerDN.getName(),
                        subjectDN.getName()));
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("X509CA: generated certificate, CA " + this.getCAId() + " for DN: "
                + subject.getCertificateDN());
    }
    return cert;
}