Example usage for org.bouncycastle.jce PKCS10CertificationRequest PKCS10CertificationRequest

List of usage examples for org.bouncycastle.jce PKCS10CertificationRequest PKCS10CertificationRequest

Introduction

In this page you can find the example usage for org.bouncycastle.jce PKCS10CertificationRequest PKCS10CertificationRequest.

Prototype

public PKCS10CertificationRequest(ASN1Sequence sequence) 

Source Link

Usage

From source file:org.ejbca.util.CertToolsTest.java

License:Open Source License

@SuppressWarnings("unchecked")
public void test19getAltNameStringFromExtension() throws Exception {
    PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(p10ReqWithAltNames);
    CertificationRequestInfo info = p10.getCertificationRequestInfo();
    ASN1Set set = info.getAttributes();
    // The set of attributes contains a sequence of with type oid
    // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest
    Enumeration<Object> en = set.getObjects();
    boolean found = false;
    while (en.hasMoreElements()) {
        ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement());
        DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0);
        if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            // The object at position 1 is a SET of x509extensions
            DERSet s = (DERSet) seq.getObjectAt(1);
            X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0));
            X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName);
            if (ext != null) {
                found = true;//ww  w  . j  av  a2  s.  c  om
                String altNames = CertTools.getAltNameStringFromExtension(ext);
                assertEquals("dNSName=ort3-kru.net.polisen.se, iPAddress=10.252.255.237", altNames);
            }
        }
    }
    assertTrue(found);

    p10 = new PKCS10CertificationRequest(p10ReqWithAltNames2);
    info = p10.getCertificationRequestInfo();
    set = info.getAttributes();
    // The set of attributes contains a sequence of with type oid
    // PKCSObjectIdentifiers.pkcs_9_at_extensionRequest

    en = set.getObjects();
    found = false;
    while (en.hasMoreElements()) {
        ASN1Sequence seq = ASN1Sequence.getInstance(en.nextElement());
        DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0);
        if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            // The object at position 1 is a SET of x509extensions
            DERSet s = (DERSet) seq.getObjectAt(1);
            X509Extensions exts = X509Extensions.getInstance(s.getObjectAt(0));
            X509Extension ext = exts.getExtension(X509Extensions.SubjectAlternativeName);
            if (ext != null) {
                found = true;
                String altNames = CertTools.getAltNameStringFromExtension(ext);
                assertEquals("dNSName=foo.bar.com, iPAddress=10.0.0.1", altNames);
            }
        }
    }
    assertTrue(found);

}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request
 * //from  w  w w  . j a  va  2s  . c  om
 * @param inCertReq
 *            Certificate request
 * @param inUserCert
 *            Issuer certificate
 * @param inUserKey
 *            Issuer privateKey
 * @param pwd
 *            Issuer password
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public byte[] x509MakeProxyCert(byte[] inCertReq, byte[] inUserCert, byte[] inUserKey, String pwd1)
        throws CertificateException, GeneralSecurityException, Exception {
    X509Certificate[] userCert = null;
    PrivateKey pvk = null;

    // Read certificate request
    InputStream inTCertReq = null;

    inTCertReq = new ByteArrayInputStream(
            GrDPX509Util.readPEM(new ByteArrayInputStream(inCertReq), GrDPConstants.CRH, GrDPConstants.CRF));

    if ((inUserCert != null) && (inUserKey != null)) {
        // Reading chain of certificates from input stream
        userCert = GrDPX509Util
                .loadCertificateChain(new BufferedInputStream(new ByteArrayInputStream(inUserCert)));

        if (userCert.length <= 0) {
            logger.error("Invalid user certificate. Number of certificates in chain : " + userCert.length);
            throw new GeneralSecurityException("Invalid user certificate.");
        }

        pvk = PrivateKeyReader.read(new BufferedInputStream(new ByteArrayInputStream(inUserKey)), pwd1);
    } else {
        logger.error("Error, CreateProxyFromCertReq :: UserCertificate and UserKey can not be null.");
        throw new CertificateException(
                "Error, CreateProxyFromCertReq :: UserCertificate and UserKey can not be null.");
    }

    // Loading chian of certificates
    X509Certificate[] cp = new X509Certificate[userCert.length + 1];

    ASN1InputStream derin = new ASN1InputStream(inTCertReq);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((DERSequence) reqInfo);
    logger.debug("Number of Certificates in chain : " + Integer.toString(userCert.length));

    if (!certReq.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

    // Generating proxy certificate
    cp[0] = createProxyCertificate(userCert[0], pvk, certReq.getPublicKey(), lifetime, proxyType, "proxy");

    for (int index = 1; index <= userCert.length; ++index)
        cp[index] = userCert[index - 1];

    certProxy = cp[0];

    return GrDPX509Util.certChainToByte(cp);
}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request and a proxy
 * certificate//from  w  ww  .jav  a2 s.co m
 * 
 * @param inCertReq
 *            Certificate request
 * @param inProxy
 *            user proxy certificate 
 *            
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public byte[] x509MakeProxyCert(byte[] inCertReq, byte[] inProxy) throws IOException, GeneralSecurityException {

    // Holds the cert chain loaded from the proxy file
    X509Certificate[] proxyCertChain = null;

    // Holds the priv key loaded from the proxy file
    PrivateKey proxyPrivKey = null;

    // Holds the final certificate chain of the proxy
    X509Certificate[] finalCertChain = null;

    // Load the proxy certificate chain
    proxyCertChain = GrDPX509Util
            .loadCertificateChain(new BufferedInputStream(new ByteArrayInputStream(inProxy)));

    // Check for null arguments
    if (inCertReq == null || inProxy == null) {
        throw new GeneralSecurityException(
                "Either the cert request or proxy cert were passed as null arguments." + " Cannot continue.");
    }

    // Check for a valid chain
    if (proxyCertChain.length <= 0) {
        throw new GeneralSecurityException(
                "Invalid number of certificates in proxy chain: " + proxyCertChain.length);
    }
    logger.debug("Number of certificates in proxy chain: " + proxyCertChain.length);

    // Reading private key form proxy file
    FileCertReader fileReader = new FileCertReader();
    KeyStore store = fileReader.readProxy(new BufferedInputStream(new ByteArrayInputStream(inProxy)),
            "keypair");
    proxyPrivKey = (PrivateKey) store.getKey("host", "keypair".toCharArray());

    // Load the certificate request
    InputStream inTCertReq = new ByteArrayInputStream(
            GrDPX509Util.readPEM(new ByteArrayInputStream(inCertReq), GrDPConstants.CRH, GrDPConstants.CRF));
    ASN1InputStream derin = new ASN1InputStream(inTCertReq);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((DERSequence) reqInfo);

    // Verify cert request validity
    if (!certReq.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

    // Generating proxy certificate
    finalCertChain = new X509Certificate[proxyCertChain.length + 1];
    finalCertChain[0] = createProxyCertificate(proxyCertChain[0], proxyPrivKey, certReq.getPublicKey(),
            lifetime, proxyType, "proxy");

    for (int i = 0; i < proxyCertChain.length; ++i) {
        finalCertChain[i + 1] = proxyCertChain[i];
    }

    // TODO: this should be removed at some point
    certProxy = finalCertChain[0];

    return GrDPX509Util.certChainToByte(finalCertChain);
}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Creates a proxy certificate from a certificate request
 * //from  w  w w  .  ja v  a 2s . c  o  m
 * @param inCertReq
 *            Certificate request
 * @param inUserCert
 *            Issuer certificate
 * @param inUserKey
 *            Issuer privateKey
 * @param pwd
 *            Issuer password
 * @return chaine of certificate containing proxy in first place
 * @deprecated Use proxy generator from util-java
 */
public X509Certificate[] createProxyFromCertReq(InputStream inCertReq, BufferedInputStream inUserCert,
        InputStream inUserKey, String pwd1) throws GeneralSecurityException, IOException, Exception {

    X509Certificate[] userCert = null;
    PrivateKey userPrivKey = null;
    PKCS10CertificationRequest certRequest = null;
    X509Certificate[] proxyCert = null;

    // Load the user certificate
    userCert = GrDPX509Util.loadCertificateChain(inUserCert);
    logger.debug("User Certificate - number of certificates in chain: " + userCert.length);

    // Load the private key
    userPrivKey = PrivateKeyReader.read(new BufferedInputStream(inUserKey), pwd1);

    // Load the certificate request
    ASN1InputStream derin = new ASN1InputStream(
            new ByteArrayInputStream(GrDPX509Util.readPEM(inCertReq, GrDPConstants.CRH, GrDPConstants.CRF)));
    DERObject reqInfo = derin.readObject();
    certRequest = new PKCS10CertificationRequest((DERSequence) reqInfo);

    // Initialize the proxy certificate chain
    proxyCert = new X509Certificate[userCert.length + 1];

    // Verify integrity of certificate request
    if (!certRequest.verify()) {
        throw new GeneralSecurityException("Certificate request verification failed.");
    }

    // Create the proxy certificate
    proxyCert[0] = createProxyCertificate(userCert[0], userPrivKey, certRequest.getPublicKey(), lifetime,
            proxyType, "proxy");

    // Complete the proxy certificate chain
    for (int index = 1; index <= userCert.length; ++index)
        proxyCert[index] = userCert[index - 1];

    certProxy = proxyCert[0];

    return proxyCert;
}

From source file:org.glite.security.delegation.GrDPX509Util.java

License:Apache License

/**
 * Reconstruct a certificate request from a PEM encoded string.
 * @param request BASE64 PEM encoded string
 * @return certificate request//from w w  w. j a  va  2s. c  o  m
 * @deprecated Use delegation storage or org.glite.security.util.FileCertReader.
 */
public static PKCS10CertificationRequest loadCertificateRequest(String request) {
    return new PKCS10CertificationRequest(readPEM(request, GrDPConstants.CRH + GrDPConstants.NEWLINE,
            GrDPConstants.CRF + GrDPConstants.NEWLINE));
}

From source file:org.glite.slcs.caclient.impl.CMPRequest.java

License:eu-egee.org license

private static CertTemplate makeCertTemplate(CertificateRequest certRequest, String issuerDN) {
    PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(certRequest.getDEREncoded());
    CertificationRequestInfo pkcs10info = pkcs10.getCertificationRequestInfo();

    log.debug("Constructing CMP CertTemplate...");
    CertTemplate certTemplate = new CertTemplate();
    certTemplate.setPublicKey(pkcs10info.getSubjectPublicKeyInfo());
    certTemplate.setSubject(pkcs10info.getSubject());
    certTemplate.setIssuer(new X509Name(issuerDN));

    // validity//w  w w.jav  a  2  s  . c  om
    OptionalValidity validity = new OptionalValidity();
    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    // five minutes extra to before/after
    date.add(Calendar.MINUTE, -5);
    Time notBefore = new Time(date.getTime());
    date.add(Calendar.MINUTE, 5);
    // TODO: lifetime fixed to 1 mio seconds, should be possible to configure by user
    date.add(Calendar.SECOND, 1000000);
    Time notAfter = new Time(date.getTime());
    validity.setNotBefore(notBefore);
    validity.setNotAfter(notAfter);
    certTemplate.setValidity(validity);

    log.debug("Constructed " + certTemplate.toString());

    return certTemplate;
}

From source file:org.glite.wms.wmproxy.WMProxyAPI.java

License:Apache License

/**
 * Generates a proxy from the input certificate and from the user proxy file
 * on the user local machine (which path has to be specified as input
 * parameter in one of the class costructors) This service is called after
 * the getProxyReq the input proxy string of this service is the string got
 * by getProxyReq./*from w w w. ja  v  a 2s. c o m*/
 * 
 * @param certReq
 *            Service certificate request
 * @return the generated proxy certificate
 * @throws CredentialException
 *             in case of any error with the local user proxy
 */

private String createProxyfromCertReq(String certReq) throws CredentialException {

    int lifetime = 0;
    X509Certificate[] parentCertChain = null;
    PrivateKey userKey = null;

    try {

        FileCertReader certReader = new FileCertReader();
        ByteArrayInputStream inStr = new ByteArrayInputStream(this.proxyPEM.getBytes());
        BufferedInputStream buffInStr = new BufferedInputStream(inStr);
        Vector<X509Certificate> vCerts = certReader.readCertChain(buffInStr);
        parentCertChain = new X509Certificate[vCerts.size()];
        vCerts.toArray(parentCertChain);
        buffInStr.close();

        inStr = new ByteArrayInputStream(this.proxyPEM.getBytes());
        buffInStr = new BufferedInputStream(inStr);
        userKey = PrivateKeyReader.read(buffInStr);

        Date now = new Date();
        lifetime = (int) (parentCertChain[0].getNotAfter().getTime() - now.getTime()) / 3600000;
        if (lifetime < 0) {
            throw new CredentialException("the local proxy has expired ");
        }

        /*
         * TODO PEM to DER conversion
         */
        byte[] derPKCS10 = null;
        PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest(derPKCS10);

        ProxyCertificateGenerator generator = new ProxyCertificateGenerator(parentCertChain, pkcs10);
        generator.setLifetime(lifetime);
        generator.generate(userKey);
        return generator.getProxyAsPEM();

    } catch (Exception exc) {
        throw new CredentialException(exc.getMessage());
    }

}

From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java

License:Apache License

/**
 * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new
 * certificate)//ww  w.  j a v  a2 s .  c om
 *
 * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet,
 *      String) createProxyCertificate
 * @param certRequestInputStream
 *            the input stream to read the certificate request from.
 * @param cert
 *            the issuer certificate
 * @param privateKey
 *            the private key to sign the new certificate with.
 * @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 delegationMode
 *            the type of proxy credential to create
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy certificate. Can be null. If
 *            delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_4_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 IOException
 *                if error reading the certificate request
 * @exception GeneralSecurityException
 *                if a security error occurs.
 * @deprecated
 */
public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet, String cnValue)
        throws IOException, GeneralSecurityException {

    ASN1InputStream derin = new ASN1InputStream(certRequestInputStream);
    ASN1Primitive reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        String err = i18n.getMessage("certReqVerification");
        throw new GeneralSecurityException(err);
    }

    return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, delegationMode, extSet,
            cnValue);
}

