Example usage for org.bouncycastle.jce PKCS10CertificationRequest getPublicKey

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

Introduction

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

Prototype

public PublicKey getPublicKey() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException 

Source Link

Document

return the public key associated with the certification request - the public key is created using the BC provider.

Usage

From source file:net.link.util.common.KeyUtils.java

License:Open Source License

public static X509Certificate generateCertificate(PKCS10CertificationRequest csr, PrivateKey issuerPrivateKey,
        X509Certificate issuerCert, DateTime notBefore, DateTime notAfter, String inSignatureAlgorithm,
        boolean caCert, boolean timeStampingPurpose, URI ocspUri)
        throws InvalidKeyException, NoSuchAlgorithmException {

    try {// w ww  . java2 s  . co m
        return generateCertificate(csr.getPublicKey(),
                csr.getCertificationRequestInfo().getSubject().toString(), issuerPrivateKey, issuerCert,
                notBefore, notAfter, inSignatureAlgorithm, caCert, timeStampingPurpose, ocspUri);
    } catch (NoSuchProviderException e) {
        throw new InternalInconsistencyException(e);
    }
}

From source file:org.apache.cloudstack.ca.provider.RootCAProvider.java

License:Apache License

private Certificate generateCertificateUsingCsr(final String csr, final List<String> domainNames,
        final List<String> ipAddresses, final int validityDays)
        throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, CertificateException,
        SignatureException, IOException, OperatorCreationException {
    PemObject pemObject = null;// w  ww  .  j  a v a2s . c  o m

    try {
        final PemReader pemReader = new PemReader(new StringReader(csr));
        pemObject = pemReader.readPemObject();
    } catch (IOException e) {
        LOG.error("Failed to read provided CSR string as a PEM object", e);
    }

    if (pemObject == null) {
        throw new CloudRuntimeException("Unable to read/process CSR: " + csr);
    }

    final PKCS10CertificationRequest request = new PKCS10CertificationRequest(pemObject.getContent());

    final String subject = request.getCertificationRequestInfo().getSubject().toString();
    final X509Certificate clientCertificate = CertUtils.generateV3Certificate(caCertificate, caKeyPair,
            request.getPublicKey(), subject, CAManager.CertSignatureAlgorithm.value(), validityDays,
            domainNames, ipAddresses);
    return new Certificate(clientCertificate, null, Collections.singletonList(caCertificate));
}

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

License:Open Source License

/**
 * Creates a proxy certificate from the certificate request. (Signs a
 * certificate request creating a new certificate)
 * /* w  w  w. j a v a2 s . c o  m*/
 * @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 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 IOException
 *                if error reading the certificate request
 * @exception GeneralSecurityException
 *                if a security error occurs.
 */
