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(String signatureAlgorithm, X509Name subject, PublicKey key,
        ASN1Set attributes, PrivateKey signingKey, String provider)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException 

Source Link

Document

create a PKCS10 certfication request using the named provider.

Usage

From source file:ca.nrc.cadc.cred.server.actions.DelegationAction.java

License:Open Source License

X509CertificateChain prepareCert(X509CertificateChain signCert) throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException, CertificateParsingException,
        CertificateEncodingException, CertificateExpiredException, CertificateNotYetValidException {
    log.debug("prepareCert - START");
    if (!(signCert.getPrivateKey() instanceof RSAKey)) {
        // TODO - Only RSA keys are supported. Generate a proxy cert
        // if this is not the case
        // This should probably be cached somehow
        if (daysValid == Float.MAX_VALUE) {
            daysValid = 30.0f;/*  w w  w.  java 2 s.  c om*/
        }
    }

    if (daysValid == Float.MAX_VALUE) {
        // return the stored certificate as it is
        log.debug("daysValid = " + daysValid + ", returning bare certificate");
        return signCert;
    } else {
        // return proxy certificate signed with the key of the
        // stored certificate

        try {

            // Add the Bouncy Castle JCE provider. This allows the CSR
            // classes to work. The BC implementation of PKCS#10 depends
            // on the ciphers in the BC provider.
            if (Security.getProvider("BC") == null) {
                Security.addProvider(new BouncyCastleProvider());
            }

            KeyPairGenerator keyPairGenerator = null;
            try {
                keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            } catch (NoSuchAlgorithmException ex) {
                ex.printStackTrace();
                throw new RuntimeException("The JCE doesn't do RSA! Game over.");
            }
            keyPairGenerator.initialize(CertUtil.DEFAULT_KEY_LENGTH);

            // generate the subject
            String subject = signCert.getChain()[0].getSubjectX500Principal().getName(X500Principal.CANONICAL);

            // generated the key pair
            KeyPair keys = keyPairGenerator.generateKeyPair();

            // generate the CSR
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                    CertUtil.DEFAULT_SIGNATURE_ALGORITHM, new X509Name(subject), keys.getPublic(), null,
                    keys.getPrivate(), "BC");
            log.debug("PKCS10CertificationRequest " + csr.getSignatureAlgorithm().toString());

            // sign the CSR
            X509Certificate newCert = CertUtil.generateCertificate(csr, Math.round(daysValid * 24 * 60 * 60),
                    signCert);

            // package and return
            X509Certificate[] certChain = new X509Certificate[signCert.getChain().length + 1];
            certChain[0] = newCert;
            System.arraycopy(signCert.getChain(), 0, certChain, 1, signCert.getChain().length);
            X509CertificateChain result = new X509CertificateChain(certChain, keys.getPrivate());
            result.setPrincipal(signCert.getPrincipal());

            return result;
        } finally {
            profiler.checkpoint("prepareCert");
        }
    }
}

From source file:es.unican.meteo.esgf.myproxyclient.MyProxyLogon.java

License:Open Source License

/**
 * Retrieves credentials from the MyProxy server.
 *//*from  w ww  .ja v  a  2s .c  o m*/
public void getCredentials() throws IOException, GeneralSecurityException {
    if (this.state != State.LOGGEDON) {
        logon();
    }
    KeyPairGenerator localKeyPairGenerator = KeyPairGenerator.getInstance("RSA");
    localKeyPairGenerator.initialize(1024);
    this.keypair = localKeyPairGenerator.genKeyPair();
    PKCS10CertificationRequest localPKCS10CertificationRequest = new PKCS10CertificationRequest("SHA1withRSA",
            new X500Principal("CN=ignore"), this.keypair.getPublic(), null, this.keypair.getPrivate(),
            "SunRsaSign");
    this.socketOut.write(localPKCS10CertificationRequest.getEncoded());
    this.socketOut.flush();
    int i = this.socketIn.read();
    if (i == -1) {
        System.err.println("connection aborted");
        System.exit(1);
    } else if ((i == 0) || (i < 0)) {
        System.err.print("bad number of certificates sent by server: ");
        System.err.println(Integer.toString(i));
        System.exit(1);
    }
    CertificateFactory localCertificateFactory = CertificateFactory.getInstance("X.509");
    this.certificateChain = localCertificateFactory.generateCertificates(this.socketIn);
    this.state = State.DONE;
}

