Example usage for org.bouncycastle.asn1 DERSequence DERSequence

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

Introduction

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

Prototype

public DERSequence(ASN1Encodable[] elements) 

Source Link

Document

Create a sequence containing an array of objects.

Usage

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

public VOMSAttributeCertificate(String holderString, int holderSerialNumber, String issuerString,
        int productionSerial, long fromEpoch, long toEpoch, String[] fqans) throws Exception {
    try {//from w  w w.  j  av  a  2  s. c  o  m
        DEREncodableVector infoVector = new ASN1EncodableVector();

        this.setVersion();
        this.setHolder(holderString, holderSerialNumber);
        this.setIssuer(issuerString);
        this.setAlgorithmIdentifier();
        this.setSerialNumber(productionSerial);
        this.setTimes(new Date(fromEpoch), new Date(toEpoch));
        this.setVOMSFQANs(fqans);
        this.setExtensions();

        infoVector.add(version);
        infoVector.add(holder);
        infoVector.add(issuer);
        infoVector.add(signature);
        infoVector.add(serialNumber);
        infoVector.add(attrCertValidityPeriod);
        infoVector.add(attributes);
        infoVector.add(extensions);

        ASN1Sequence infoSequence = ASN1Sequence.getInstance(new DERSequence(infoVector));

        this.acinfo = new AttributeCertificateInfo(infoSequence);

        // Do it this way to match Vincenzo as much as possible
        // - rather than this way... this.signatureAlgorithm = new AlgorithmIdentifier( "1.2.840.113549.1.1.4" ) ;
        this.signatureAlgorithm = new AlgorithmIdentifier(new DERObjectIdentifier("1.2.840.113549.1.1.4"),
                (DEREncodable) null);

        this.signatureValue = new DERBitString(this.sign());

        this.ac = new AttributeCertificate(acinfo, signatureAlgorithm, signatureValue);

    } catch (Exception e) {
        // inspect?: 
        throw e;
    }

}

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

public void setVOMSFQANs(String[] fqans) throws Exception {
    try {//from   w  w w. j a  v a 2  s . c  o  m
        //--------------------------------------------------------------------------
        // put the FQANs into the SEQUENCE

        DEREncodableVector fqanVector = new ASN1EncodableVector();

        for (int f = 0; f < fqans.length; f++) {
            DERGeneralString fqan = new DERGeneralString(fqans[f]);
            ASN1OctetString fqanOctetString = ASN1OctetString.getInstance(new DEROctetString(fqan.getOctets()));
            fqanVector.add(fqanOctetString);
        }

        ASN1Sequence fqanSequence = ASN1Sequence.getInstance(new DERSequence(fqanVector));

        //--------------------------------------------------------------------------
        // put something into the undocumented TaggedObject

        DERGeneralString origin = new DERGeneralString("gridportal://newvoms:15000");

        ASN1OctetString originOctetString = ASN1OctetString.getInstance(new DEROctetString(origin.getOctets()));

        /*
         ASN1TaggedObject taggedObject2 = ASN1TaggedObject.getInstance( new DERTaggedObject( 6 , originOctetString ) , true ) ;
                
         ASN1TaggedObject taggedObject = ASN1TaggedObject.getInstance( new DERTaggedObject( 0 , taggedObject2 ) , true ) ;
                
         DEROctetString originOctetString = new DEROctetString( origin.getOctets() ) ;
         */

        DERTaggedObject taggedObject2 = new DERTaggedObject(6, originOctetString);

        DERTaggedObject taggedObject = new DERTaggedObject(0, taggedObject2);

        //--------------------------------------------------------------------------
        // put the taggedObject and then the fqanSequence into sequence2

        DEREncodableVector sequence2Vector = new ASN1EncodableVector();
        sequence2Vector.add(taggedObject);
        sequence2Vector.add(fqanSequence);
        ASN1Sequence sequence2 = ASN1Sequence.getInstance(new DERSequence(sequence2Vector));

        //--------------------------------------------------------------------------
        // the SET has one member - sequence2

        ASN1Set set = ASN1Set.getInstance(new DERSet(sequence2));

        //--------------------------------------------------------------------------
        // SEQUENCE sequence has an OID and the set

        DERObjectIdentifier voms4oid = new DERObjectIdentifier("1.3.6.1.4.1.8005.100.100.4");

        DEREncodableVector sequenceVector = new ASN1EncodableVector();
        sequenceVector.add(voms4oid);
        sequenceVector.add(set);
        ASN1Sequence sequence = ASN1Sequence.getInstance(new DERSequence(sequenceVector));

        //--------------------------------------------------------------------------

        this.attributes = ASN1Sequence.getInstance(new DERSequence(sequence));

    } catch (Exception e) {
        throw e;
    }

}

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

