Example usage for org.bouncycastle.asn1 DEREncodableVector DEREncodableVector

List of usage examples for org.bouncycastle.asn1 DEREncodableVector DEREncodableVector

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DEREncodableVector DEREncodableVector.

Prototype

public DEREncodableVector() 

Source Link

Usage

From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java

License:Open Source License

/**
 * Utility method for generating a "standard" server certificate. Recognized by most
 * browsers as valid for SSL/TLS.  These certificates are generated de novo, not from
 * a template, so they will not retain the structure of the original certificate and may
 * not be suitable for applications that require Extended Validation/High Assurance SSL
 * or other distinct extensions or EKU./*from  w w w.j av a2s.co  m*/
 *
 * @param newPubKey
 * @param caCert
 * @param caPrivateKey
 * @param hostname
 * @return
 * @throws CertificateParsingException
 * @throws SignatureException
 * @throws InvalidKeyException
 * @throws CertificateExpiredException
 * @throws CertificateNotYetValidException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
@SuppressWarnings({ "deprecation", "unused" })
public static X509Certificate generateStdSSLServerCertificate(final PublicKey newPubKey,
        final X509Certificate caCert, final PrivateKey caPrivateKey, final String subject)
        throws CertificateParsingException, SignatureException, InvalidKeyException,
        CertificateExpiredException, CertificateNotYetValidException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {
    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    v3CertGen.setSubjectDN(new X500Principal(subject));
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);
    v3CertGen.setPublicKey(newPubKey);
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 30L * 60 * 60 * 24 * 30 * 12));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30 * 12));
    v3CertGen.setIssuerDN(caCert.getSubjectX500Principal());

    // Firefox actually tracks serial numbers within a CA and refuses to validate if it sees duplicates
    // This is not a secure serial number generator, (duh!) but it's good enough for our purposes.
    v3CertGen.setSerialNumber(new BigInteger(Long.toString(System.currentTimeMillis())));

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

    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(newPubKey));

    v3CertGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert.getPublicKey()));

    //       Firefox 2 disallows these extensions in an SSL server cert.  IE7 doesn't care.
    //      v3CertGen.addExtension(
    //            X509Extensions.KeyUsage,
    //            false,
    //            new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature ) );

    DEREncodableVector typicalSSLServerExtendedKeyUsages = new DEREncodableVector();

    typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
    typicalSSLServerExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.clientAuth));
    typicalSSLServerExtendedKeyUsages
            .add(new DERObjectIdentifier(ExtendedKeyUsageConstants.netscapeServerGatedCrypto));
    typicalSSLServerExtendedKeyUsages
            .add(new DERObjectIdentifier(ExtendedKeyUsageConstants.msServerGatedCrypto));

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new DERSequence(typicalSSLServerExtendedKeyUsages));

    //  Disabled by default.  Left in comments in case this is desired.
    //
    //      v3CertGen.addExtension(
    //            X509Extensions.AuthorityInfoAccess,
    //            false,
    //            new AuthorityInformationAccess(new DERObjectIdentifier(OID_ID_AD_CAISSUERS),
    //                  new GeneralName(GeneralName.uniformResourceIdentifier, "http://" + subject + "/aia")));

    //      v3CertGen.addExtension(
    //            X509Extensions.CRLDistributionPoints,
    //            false,
    //            new CRLDistPoint(new DistributionPoint[] {}));

    X509Certificate cert = v3CertGen.generate(caPrivateKey, "BC");

    return cert;
}

From source file:net.lightbody.bmp.proxy.selenium.CertificateCreator.java

License:Open Source License

/**
 * Creates a typical Certification Authority (CA) certificate.
 * @param keyPair//from w  w  w.ja va 2  s.c  om
 * @throws SecurityException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@SuppressWarnings("deprecation")
public static X509Certificate createTypicalMasterCert(final KeyPair keyPair)
        throws SignatureException, InvalidKeyException, SecurityException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    X509Principal issuer = new X509Principal(
            "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US");

    // Create
    v3CertGen.setSerialNumber(BigInteger.valueOf(1));
    v3CertGen.setIssuerDN(issuer);
    v3CertGen.setSubjectDN(issuer);

    //Set validity period
    v3CertGen
            .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30)));
    v3CertGen
            .setNotAfter(new Date(System.currentTimeMillis() + 240 /* months */ * (1000L * 60 * 60 * 24 * 30)));

    //Set signature algorithm & public key
    v3CertGen.setPublicKey(keyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);

    // Add typical extensions for signing cert
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

    v3CertGen.addExtension(X509Extensions.KeyUsage, false,
            new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign));

    DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector();

    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown));

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalCAExtendedKeyUsages));

    X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC");

    cert.checkValidity(new Date());

    cert.verify(keyPair.getPublic());

    return cert;
}