From source file:eu.optimis.ics.Credentials.Credentials.java

License:Open Source License

public PKCS10CertificationRequest genCertificationRequest(KeyPair keyPair, String CN) {
    PKCS10CertificationRequest CSRequest = null;
    X500Principal name = new X500Principal("CN=" + CN + ", OU=ATOS, O=ATOS, L=Barcelona, C=ES");
    /*/*from  ww w .  java  2s.c o m*/
    // challenge password attribute
            
    ASN1EncodableVector challpwd = new ASN1EncodableVector();
    challpwd.add(new DERObjectIdentifier(PKCSObjectIdentifiers.pkcs_9_at_challengePassword.getId()));
            
    ASN1EncodableVector pwdValue = new ASN1EncodableVector();
    pwdValue.add(new DERUTF8String("pakistan"));
            
    challpwd.add(new DERSet(pwdValue));
            
    ASN1EncodableVector vector = new ASN1EncodableVector();
      vector.add(new DERSequence(challpwd));
             
      DERSet attributes = new DERSet(vector);
      */
    DERSet attributes = null;
    try {
        CSRequest = new PKCS10CertificationRequest("SHA1withRSA", name, keyPair.getPublic(), attributes,
                keyPair.getPrivate(), "BC");
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    }
    return CSRequest;
}

From source file:hu.akarnokd.utils.crypto.KeystoreManager.java

License:Apache License

/**
 * Create a certificate signing request.
 * The created text can be sent to a Certificate Authority to request
 * a countersigning./*from   w ww .  java2s  . c om*/
 * @param cert the local X509Certificate object
 * @param privKey the private key of the certificate
 * @return the request string
 */
public String createRSASigningRequest(X509Certificate cert, PrivateKey privKey) {
    X509Name xname = new X509Name(cert.getSubjectDN().getName());
    try {
        PKCS10CertificationRequest certReq = new PKCS10CertificationRequest("MD5withRSA", xname,
                cert.getPublicKey(), null, privKey, BC_PROVIDER.getName());

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DEROutputStream dout = new DEROutputStream(bout);
        try {
            dout.writeObject(certReq.toASN1Primitive());
        } finally {
            dout.close();
        }

        String s = Base64.encodeBytes(bout.toByteArray());
        StringBuilder result = new StringBuilder(s.length() + 100);
        result.append("-----BEGIN NEW CERTIFICATE REQUEST-----\n");
        // split base64 string into 76 character lines
        int lineLen = 76;
        int len = s.length();
        int idx = 0;
        while (len > 0) {
            if (len > lineLen) {
                result.append(s.substring(idx, idx + lineLen)).append('\n');
                len -= lineLen;
                idx += lineLen;
            } else {
                result.append(s.substring(idx)).append('\n');
                break;
            }
        }
        result.append("-----END NEW CERTIFICATE REQUEST-----\n");
        return result.toString();
    } catch (Exception ex) {
        throw new KeystoreFault(ex);
    }
}

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

License:Open Source License

/**
 * @see CA#createRequest(Collection, String, Certificate, int)
 *//*from w  w w.j a  v a 2  s.c  o m*/