private DERSequence DNtoDERSequence(String thisDN) throws Exception {
    DERSequence this_sequence = null;

    try {//  www . j a  va2s . c  om
        DEREncodableVector this_overall_vector = new ASN1EncodableVector();

        String[] parts = thisDN.split("/");

        for (int p = 1; p < parts.length; p++) {

            int equals_position = parts[p].indexOf("=");

            String oid_string = parts[p].substring(0, equals_position);
            String value_string = parts[p].substring(equals_position + 1);
            String oid = Translate_OID.getOIDFromString(oid_string);
            if (oid.equals(oid_string)) {
                throw new Exception("unrecognised OID string :: " + oid);
            }

            DEREncodableVector this_vector = new ASN1EncodableVector();
            DERObjectIdentifier this_oid = new DERObjectIdentifier(oid);

            this_vector.add(this_oid);

            if (oid_string.equals("E")) {
                DERIA5String this_string = new DERIA5String(value_string);
                this_vector.add(this_string);
            } else {
                DERPrintableString this_string = new DERPrintableString(value_string);
                this_vector.add(this_string);
            }

            DERSet this_single_object_set = new DERSet(new DERSequence(this_vector));

            this_overall_vector.add(this_single_object_set);

        }

        this_sequence = new DERSequence(this_overall_vector);

    } catch (Exception e) {
        throw e;
    }

    return this_sequence;

}

From source file:nl.uva.vlet.grid.voms.VomsProxyCredential.java

License:Apache License

private void generateProxy() throws GeneralSecurityException {

    // Extension 1
    DERSequence seqac = new DERSequence(this.ac);
    DERSequence seqacwrap = new DERSequence(seqac);
    BouncyCastleX509Extension ace = new BouncyCastleX509Extension(VomsUtil.CERT_VOMS_EXTENSION_OID, seqacwrap);

    // Extension 2
    KeyUsage keyUsage = new KeyUsage(
            KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment);
    BouncyCastleX509Extension kue = new BouncyCastleX509Extension("2.5.29.15", keyUsage.getDERObject());

    // ==================================================================
    // Warning does not work with cog-jglobus-1.5 and higher,
    // but is necessary for now ! 
    // Else WMS doesn't recognize the VOMS information in the Proxy. 
    //// w  ww . j a  v a  2  s  .co  m
    X509ExtensionSet globusExtensionSet = null;
    //if (use_legacy_cog_1_4_extensions)
    {
        globusExtensionSet = new X509ExtensionSet();
        globusExtensionSet.add(ace);
        globusExtensionSet.add(kue);
    }

    // ================================================================== 
    // generate new VOMS proxy
    BouncyCastleCertProcessingFactory factory = BouncyCastleCertProcessingFactory.getDefault();
    vomsProxy = factory.createCredential(plainProxy.getCertificateChain(), plainProxy.getPrivateKey(),
            plainProxy.getStrength(), (int) plainProxy.getTimeLeft(), GSIConstants.DELEGATION_FULL,
            globusExtensionSet);

    infoPrintf("generateProxy() done.\n");
}

From source file:org.apache.cloudstack.utils.security.CertUtils.java

License:Apache License

public static X509Certificate generateV3Certificate(final X509Certificate caCert, final KeyPair caKeyPair,
        final PublicKey clientPublicKey, final String subject, final String signatureAlgorithm,
        final int validityDays, final List<String> dnsNames, final List<String> publicIPAddresses)
        throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException,
        InvalidKeyException, SignatureException, OperatorCreationException {

    final DateTime now = DateTime.now(DateTimeZone.UTC);
    final BigInteger serial = generateRandomBigInt();
    final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    final X509v3CertificateBuilder certBuilder;
    if (caCert == null) {
        // Generate CA certificate
        certBuilder = new JcaX509v3CertificateBuilder(new X500Name(subject), serial,
                now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Name(subject),
                clientPublicKey);//from   www.  ja  va 2  s .c  o  m

        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));
    } else {
        // Generate client certificate
        certBuilder = new JcaX509v3CertificateBuilder(caCert, serial, now.minusHours(12).toDate(),
                now.plusDays(validityDays).toDate(), new X500Principal(subject), clientPublicKey);

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(caCert));
    }

    certBuilder.addExtension(Extension.subjectKeyIdentifier, false,
            extUtils.createSubjectKeyIdentifier(clientPublicKey));

    final List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
    if (publicIPAddresses != null) {
        for (final String publicIPAddress : publicIPAddresses) {
            if (Strings.isNullOrEmpty(publicIPAddress)) {
                continue;
            }
            subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, publicIPAddress));
        }
    }
    if (dnsNames != null) {
        for (final String dnsName : dnsNames) {
            if (Strings.isNullOrEmpty(dnsName)) {
                continue;
            }
            subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, dnsName));
        }
    }
    if (subjectAlternativeNames.size() > 0) {
        final GeneralNames subjectAltNames = GeneralNames
                .getInstance(new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[] {})));
        certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    }

    final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC")
            .build(caKeyPair.getPrivate());
    final X509CertificateHolder certHolder = certBuilder.build(signer);
    final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
    if (caCert != null) {
        cert.verify(caCert.getPublicKey());
    } else {
        cert.verify(caKeyPair.getPublic());
    }
    return cert;
}