From source file:org.browsermob.proxy.selenium.CertificateCreator.java

License:Open Source License

/**
 * Creates a typical Certification Authority (CA) certificate.
 * @param keyPair//from w w  w  . java 2 s . c om
 * @throws SecurityException
 * @throws InvalidKeyException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
@SuppressWarnings("deprecation")
public static X509Certificate createTypicalMasterCert(final KeyPair keyPair)
        throws SignatureException, InvalidKeyException, SecurityException, CertificateException,
        NoSuchAlgorithmException, NoSuchProviderException {

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    X509Principal issuer = new X509Principal(
            "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US");

    // Create
    v3CertGen.setSerialNumber(BigInteger.valueOf(1));
    v3CertGen.setIssuerDN(issuer);
    v3CertGen.setSubjectDN(issuer);

    //Set validity period
    v3CertGen
            .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30)));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + 48 /* months */ * (1000L * 60 * 60 * 24 * 30)));

    //Set signature algorithm & public key
    v3CertGen.setPublicKey(keyPair.getPublic());
    v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO);

    // Add typical extensions for signing cert
    v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(keyPair.getPublic()));

    v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));

    v3CertGen.addExtension(X509Extensions.KeyUsage, false,
            new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign));

    DEREncodableVector typicalCAExtendedKeyUsages = new DEREncodableVector();

    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning));
    typicalCAExtendedKeyUsages.add(new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown));

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new DERSequence(typicalCAExtendedKeyUsages));

    X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC");

    cert.checkValidity(new Date());

    cert.verify(keyPair.getPublic());

    return cert;
}

From source file:org.glite.voms.ac.ACCerts.java

License:Open Source License

/**
 * Makes a DERObject representation.//w  ww  . ja va 2s .c  o  m
 *
 * @return the DERObject
 */
public ASN1Primitive toASN1Primitive() {
    DEREncodableVector v = new DEREncodableVector();

    ListIterator li = l.listIterator();
    while (li.hasNext()) {
        X509CertificateStructure x509 = (X509CertificateStructure) li.next();
        v.add(x509);
    }
    return new DERSequence(v);
}

From source file:org.glite.voms.ac.ACGenerator.java

License:eu-egee.org license

public AttributeCertificateInfo generateACInfo() {
    if ((issuer == null) || (holderIssuer == null) || (holderSerial == null) || (notAfter == null)
            || (notBefore == null)) {/*from w w  w. j  a v a  2  s. com*/
        throw new IllegalArgumentException("All mandatory components are not present");
    }

    DEREncodableVector v = new DEREncodableVector();
    v.add(new DERInteger(1));
    v.add(new Holder(holderIssuer, holderSerial));
    v.add(new AttCertIssuer(new V2Form(Util.x500nameToGeneralNames(issuer))));
    v.add(new AlgorithmIdentifier("1.2.840.113549.1.1.5")); // sha1WithRSA
    v.add(new DERInteger(1));

    return null;
}

From source file:org.glite.voms.ac.ACTargets.java

License:Open Source License

/**
 * Makes a DERObject representation./*from ww  w .  ja  va2s.  c o  m*/
 *
 * @return the DERObject
 */
public ASN1Primitive toASN1Primitive() {
    DEREncodableVector v = new DEREncodableVector();

    ListIterator li = l.listIterator();
    while (li.hasNext()) {
        ACTarget c = (ACTarget) li.next();
        v.add(c);
    }
    return new DERSequence(v);
}

From source file:org.glite.voms.ac.AttributeCertificateInfo.java

License:eu-egee.org license