public byte[] createRequest(Collection<DEREncodable> attributes, String signAlg, Certificate cacert,
        int signatureKeyPurpose) throws CATokenOfflineException {
    log.trace(
            ">createRequest: " + signAlg + ", " + CertTools.getSubjectDN(cacert) + ", " + signatureKeyPurpose);
    ASN1Set attrset = new DERSet();
    if (attributes != null) {
        log.debug("Adding attributes in the request");
        Iterator<DEREncodable> iter = attributes.iterator();
        ASN1EncodableVector vec = new ASN1EncodableVector();
        while (iter.hasNext()) {
            DEREncodable o = (DEREncodable) iter.next();
            vec.add(o);
            attrset = new DERSet(vec);
        }
    }
    X509NameEntryConverter converter = null;
    if (getUsePrintableStringSubjectDN()) {
        converter = new PrintableStringEntryConverter();
    } else {
        converter = new X509DefaultEntryConverter();
    }
    X509Name x509dn = CertTools.stringToBcX509Name(getSubjectDN(), converter, getUseLdapDNOrder());
    PKCS10CertificationRequest req;
    try {
        CATokenContainer catoken = getCAToken();
        KeyPair keyPair = new KeyPair(catoken.getPublicKey(signatureKeyPurpose),
                catoken.getPrivateKey(signatureKeyPurpose));
        if (keyPair == null) {
            throw new IllegalArgumentException(
                    "Keys for key purpose " + signatureKeyPurpose + " does not exist.");
        }
        req = new PKCS10CertificationRequest(signAlg, x509dn, keyPair.getPublic(), attrset,
                keyPair.getPrivate(), catoken.getProvider());
        log.trace("<createRequest");
        return req.getEncoded();
    } catch (CATokenOfflineException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.ejbca.core.protocol.ocsp.standalonesession.KeyRenewer.java

License:Open Source License

/**
 * Fetch a new certificate from EJBCA and stores the key with the certificate chain.
 * @param ejbcaWS from {@link #getEjbcaWS()}
 * @param userData from {@link #getUserDataVOWS(EjbcaWS, String)}
 * @param keyPair from {@link #generateKeyPair()}
 * @return the certificate chain of the stored key
 *//*from ww  w .j  a  v  a 2s  .  co  m*/
private X509Certificate[] storeKey(EjbcaWS ejbcaWS, UserDataVOWS userData, KeyPair keyPair) {
    X509Certificate tmpCert = null;
    final Iterator<X509Certificate> i;
    try {
        final PKCS10CertificationRequest pkcs10 = new PKCS10CertificationRequest("SHA1WithRSA",
                CertTools.stringToBcX509Name("CN=NOUSED"), keyPair.getPublic(), new DERSet(),
                keyPair.getPrivate(), this.privateKeyContainerKeyStore.providerName);
        final CertificateResponse certificateResponse = ejbcaWS.pkcs10Request(userData.getUsername(),
                userData.getPassword(), new String(Base64.encode(pkcs10.getEncoded())), null,
                CertificateHelper.RESPONSETYPE_CERTIFICATE);
        i = (Iterator<X509Certificate>) CertificateFactory.getInstance("X.509")
                .generateCertificates(new ByteArrayInputStream(Base64.decode(certificateResponse.getData())))
                .iterator();
    } catch (Exception e) {
        m_log.error("Certificate generation problem.", e);
        return null;
    }
    while (i.hasNext()) {
        tmpCert = i.next();
        try {
            tmpCert.verify(this.caChain.get(0).getPublicKey());
        } catch (Exception e) {
            tmpCert = null;
            continue;
        }
        if (keyPair.getPublic().equals(tmpCert.getPublicKey())) {
            break;
        }
        tmpCert = null;
    }
    if (tmpCert == null) {
        m_log.error("No certificate signed by correct CA generated.");
        return null;
    }
    final List<X509Certificate> lCertChain = new ArrayList<X509Certificate>(this.caChain);
    lCertChain.add(0, tmpCert);
    final X509Certificate certChain[] = lCertChain.toArray(new X509Certificate[0]);
    if (this.privateKeyContainerKeyStore.fileName != null
            && this.privateKeyContainerKeyStore.sessionData.mKeyPassword == null) {
        m_log.error("Key password must be configured when updating SW keystore.");
        return null;
    }
    try {
        this.privateKeyContainerKeyStore.keyStore.setKeyEntry(this.privateKeyContainerKeyStore.alias,
                keyPair.getPrivate(),
                this.privateKeyContainerKeyStore.sessionData.mKeyPassword != null
                        ? this.privateKeyContainerKeyStore.sessionData.mKeyPassword.toCharArray()
                        : null,
                certChain);
    } catch (Throwable e) {
        m_log.error("Problem to store new key in HSM.", e);
        return null;
    }
    if (this.privateKeyContainerKeyStore.fileName != null) {
        try {
            this.privateKeyContainerKeyStore.keyStore.store(
                    new FileOutputStream(this.privateKeyContainerKeyStore.fileName),
                    this.privateKeyContainerKeyStore.sessionData.mStorePassword.toCharArray());
        } catch (Throwable e) {
            m_log.error("Not possible to store keystore on file.", e);
        }
    }
    return certChain;
}

From source file:org.qipki.crypto.x509.X509GeneratorImpl.java

License:Open Source License

@Override
public PKCS10CertificationRequest generatePKCS10(DistinguishedName distinguishedName, KeyPair keyPair) {
    try {//from  w ww .  j  ava  2  s  .c  om
        return new PKCS10CertificationRequest(SignatureAlgorithm.SHA256withRSA.jcaString(),
                distinguishedName.toX500Principal(), keyPair.getPublic(), null, keyPair.getPrivate(),
                cryptoContext.providerName());
    } catch (GeneralSecurityException ex) {
        throw new CryptoFailure("Unable to generate PKCS#10", ex);
    }
}

From source file:org.qipki.crypto.x509.X509GeneratorImpl.java

License:Open Source License

@Override
public PKCS10CertificationRequest generatePKCS10(DistinguishedName distinguishedName, KeyPair keyPair,
        GeneralNames subjectAlternativeNames) {
    try {/* w  w w .  j a v a  2 s  . co  m*/
        return new PKCS10CertificationRequest(SignatureAlgorithm.SHA256withRSA.jcaString(),
                distinguishedName.toX500Principal(), keyPair.getPublic(),
                generateSANAttribute(subjectAlternativeNames), keyPair.getPrivate(),
                cryptoContext.providerName());
    } catch (GeneralSecurityException ex) {
        throw new CryptoFailure("Unable to generate PKCS#10", ex);
    }
}

From source file:org.teragrid.portal.filebrowser.applet.util.proxy.MyProxyLogon.java

License:Open Source License

/**
 * Retrieves credentials from the MyProxy server.
 *//*from  ww  w  .  j  a v  a2 s. c o m*/
public void getCredentials() throws IOException, GeneralSecurityException {
    int numCertificates;
    KeyPairGenerator keyGenerator;
    PKCS10CertificationRequest pkcs10;
    CertificateFactory certFactory;

    if (this.state != State.LOGGEDON) {
        this.logon();
    }

    keyGenerator = KeyPairGenerator.getInstance(keyAlg);
    keyGenerator.initialize(keySize);
    this.keypair = keyGenerator.genKeyPair();

    pkcs10 = new PKCS10CertificationRequest(pkcs10SigAlgName, new X509Name(DN), this.keypair.getPublic(), null,
            this.keypair.getPrivate(), pkcs10Provider);

    this.socketOut.write(pkcs10.getEncoded());
    this.socketOut.flush();
    numCertificates = this.socketIn.read();
    if (numCertificates == -1) {
        System.err.println("connection aborted");
        System.exit(1);
    } else if (numCertificates == 0 || numCertificates < 0) {
        System.err.print("bad number of certificates sent by server: ");
        System.err.println(Integer.toString(numCertificates));
        System.exit(1);
    }
    certFactory = CertificateFactory.getInstance("X.509");
    this.certificateChain = certFactory.generateCertificates(this.socketIn);
    this.state = State.DONE;
}

From source file:org.votingsystem.signature.util.CertificationRequestVS.java

License:Open Source License

public static CertificationRequestVS getVoteRequest(int keySize, String keyName, String signatureMechanism,
        String provider, String accessControlURL, String eventId, String getHashCertVSBase64)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException,
        IOException {//w ww  .  ja  v a  2s .  com
    KeyPair keyPair = KeyGeneratorVS.INSTANCE.genKeyPair();
    X500Principal subject = new X500Principal(
            "CN=accessControlURL:" + accessControlURL + ", OU=eventId:" + eventId);
    ASN1EncodableVector asn1EncodableVector = new ASN1EncodableVector();
    Map delegationDataMap = new HashMap<String, String>();
    delegationDataMap.put("accessControlURL", accessControlURL);
    delegationDataMap.put("hashCertVS", getHashCertVSBase64);
    delegationDataMap.put("eventId", eventId);
    String delegationDataStr = JSON.getMapper().writeValueAsString(delegationDataMap);
    asn1EncodableVector.add(new DERTaggedObject(ContextVS.VOTE_TAG, new DERUTF8String(delegationDataStr)));
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureMechanism, subject,
            keyPair.getPublic(), new DERSet(asn1EncodableVector), keyPair.getPrivate(), provider);
    return new CertificationRequestVS(keyPair, csr, signatureMechanism);
}