From source file:org.apache.http.contrib.auth.BouncySpnegoTokenGenerator.java

License:Apache License

public byte[] generateSpnegoDERObject(byte[] kerbTicket) throws IOException {
    DEROctetString ourKerberosTicket = new DEROctetString(kerbTicket);

    DERSequence kerbOidSeq = new DERSequence(kerbOid);
    DERTaggedObject tagged0 = new DERTaggedObject(0, kerbOidSeq);
    DERTaggedObject tagged2 = new DERTaggedObject(2, ourKerberosTicket);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(tagged0);//from  ww  w .  ja va 2 s.c o m
    v.add(tagged2);
    DERSequence seq = new DERSequence(v);
    DERTaggedObject taggedSpnego = new DERTaggedObject(0, seq);

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ASN1OutputStream asn1Out = new ASN1OutputStream(out);

    ASN1Object spnegoOIDASN1 = (ASN1Object) spnegoOid.toASN1Object();
    ASN1Object taggedSpnegoASN1 = (ASN1Object) taggedSpnego.toASN1Object();

    int length = spnegoOIDASN1.getDEREncoded().length + taggedSpnegoASN1.getDEREncoded().length;
    byte[] lenBytes = writeLength(length);
    byte[] appWrap = new byte[lenBytes.length + 1];

    appWrap[0] = 0x60;
    for (int i = 1; i < appWrap.length; i++) {
        appWrap[i] = lenBytes[i - 1];
    }

    asn1Out.write(appWrap);
    asn1Out.writeObject(spnegoOid.toASN1Object());
    asn1Out.writeObject(taggedSpnego.toASN1Object());

    byte[] app = out.toByteArray();
    ASN1InputStream in = new ASN1InputStream(app);

    if (log.isDebugEnabled()) {
        int skip = 12;
        byte[] manipBytes = new byte[app.length - skip];
        for (int i = skip; i < app.length; i++) {
            manipBytes[i - skip] = app[i];
        }
        ASN1InputStream ourSpnego = new ASN1InputStream(manipBytes);
        log.debug(ASN1Dump.dumpAsString(ourSpnego.readObject()));
    }

    return in.readObject().getDEREncoded();
}

From source file:org.apache.kerby.pkix.EndEntityGenerator.java

License:Apache License

/**
 * Generate certificate./*from ww w. ja  va  2  s.c  om*/
 *
 * @param issuerCert
 * @param issuerPrivateKey
 * @param publicKey
 * @param dn
 * @param validityDays
 * @param friendlyName
 * @return The certificate.
 * @throws InvalidKeyException
 * @throws SecurityException
 * @throws SignatureException
 * @throws NoSuchAlgorithmException
 * @throws DataLengthException
 * @throws CertificateException
 */