public AttributeCertificateInfo(ASN1Sequence seq) throws IOException {
    DERObjectIdentifier AC_TARGET_OID_DER = new DERObjectIdentifier(AC_TARGET_OID);
    DERObjectIdentifier AC_CERTS_OID_DER = new DERObjectIdentifier(AC_CERTS_OID);
    DERObjectIdentifier AC_FULL_ATTRIBUTES_OID_DER = new DERObjectIdentifier(AC_FULL_ATTRIBUTES_OID);
    version = (DERInteger) seq.getObjectAt(0);
    holder = new Holder((ASN1Sequence) seq.getObjectAt(1));
    issuer = new AttCertIssuer(seq.getObjectAt(2));
    signature = new AlgorithmIdentifier((ASN1Sequence) seq.getObjectAt(3));
    serialNumber = (DERInteger) seq.getObjectAt(4);

    // VOMS has encoding problems of attCertValidity (uses PrivateKeyUsagePeriod syntax instead)
    ASN1Sequence s2 = (ASN1Sequence) seq.getObjectAt(5);
    ASN1Sequence s3 = s2;/*from ww  w  .j a  v a2s .  c  o m*/

    if (s2.getObjectAt(0) instanceof ASN1TaggedObject) {
        badVomsEncoding = true;

        DEREncodableVector v = new DEREncodableVector();

        for (int i = 0; i < 2; i++) {
            byte[] bb = ((DEROctetString) ((ASN1TaggedObject) s2.getObjectAt(i)).getObject()).getOctets();
            v.add(new DERGeneralizedTime(new String(bb)));
        }

        s3 = (ASN1Sequence) new DERSequence(v);
    }

    attrCertValidityPeriod = AttCertValidityPeriod.getInstance(s3);
    attributes = (ASN1Sequence) seq.getObjectAt(6);

    // getting FQANs
    //        System.out.println("Getting FQANs");
    if (attributes != null && attributes.size() != 0) {
        for (Enumeration e = attributes.getObjects(); e.hasMoreElements();) {
            //                 DERObject o = (DERObject)e.nextElement();
            //                 byte[] value = null;
            //                 try {
            //                     value = o.getEncoded();
            //                 }
            //                 catch(Exception ex) {}
            //                 System.out.println("Class is: " + o.getClass());
            //                 System.out.print("Value is: ");
            //                 for (int i =0; i < value.length; i++)
            //                     System.out.print(Integer.toHexString(value[i]) + " ");
            //                 System.out.println();

            ASN1Sequence attribute = (ASN1Sequence) e.nextElement();

            if (VOMS_ATTR_OID.equals(((DERObjectIdentifier) attribute.getObjectAt(0)).getId())) {
                DLSet set = (DLSet) attribute.getObjectAt(1);

                for (Enumeration s = set.getObjects(); s.hasMoreElements();) {
                    IetfAttrSyntax attr = new IetfAttrSyntax((ASN1Sequence) s.nextElement());
                    String url = ((DERIA5String) GeneralName
                            .getInstance(
                                    ((ASN1Sequence) attr.getPolicyAuthority().toASN1Primitive()).getObjectAt(0))
                            .getName()).getString();
                    int idx = url.indexOf("://");

                    if ((idx < 0) || (idx == (url.length() - 1))) {
                        throw new IllegalArgumentException(
                                "Bad encoding of VOMS policyAuthority : [" + url + "]");
                    }

                    myVo = url.substring(0, idx);
                    myHostPort = url.substring(idx + 3);

                    idx = myHostPort.lastIndexOf(":");

                    if ((idx < 0) || (idx == (myHostPort.length() - 1))) {
                        throw new IllegalArgumentException(
                                "Bad encoding of VOMS policyAuthority : [" + url + "]");
                    }

                    myHost = myHostPort.substring(0, idx);
                    myPort = Integer.valueOf(myHostPort.substring(idx + 1)).intValue();

                    if (attr.getValueType() != IetfAttrSyntax.VALUE_OCTETS) {
                        throw new IllegalArgumentException(
                                "VOMS attribute values are not encoded as octet strings, policyAuthority = "
                                        + url);
                    }

                    for (Iterator j = attr.getValues().iterator(); j.hasNext();) {
                        String fqan = new String(((ASN1OctetString) j.next()).getOctets());
                        FQAN f = new FQAN(fqan);

                        // maybe requiring that the attributes start with vo is too much?
                        if (!myStringList.contains(fqan)
                                && (fqan.startsWith("/" + myVo + "/") || fqan.equals("/" + myVo))) {
                            myStringList.add(fqan);
                            myFQANs.add(f);
                        }
                    }
                }
            }
        }
    }

    // check if the following two can be detected better!!! 
    // for example, is it possible to have only the extensions? how to detect this?
    if (seq.size() > 8) {
        issuerUniqueID = new DERBitString(seq.getObjectAt(7));
        extensions = new X509Extensions((ASN1Sequence) seq.getObjectAt(8));
    } else if (seq.size() > 7) {
        extensions = new X509Extensions((ASN1Sequence) seq.getObjectAt(7));
    }

    // start parsing of known extensions
    //        System.out.println("Getting AC_TARGET");
    if (extensions.getExtension(AC_TARGET_OID_DER) != null) {
        byte[] data = (extensions.getExtension(AC_TARGET_OID_DER).getValue().getOctets());
        ASN1Primitive dobj = null;
        try {
            dobj = new ASN1InputStream(new ByteArrayInputStream(data)).readObject();

            //            System.out.println("DOBJ Class: " + dobj.getClass());
            acTargets = new ACTargets(ASN1Sequence.getInstance(dobj));
        } catch (Exception e) {
            throw new IllegalArgumentException("DERO: " + e.getMessage(), e);
        }
    }

    //        System.out.println("Getting AC_CERTS");
    if (extensions.getExtension(AC_CERTS_OID_DER) != null) {
        byte[] data = (extensions.getExtension(AC_CERTS_OID_DER).getValue().getOctets());
        ASN1Primitive dobj = null;
        try {
            dobj = new ASN1InputStream(new ByteArrayInputStream(data)).readObject();
            //             System.out.println("DOBJ Class: " + dobj.getClass());
            acCerts = new ACCerts(ASN1Sequence.getInstance(dobj));
        } catch (Exception e) {
            throw new IllegalArgumentException("DERO: " + e.getMessage(), e);
        }
    }

    //        System.out.println("Getting FULL_ATTRIBUTES");
    if (extensions.getExtension(AC_FULL_ATTRIBUTES_OID_DER) != null) {
        byte[] data = (extensions.getExtension(AC_FULL_ATTRIBUTES_OID_DER).getValue().getOctets());
        ASN1Primitive dobj = null;
        try {
            dobj = new ASN1InputStream(new ByteArrayInputStream(data)).readObject();

            //             System.out.println("DOBJ Class: " + dobj.getClass());
            fullAttributes = new FullAttributes(ASN1Sequence.getInstance(dobj));
        } catch (Exception e) {
            throw new IllegalArgumentException("DERO: " + e.getMessage());
        }
    }
}