public X509Certificate createCertificate(String provider, InputStream certRequestInputStream,
        X509Certificate cert, PrivateKey privateKey, int lifetime, int delegationMode, X509ExtensionSet extSet,
        String cnValue, String signatureAlgorithm) throws IOException, GeneralSecurityException {

    DERInputStream derin = new DERInputStream(certRequestInputStream);
    DERObject reqInfo = derin.readObject();
    PKCS10CertificationRequest certReq = new PKCS10CertificationRequest((ASN1Sequence) reqInfo);

    boolean rs = certReq.verify();

    if (!rs) {
        throw new GeneralSecurityException("Certificate request verification failed!");
    }

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

From source file:org.deviceconnect.android.ssl.CertificateAuthority.java

License:MIT License

/**
 * ??????.//from ww  w  . j  a  v a 2s .c  om
 *
 * @param pkcs10 PKCS#10?????.
 * @return ???????. ?????null
 */
byte[] requestCertificate(final byte[] pkcs10) {
    try {
        if (getRootCertificate() == null) {
            return null;
        }

        // ??
        PKCS10CertificationRequest request = new PKCS10CertificationRequest(pkcs10);
        PrivateKey signingKey = mRootKeyStoreMgr.getPrivateKey(mIssuerName);
        KeyPair keyPair = new KeyPair(request.getPublicKey(), signingKey);
        X500Principal subject = new X500Principal("CN=localhost");
        X500Principal issuer = new X500Principal("CN=" + mIssuerName);
        GeneralNames generalNames = parseSANs(request);

        // 
        Certificate certificate = mRootKeyStoreMgr.generateX509V3Certificate(keyPair, subject, issuer,
                generalNames, false);
        return certificate.getEncoded();
    } catch (GeneralSecurityException e) {
        mLogger.log(Level.SEVERE, "Failed to generate certificate to byte array.", e);
    } catch (IOException e) {
        mLogger.log(Level.SEVERE, "Failed to parse SANs in certificate.", e);
    }
    return null;
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

License:Open Source License

/**
 * Returns a JsonValue map representing a CSR
 * //from  w w  w  .  ja va2s .  c o m
 * @param alias  the certificate alias
 * @param csr  The CSR
 * @return a JsonValue map representing the CSR
 * @throws Exception
 */
protected JsonValue returnCertificateRequest(String alias, PKCS10CertificationRequest csr) throws Exception {
    JsonValue content = new JsonValue(new LinkedHashMap<String, Object>());
    content.put(ResourceResponse.FIELD_CONTENT_ID, alias);
    content.put("csr", getCertString(csr));
    content.put("publicKey", getKeyMap(csr.getPublicKey()));
    return content;
}

From source file:org.glite.ce.cream.delegationmanagement.cmdexecutor.DelegationExecutor.java

License:Apache License

private String createAndStoreCertificateRequest(X509Certificate parentCert, String delegationId, String dn,
        String localUser, List<VOMSAttribute> vomsAttributes) throws CommandException {
    logger.debug("BEGIN createAndStoreCertificateRequest");

    ProxyCertificateOptions prOpts = new ProxyCertificateOptions(new X509Certificate[] { parentCert });
    prOpts.setKeyLength(keySize);/*  ww  w.  ja v a  2s.c  o  m*/

    ProxyCSR pCSRContainer = null;
    String privateKey = null;
    PublicKey publicKey = null;
    String certificateRequest = null;
    try {

        pCSRContainer = ProxyCSRGenerator.generate(prOpts);
        PKCS10CertificationRequest pRequest = pCSRContainer.getCSR();
        publicKey = pRequest.getPublicKey();

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        CertificateUtils.savePrivateKey(outStream, pCSRContainer.getPrivateKey(), CertificateUtils.Encoding.PEM,
                null, null);
        outStream.close();
        privateKey = outStream.toString();

        StringWriter strWriter = new StringWriter();
        PEMWriter pemWriter = new PEMWriter(strWriter);
        pemWriter.writeObject(pRequest);
        pemWriter.close();
        certificateRequest = strWriter.toString();

        logger.debug("Public key is: " + publicKey.toString());
        logger.debug("Private key is: " + privateKey);
        logger.debug("Certificate request is: " + certificateRequest);

    } catch (Exception ex) {
        throw new CommandException("Error while generating the certificate request [delegId=" + delegationId
                + "; dn=" + dn + "; localUser=" + localUser + "]: " + ex.getMessage());
    }

    String reqId = null;
    try {
        reqId = delegationId + '+' + this.generateSessionID(publicKey);
        logger.debug("DelegationRequestId (delegationId + sessionId): " + reqId);
    } catch (GeneralSecurityException e) {
        throw new CommandException("Error while generating the sessionId [delegId=" + delegationId + "; dn="
                + dn + "; localUser=" + localUser + "]: " + e.getMessage());
    }

    ArrayList<String> vomsAttributeList = new ArrayList<String>(0);

    for (VOMSAttribute vomsAttr : vomsAttributes) {
        vomsAttributeList.addAll(vomsAttr.getFQANs());
    }

    DelegationRequest delegationRequest = null;
    try {
        boolean found = true;
        // Search for an existing entry in storage for this delegation ID
        delegationRequest = DelegationManager.getInstance().getDelegationRequest(reqId, dn, localUser);

        if (delegationRequest == null) {
            delegationRequest = new DelegationRequest(reqId);
            found = false;
        }

        delegationRequest.setDN(dn);
        delegationRequest.setVOMSAttributes(vomsAttributeList);
        delegationRequest.setCertificateRequest(certificateRequest);
        delegationRequest.setPublicKey(publicKey.toString());
        delegationRequest.setPrivateKey(privateKey);
        delegationRequest.setLocalUser(localUser);

        if (found) {
            DelegationManager.getInstance().update(delegationRequest);
        } else {
            DelegationManager.getInstance().insert(delegationRequest);
        }
    } catch (Exception e) {
        throw new CommandException("Failure on storage interaction [delegId=" + delegationId + "; dn=" + dn
                + "; localUser=" + localUser + "]: " + e.getMessage());
    }

    logger.debug("END createAndStoreCertificateRequest");
    return certificateRequest;
}

From source file:org.glite.ce.cream.delegationmanagement.cmdexecutor.DelegationExecutor.java

License:Apache License

private void putDelegation(Command command) throws CommandException {

    String delegationId = getParameterValueAsString(command, DelegationCommand.DELEGATION_ID);
    String deleg = getParameterValueAsString(command, DelegationCommand.DELEGATION);
    String userDN = getParameterValueAsString(command, DelegationCommand.USER_DN_RFC2253);
    String localUser = getParameterValueAsString(command, DelegationCommand.LOCAL_USER);
    String localUserGroup = getParameterValueAsString(command, DelegationCommand.LOCAL_USER_GROUP);

    String delegInfoStr = "[delegId=" + delegationId + "; dn=" + userDN + "; localUser=" + localUser + "]";

    logger.debug("BEGIN putDelegation" + delegInfoStr);

    X509Certificate[] certChain = null;
    try {/*from  w  w w.  j av  a2 s  .  c om*/

        BufferedInputStream pemStream = new BufferedInputStream(new ByteArrayInputStream(deleg.getBytes()));
        certChain = CertificateUtils.loadCertificateChain(pemStream, CertificateUtils.Encoding.PEM);

        if (certChain.length == 0) {
            throw new IOException("Chain has size 0");
        } else {
            logger.debug("Given proxy certificate loaded successfully.");
        }

    } catch (IOException ex) {
        throw new CommandException("Failed to load certificate chain " + delegInfoStr + ": " + ex.getMessage());
    }

    ValidationResult vRes = AuthorizationModule.validator.validate(certChain);
    if (!vRes.isValid()) {

        StringBuffer buff = new StringBuffer("Proxy certificate is not valid\n");
        for (ValidationError vErr : vRes.getErrors()) {
            buff.append(vErr.getMessage()).append("\n");
        }

        String tmps = buff.toString();
        throw new CommandException("Validation failed " + delegInfoStr + ": " + tmps);

    }

    ProxyChainInfo pChainInfo = null;
    boolean isRFCproxy = false;

    try {

        pChainInfo = new ProxyChainInfo(certChain);

        isRFCproxy = pChainInfo.getProxyType().equals(ProxyChainType.RFC3820);

    } catch (CertificateException ex) {
        throw new CommandException("Proxy parsing error " + delegInfoStr + ": " + ex.getMessage());
    }

    String subjectDN = certChain[0].getIssuerX500Principal().getName();
    String issuerDN = certChain[0].getSubjectX500Principal().getName();

    if (logger.isDebugEnabled()) {
        logger.debug("subject DN: " + subjectDN);
        logger.debug("issuer DN: " + issuerDN);
        logger.debug("chain length is: " + certChain.length);
        logger.debug("last cert is:" + certChain[certChain.length - 1]);

        for (int n = 0; n < certChain.length; n++) {
            logger.debug("cert [" + n + "] is from " + certChain[n].getSubjectX500Principal().getName());
        }
    }

    if (subjectDN == null || issuerDN == null) {
        throw new CommandException(
                "Failed to get DN (subject or issuer) out of delegation " + delegInfoStr + ": it came null");
    }

    String clientDN;
    try {
        X509Certificate eeCert = ProxyUtils.getEndUserCertificate(certChain);
        clientDN = eeCert.getSubjectX500Principal().getName();
    } catch (Exception ex) {
        throw new CommandException(
                "No user certificate found in the delegation chain " + delegInfoStr + ": " + ex.getMessage());
    }

    if (clientDN == null) {
        throw new CommandException("Failed to get client DN " + delegInfoStr + ": it came null");
    }

    String authDN = CEUtils.getUserDN_RFC2253();
    if (!clientDN.equals(authDN)) {
        throw new CommandException("Invalid delegation issuer: '" + clientDN + "' " + authDN);
    }

    String reqId = delegationId;
    try {
        reqId = delegationId + '+' + this.generateSessionID(certChain[0].getPublicKey());
        logger.debug("reqId (delegationId + sessionId): " + reqId);
    } catch (GeneralSecurityException e) {
        throw new CommandException("Failed to generate the session ID " + delegInfoStr + ": " + e.getMessage());
    }

    DelegationRequest delegationRequest = null;
    try {
        // Search for an existing entry in storage for this delegation ID
        delegationRequest = DelegationManager.getInstance().getDelegationRequest(reqId, userDN, localUser);
    } catch (Exception e) {
        throw new CommandException("Failure on storage interaction " + delegInfoStr + ": " + e.getMessage());
    }

    // Check if the delegation request existed
    if (delegationRequest == null) {
        throw new CommandException("Delegation request not found! " + delegInfoStr);
    }
    logger.debug("Got delegation request from cache " + delegInfoStr);

    PrivateKey delegPKey = null;
    try {
        ByteArrayInputStream bIn = new ByteArrayInputStream(delegationRequest.getPrivateKey().getBytes());
        delegPKey = CertificateUtils.loadPEMPrivateKey(bIn, null);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        throw new CommandException("Cannot load delegated private key");
    }

    // the public key of the cached certificate request has to
    // match the public key of the proxy certificate, otherwise
    // this is an answer to a different request
    PublicKey publicKey = null;
    PEMReader pemReader = new PEMReader(new StringReader(delegationRequest.getCertificateRequest()));
    try {
        PKCS10CertificationRequest req = (PKCS10CertificationRequest) pemReader.readObject();
        publicKey = req.getPublicKey();
    } catch (IOException e1) {
        throw new CommandException("Could not load the original certificate request from cache " + delegInfoStr
                + ": " + e1.getMessage());
    } catch (Throwable th) {
        throw new CommandException("cannot get the public key " + delegInfoStr + ": " + th.getMessage());
    }

    if (!publicKey.equals(certChain[0].getPublicKey())) {
        logger.error(
                "The delegation and the original request's public key do not match [delegation public key: '"
                        + certChain[0].getPublicKey() + "'; request public key: '" + publicKey + "']");
        throw new CommandException(
                "The delegation and the original request's public key do not match " + delegInfoStr);
    }

    SimpleDateFormat dateFormat = new SimpleDateFormat();
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    FieldPosition fp = new FieldPosition(SimpleDateFormat.YEAR_FIELD);

    StringBuffer buff = new StringBuffer("[ isRFC=\"");
    buff.append(isRFCproxy);
    buff.append("\"; valid from=\"");
    dateFormat.format(certChain[0].getNotBefore(), buff, fp);
    buff.append(" (GMT)\"; valid to=\"");
    dateFormat.format(certChain[0].getNotAfter(), buff, fp);
    buff.append(" (GMT)\"; holder DN=\"").append(clientDN);
    buff.append("\"; holder AC issuer=\"").append(issuerDN);

    HashMap<String, List<String>> proxyVOAttrs = new HashMap<String, List<String>>(0);
    List<String> vomsAttrituteList = new ArrayList<String>(0);

    VOMSResultCollector collector = new VOMSResultCollector();
    VOMSACValidator validator = VOMSValidators.newValidator(AuthorizationModule.vomsStore,
            AuthorizationModule.validator, collector);
    List<VOMSAttribute> vomsList = validator.validate(certChain);

    if (collector.size() > 0) {
        StringBuffer eBuff = new StringBuffer("Cannot validate proxy ");
        eBuff.append(delegationId).append("\n").append(collector.toString());
        throw new CommandException(eBuff.toString());
    }

    for (VOMSAttribute vomsAttr : vomsList) {
        buff.append("\"; VO=\"").append(vomsAttr.getVO());
        buff.append("\"; AC issuer=\"").append(vomsAttr.getIssuer());
        buff.append("\"; VOMS attributes={ ");

        for (String attr : vomsAttr.getFQANs()) {
            buff.append(attr).append(", ");
            vomsAttrituteList.add(attr);
        }

        buff.replace(buff.length() - 2, buff.length() - 1, " }");

        proxyVOAttrs.put(vomsAttr.getVO(), vomsAttr.getFQANs());
    }

    buff.append("]");

    // Save the delegation into the storage (copying the rest from the info
    // taken from the cache)
    Delegation delegation = null;

    try {
        delegation = DelegationManager.getInstance().getDelegation(delegationId, userDN, localUser, false);
    } catch (Exception e) {
        throw new CommandException("Failure on storage interaction " + delegInfoStr + ": " + e.getMessage());
    }

    boolean found = true;

    if (delegation == null) {
        delegation = new Delegation(delegationId);
        found = false;
    }

    if (!proxyVOAttrs.values().isEmpty()) {
        List<String> fqanList = proxyVOAttrs.values().iterator().next();
        if (fqanList != null && fqanList.size() > 0) {
            delegation.setFQAN(fqanList.get(0).toString());
        }
    }

    if (!proxyVOAttrs.keySet().isEmpty()) {
        delegation.setVO(proxyVOAttrs.keySet().iterator().next());
    }

    if (!vomsAttrituteList.isEmpty()) {
        delegation.setVOMSAttributes(vomsAttrituteList);
    }

    delegation.setRFC(isRFCproxy);
    delegation.setDN(userDN);
    delegation.setCertificate(insertKeyIntoChain(delegationRequest.getPrivateKey(), deleg));
    delegation.setStartTime(certChain[0].getNotBefore());
    delegation.setExpirationTime(certChain[0].getNotAfter());
    delegation.setLastUpdateTime(Calendar.getInstance().getTime());
    delegation.setLocalUser(localUser);
    delegation.setLocalUserGroup(localUserGroup);
    delegation.setInfo(buff.toString());
    delegation.setFileName(makeDelegationFileName(delegationId));
    delegation.setPath(makeDelegationPath(delegation));

    try {
        storeLimitedDelegationProxy(delegation, pChainInfo, certChain, delegPKey);

        logger.info("New delegation created " + delegation.toString());
    } catch (CommandException e) {
        logger.error(
                "Cannot store the limited delegation locally " + delegation.toString() + ": " + e.getMessage());
        throw e;
    }

    try {
        if (found) {
            DelegationManager.getInstance().update(delegation);
        } else {
            DelegationManager.getInstance().insert(delegation);
        }
    } catch (Throwable t) {
        logger.error(t.getMessage());
        throw new CommandException(
                "Failure on storage interaction " + delegation.toString() + ": " + t.getMessage());
    }

    logger.debug("Delegation finished successfully.");

    // Remove the credential from storage cache
    try {
        DelegationManager.getInstance().delete(delegationRequest);
    } catch (Exception e) {
        logger.warn(
                "Failed to remove credential from storage " + delegation.toString() + ": " + e.getMessage());
    }

    command.getResult().addParameter(DelegationCommand.DELEGATION, delegation);
    logger.debug("END putDelegation" + delegInfoStr);
}

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

License:Apache License

/**
 * Creates a proxy certificate from a certificate request
 * // w  ww  .  j  a v a2 s .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 ww w .  j ava2s  .  c o  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 .j  av  a 2 s .  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;
}