public static X509Certificate generate(X509Certificate issuerCert, PrivateKey issuerPrivateKey,
        PublicKey publicKey, String dn, int validityDays, String friendlyName)
        throws InvalidKeyException, SecurityException, SignatureException, NoSuchAlgorithmException,
        DataLengthException, CertificateException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    // Set certificate attributes.
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(issuerCert));
    certGen.setSubjectDN(new X509Principal(dn));

    certGen.setNotBefore(new Date());

    Calendar expiry = Calendar.getInstance();
    expiry.add(Calendar.DAY_OF_YEAR, validityDays);

    certGen.setNotAfter(expiry.getTime());

    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    // MAY set BasicConstraints=false or not at all.
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

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

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

    ASN1EncodableVector keyPurposeVector = new ASN1EncodableVector();
    keyPurposeVector.add(KeyPurposeId.id_kp_smartcardlogon);
    //keyPurposeVector.add( KeyPurposeId.id_kp_serverAuth );
    DERSequence keyPurposeOids = new DERSequence(keyPurposeVector);

    // If critical, will throw unsupported EKU.
    certGen.addExtension(X509Extensions.ExtendedKeyUsage, false, keyPurposeOids);

    ASN1EncodableVector pkinitSanVector = new ASN1EncodableVector();
    pkinitSanVector.add(ID_PKINIT_SAN);
    pkinitSanVector.add(new DERTaggedObject(0, new DERSequence()));
    DERSequence pkinitSan = new DERSequence(pkinitSanVector);

    String dnsName = "localhost";

    GeneralName name1 = new GeneralName(GeneralName.otherName, pkinitSan);
    GeneralName name2 = new GeneralName(GeneralName.dNSName, dnsName);

    GeneralNamesBuilder genNamesBuilder = new GeneralNamesBuilder();

    genNamesBuilder.addName(name1);
    genNamesBuilder.addName(name2);

    GeneralNames sanGeneralNames = genNamesBuilder.build();

    certGen.addExtension(X509Extensions.SubjectAlternativeName, true, sanGeneralNames);

    /*
     * The KDC MAY require the presence of an Extended Key Usage (EKU) KeyPurposeId
     * [RFC3280] id-pkinit-KPClientAuth in the extensions field of the client's
     * X.509 certificate.
     */

    /*
     * The digitalSignature key usage bit [RFC3280] MUST be asserted when the
     * intended purpose of the client's X.509 certificate is restricted with
     * the id-pkinit-KPClientAuth EKU.
     */

    /*
     * KDCs implementing this requirement SHOULD also accept the EKU KeyPurposeId
     * id-ms-kp-sc-logon (1.3.6.1.4.1.311.20.2.2) as meeting the requirement, as
     * there are a large number of X.509 client certificates deployed for use
     * with PKINIT that have this EKU.
     */

    // KDC
    /*
     * In addition, unless the client can otherwise verify that the public key
     * used to verify the KDC's signature is bound to the KDC of the target realm,
     * the KDC's X.509 certificate MUST contain a Subject Alternative Name extension
     * [RFC3280] carrying an AnotherName whose type-id is id-pkinit-san (as defined
     * in Section 3.2.2) and whose value is a KRB5PrincipalName that matches the
     * name of the TGS of the target realm (as defined in Section 7.3 of [RFC4120]).
     */

    /*
     * Unless the client knows by some other means that the KDC certificate is
     * intended for a Kerberos KDC, the client MUST require that the KDC certificate
     * contains the EKU KeyPurposeId [RFC3280] id-pkinit-KPKdc.
     */

    /*
     * The digitalSignature key usage bit [RFC3280] MUST be asserted when the
     * intended purpose of the KDC's X.509 certificate is restricted with the
     * id-pkinit-KPKdc EKU.
     */

    /*
     * If the KDC certificate contains the Kerberos TGS name encoded as an id-pkinit-san
     * SAN, this certificate is certified by the issuing CA as a KDC certificate,
     * therefore the id-pkinit-KPKdc EKU is not required.
     */

    /*
     * KDC certificates issued by Windows 2000 Enterprise CAs contain a dNSName
     * SAN with the DNS name of the host running the KDC, and the id-kp-serverAuth
     * EKU [RFC3280].
     */

    /*
     * KDC certificates issued by Windows 2003 Enterprise CAs contain a dNSName
     * SAN with the DNS name of the host running the KDC, the id-kp-serverAuth
     * EKU, and the id-ms-kp-sc-logon EKU.
     */

    /*
     * RFC: KDC certificates with id-pkinit-san SAN as specified in this RFC.
     * 
     * MS:  dNSName SAN containing the domain name of the KDC
     *      id-pkinit-KPKdc EKU
     *      id-kp-serverAuth EKU.
     */

    /*
     * Client certificates accepted by Windows 2000 and Windows 2003 Server KDCs
     * must contain an id-ms-san-sc-logon-upn (1.3.6.1.4.1.311.20.2.3) SAN and
     * the id-ms-kp-sc-logon EKU.  The id-ms-san-sc-logon-upn SAN contains a
     * UTF8-encoded string whose value is that of the Directory Service attribute
     * UserPrincipalName of the client account object, and the purpose of including
     * the id-ms-san-sc-logon-upn SAN in the client certificate is to validate
     * the client mapping (in other words, the client's public key is bound to
     * the account that has this UserPrincipalName value).
     */

    X509Certificate cert = certGen.generate(issuerPrivateKey);

    PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;

    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
            new SubjectKeyIdentifier(getDigest(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()))));

    return cert;
}