From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java

License:Apache License

/**
 * Creates a proxy certificate from the certificate request. (Signs a certificate request creating a new
 * certificate)//from ww w  .  java  2 s . c om
 *
 * @see #createProxyCertificate(X509Certificate, PrivateKey, PublicKey, int, int, X509ExtensionSet,
 *      String) createProxyCertificate
 * @param certRequestInputStream
 *            the input stream to read the certificate request from.
 * @param cert
 *            the issuer certificate
 * @param privateKey
 *            the private key to sign the new certificate with.
 * @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 certType
 *            the type of proxy credential to create
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy certificate. Can be null. If
 *            delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_4_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 IOException
 *                if error reading the certificate request
 * @exception GeneralSecurityException
 *                if a security error occurs.
 */
public X509Certificate createCertificate(InputStream certRequestInputStream, X509Certificate cert,
        PrivateKey privateKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet,
        String cnValue) throws IOException, GeneralSecurityException {

    ASN1InputStream derin = new ASN1InputStream(certRequestInputStream);
    ASN1Primitive reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        String err = i18n.getMessage("certReqVerification");
        throw new GeneralSecurityException(err);
    }

    return createProxyCertificate(cert, privateKey, certReq.getPublicKey(), lifetime, certType, extSet,
            cnValue);
}

From source file:org.ntnu.utility.NorduGridCertificateRequest.java

License:Open Source License

/**
 * Reads a certificate request file in PKCS10 and PEM format.
 *//*from w w  w.  j  a  v a  2s  . c o m*/
public boolean readFromFile(String filepath) {

    try {

        String base64string;
        base64string = getCertFileContent(filepath);

        byte[] certData = Base64.decode(base64string);
        certreq = new PKCS10CertificationRequest(certData);

        // read info from cert request
        CertificationRequestInfo certinfo = certreq.getCertificationRequestInfo();
        X509Name x509name = certinfo.getSubject();

        readAttributes(x509name);

        this.publickey = certreq.getPublicKey();

    } catch (Exception e) {
        //e.printStackTrace();
        return false;
    }

    populated = true;
    return true;

}