From source file:org.glite.voms.ac.AttributeCertificateInfo.java

License:eu-egee.org license

/**
 * Produce an object suitable for an ASN1OutputStream.
 *
 * <pre>/*from   w ww .  j  av  a  2s .  c  om*/
 *
 *
 *
 *     AttributeCertificateInfo ::= SEQUENCE {
 *          version              AttCertVersion -- version is v2,
 *          holder               Holder,
 *          issuer               AttCertIssuer,
 *          signature            AlgorithmIdentifier,
 *          serialNumber         CertificateSerialNumber,
 *          attrCertValidityPeriod   AttCertValidityPeriod,
 *          attributes           SEQUENCE OF Attribute,
 *          issuerUniqueID       UniqueIdentifier OPTIONAL,
 *          extensions           Extensions OPTIONAL
 *     }
 *
 *     AttCertVersion ::= INTEGER { v2(1) }
 *
 *
 *
 * </pre>
 */
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(version);
    v.add(holder);
    v.add(issuer);
    v.add(signature);
    v.add(serialNumber);

    if (!badVomsEncoding) {
        v.add(attrCertValidityPeriod);
    } else {
        DEREncodableVector v2 = new DEREncodableVector();
        v2.add(new DERTaggedObject(false, 0, new DEROctetString(
                (attrCertValidityPeriod.getNotBeforeTime().getTime().substring(0, 14) + "Z").getBytes())));
        v2.add(new DERTaggedObject(false, 1, new DEROctetString(
                (attrCertValidityPeriod.getNotAfterTime().getTime().substring(0, 14) + "Z").getBytes())));
        v.add(new DERSequence(v2));
    }

    v.add(attributes);

    if (issuerUniqueID != null) {
        v.add(issuerUniqueID);
    }

    if (extensions != null) {
        v.add(extensions);
    }

    return new DERSequence(v);
}

From source file:org.glite.voms.ac.AttributeHolder.java

License:Open Source License

/**
 * Makes a DERObject representation./*from   w  w  w  .j  a v a  2  s  . c  o  m*/
 *
 * @return the DERObject
 */
public ASN1Primitive toASN1Primitive() {
    DEREncodableVector v = new DEREncodableVector();

    v.add(grantor);

    DEREncodableVector v2 = new DEREncodableVector();

    for (ListIterator li = l.listIterator(); li.hasNext();) {
        GenericAttribute att = (GenericAttribute) li.next();
        v2.add(att);
    }
    ASN1Sequence seq = (ASN1Sequence) new DERSequence(v2);

    v.add(seq);

    return new DERSequence(v);
}

From source file:org.glite.voms.ac.FullAttributes.java

License:Open Source License

/**
 * Makes a DERObject representation./*w  w w.j  a  v a 2 s  .  c  o m*/
 *
 * @return the DERObject
 */
public ASN1Primitive toASN1Primitive() {
    DEREncodableVector v2 = new DEREncodableVector();

    for (ListIterator li = l.listIterator(); li.hasNext();) {
        AttributeHolder holder = (AttributeHolder) li.next();
        v2.add(holder);
    }

    ASN1Sequence seq = (ASN1Sequence) new DERSequence(v2);
    DEREncodableVector v = new DEREncodableVector();
    v.add(seq);

    return new DERSequence(v);
}