From source file:org.apache.poi.poifs.crypt.PkiTestUtils.java

License:Apache License

static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn, Date notBefore,
        Date notAfter, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey, boolean caFlag,
        int pathLength, String crlUri, String ocspUri, KeyUsage keyUsage)
        throws IOException, OperatorCreationException, CertificateException {
    String signatureAlgorithm = "SHA1withRSA";
    X500Name issuerName;//  ww  w.j  a  v  a 2 s.  com
    if (issuerCertificate != null) {
        issuerName = new X509CertificateHolder(issuerCertificate.getEncoded()).getIssuer();
    } else {
        issuerName = new X500Name(subjectDn);
    }

    RSAPublicKey rsaPubKey = (RSAPublicKey) subjectPublicKey;
    RSAKeyParameters rsaSpec = new RSAKeyParameters(false, rsaPubKey.getModulus(),
            rsaPubKey.getPublicExponent());

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(rsaSpec);

    DigestCalculator digestCalc = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()
            .get(CertificateID.HASH_SHA1);

    X509v3CertificateBuilder certificateGenerator = new X509v3CertificateBuilder(issuerName,
            new BigInteger(128, new SecureRandom()), notBefore, notAfter, new X500Name(subjectDn),
            subjectPublicKeyInfo);

    X509ExtensionUtils exUtils = new X509ExtensionUtils(digestCalc);
    SubjectKeyIdentifier subKeyId = exUtils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
    AuthorityKeyIdentifier autKeyId = (issuerCertificate != null)
            ? exUtils.createAuthorityKeyIdentifier(new X509CertificateHolder(issuerCertificate.getEncoded()))
            : exUtils.createAuthorityKeyIdentifier(subjectPublicKeyInfo);

    certificateGenerator.addExtension(Extension.subjectKeyIdentifier, false, subKeyId);
    certificateGenerator.addExtension(Extension.authorityKeyIdentifier, false, autKeyId);

    if (caFlag) {
        BasicConstraints bc;

        if (-1 == pathLength) {
            bc = new BasicConstraints(true);
        } else {
            bc = new BasicConstraints(pathLength);
        }
        certificateGenerator.addExtension(Extension.basicConstraints, false, bc);
    }

    if (null != crlUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        DERIA5String crlUriDer = new DERIA5String(crlUri);
        GeneralName gn = new GeneralName(uri, crlUriDer);

        DERSequence gnDer = new DERSequence(gn);
        GeneralNames gns = GeneralNames.getInstance(gnDer);

        DistributionPointName dpn = new DistributionPointName(0, gns);
        DistributionPoint distp = new DistributionPoint(dpn, null, null);
        DERSequence distpDer = new DERSequence(distp);
        certificateGenerator.addExtension(Extension.cRLDistributionPoints, false, distpDer);
    }

    if (null != ocspUri) {
        int uri = GeneralName.uniformResourceIdentifier;
        GeneralName ocspName = new GeneralName(uri, ocspUri);

        AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                X509ObjectIdentifiers.ocspAccessMethod, ocspName);

        certificateGenerator.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess);
    }

    if (null != keyUsage) {
        certificateGenerator.addExtension(Extension.keyUsage, true, keyUsage);
    }

    JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithm);
    signerBuilder.setProvider("BC");

    X509CertificateHolder certHolder = certificateGenerator.build(signerBuilder.build(issuerPrivateKey));

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    //        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    //        certificate = (X509Certificate) certificateFactory
    //                .generateCertificate(new ByteArrayInputStream(certificate
    //                        .getEncoded()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}

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. java2 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.cagrid.security.ssl.proxy.trust.ProxyCertInfo.java

License:Open Source License

/**
 * Returns the DER-encoded ASN.1 representation of the extension.
 * //from   w w  w . j  a va  2  s  .  c  o  m
 * @return <code>DERObject</code> the encoded representation of the
 *         extension.
 */
public DERObject getDERObject() {
    ASN1EncodableVector vec = new ASN1EncodableVector();

    if (this.pathLenConstraint != null) {
        vec.add(this.pathLenConstraint);
    }

    vec.add(this.proxyPolicy.getDERObject());

    return new DERSequence(vec);
}