Example usage for org.bouncycastle.jce PKCS10CertificationRequest getEncoded

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

Introduction

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

Prototype

public byte[] getEncoded() 

Source Link

Document

return a DER encoded byte array representing this object

Usage

From source file:gridReq.java

License:Open Source License

/**
 * Generates a encrypted private key and certificate request.
 *///from  w w  w  .j  ava2 s  .c om
static public void genCertificateRequest(String dname, String emailAddressOfCA, String password,
        String privKeyLoc, String certLoc, String certReqLoc) throws Exception {

    String sigAlgName = "MD5WithRSA";
    String keyAlgName = "RSA";

    //CertUtil.init();

    // Generate a new key pair.
    KeyPairGenerator keygen = KeyPairGenerator.getInstance(keyAlgName);
    KeyPair keyPair = keygen.genKeyPair();
    PrivateKey privKey = keyPair.getPrivate();
    PublicKey pubKey = keyPair.getPublic();

    // Generate the certificate request.        
    X509Name name = new X509Name(dname);
    DERConstructedSet derSet = new DERConstructedSet();
    PKCS10CertificationRequest request = new PKCS10CertificationRequest(sigAlgName, name, pubKey, derSet,
            privKey);

    // Save the certificate request to a .pem file.
    byte[] data = request.getEncoded();
    PrintStream ps = new PrintStream(new FileOutputStream(certReqLoc));

    // build / delimited name.        
    String certSubject = "";
    StringTokenizer tokens = new StringTokenizer(dname, ",");
    while (tokens.hasMoreTokens()) {
        certSubject = certSubject + "/" + tokens.nextToken();
    }

    ps.print("\n\n" + "Please mail the following certificate request to " + emailAddressOfCA + "\n" + "\n"
            + "==================================================================\n" + "\n"
            + "Certificate Subject:\n" + "\n" + certSubject + "\n" + "\n"
            + "The above string is known as your user certificate subject, and it \n"
            + "uniquely identifies this user.\n" + "\n"
            + "To install this user certificate, please save this e-mail message\n"
            + "into the following file.\n" + "\n" + "\n" + certLoc + "\n" + "\n" + "\n"
            + "      You need not edit this message in any way. Simply \n"
            + "      save this e-mail message to the file.\n" + "\n" + "\n"
            + "If you have any questions about the certificate contact\n" + "the Certificate Authority at "
            + emailAddressOfCA + "\n" + "\n");
    ps.print(toPEM(data));
    ps.close();

    // Save private key to a .pem file.
    OpenSSLKey key = new BouncyCastleOpenSSLKey(privKey);
    if (password.length() != 0) {
        key.encrypt(password);
    }
    key.writeTo(new File(privKeyLoc).getAbsolutePath());
    // set read only permissions
    //Util.setFilePermissions(privKeyLoc, 600);

    // Create an empty cert file.
    File f = new File(certLoc);
    f.createNewFile();
}

From source file:Applet.utiles.Utiles.java

public static String convertPKCS10ToBase64(PKCS10CertificationRequest pkcs10) {
    byte[] pk = Base64.encode(pkcs10.getEncoded());
    String baseString = "";
    for (int i = 0; i < pk.length; i++) {
        baseString = baseString + (char) pk[i];
    }//from w w  w  .j av a2 s. c o  m
    return baseString;
}

From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationClient.java

License:Open Source License

/**
 * Contacts the Entity Authentication Server to create an authentication for the specified Entity ID
 * @param entityID/* w w  w . j ava 2 s .  c  o m*/
 * @param entityAuthenticationServerID
 * @param entityKeys
 * @return
 * @throws CertificateEncodingException
 * @throws InvalidKeyException
 * @throws IllegalStateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws SignatureException
 * @throws UnrecoverableKeyException
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateParsingException
 */
public EntityAuthentication authenticateEntity(EntityID entityID, EntityID entityAuthenticationServerID,
        KeyPair entityKeys) throws CertificateEncodingException, InvalidKeyException, IllegalStateException,
        NoSuchProviderException, NoSuchAlgorithmException, SignatureException, UnrecoverableKeyException,
        KeyStoreException, IOException, CertificateParsingException {
    EntityAuthentication returnAuthentication = null;
    synchronized (cachedAuthentications) {
        HashMap<EntityID, EntityAuthentication> authentications = cachedAuthentications.get(entityID);
        if (authentications != null) {
            EntityAuthentication checkAuthentication = authentications.get(entityAuthenticationServerID);
            if (checkAuthentication != null) {
                if (checkAuthentication.getAuthorizationExpirationTime().before(new Date())) {
                    returnAuthentication = checkAuthentication;
                } else {
                    // Authentication is expired, remove from the table
                    authentications.remove(entityAuthenticationServerID);
                }
            }
        }
    }
    if (returnAuthentication == null) {
        X500Principal entityName = new X500Principal(kEntityIDCNPrefix + entityID.toString());

        PKCS10CertificationRequest certReq = new PKCS10CertificationRequest(
                EntityAuthenticationServer.kCertificateSignatureAlg, entityName, entityKeys.getPublic(), null,
                entityKeys.getPrivate());
        byte[] encodedCertReq = certReq.getEncoded();
        EntityAuthenticationServer[] authenticateServers = new EntityAuthenticationServer[entityAuthenticationServers
                .size()];
        authenticateServers = entityAuthenticationServers.toArray(authenticateServers);

        for (int curServerNum = 0; curServerNum < authenticateServers.length; curServerNum++) {
            if (authenticateServers[curServerNum].getEntityID().equals(entityAuthenticationServerID)) {
                returnAuthentication = authenticateServers[curServerNum].authenticateServer(entityID,
                        encodedCertReq);
                break;
            }
            ;
        }
        if (returnAuthentication != null) {
            synchronized (cachedAuthentications) {
                HashMap<EntityID, EntityAuthentication> authentications = cachedAuthentications.get(entityID);
                if (authentications == null) {
                    authentications = new HashMap<EntityID, EntityAuthentication>();
                    cachedAuthentications.put(entityID, authentications);
                }
                EntityAuthentication checkAuthentication = authentications.get(entityAuthenticationServerID);
                if (checkAuthentication != null
                        && checkAuthentication.getAuthorizationExpirationTime().before(new Date())) {
                    // Hmmm - someone beat us to it.  Use that authentication
                    returnAuthentication = checkAuthentication;
                } else {
                    authentications.put(entityAuthenticationServerID, returnAuthentication);
                }
            }
        }
    }
    return returnAuthentication;
}

From source file:com.igeekinc.indelible.indeliblefs.security.EntityAuthenticationServerNewRMITest.java

License:Open Source License

private void doTestAuthenticateServer(SocketAddress tcpConnectAddress)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException,
        SignatureException, CertificateEncodingException, UnrecoverableKeyException, KeyStoreException,
        RemoteException, CertificateParsingException, IllegalStateException, AuthenticationFailureException,
        ServerNotRegisteredException {//from   w w  w.  j  a  va  2s  .  c  o  m
    EntityAuthenticationServerFirehoseClient client = new EntityAuthenticationServerFirehoseClient(
            tcpConnectAddress);
    try {
        X500Principal entityName = new X500Principal(
                EntityAuthenticationClient.kEntityIDCNPrefix + id.toString());
        PKCS10CertificationRequest certReq = new PKCS10CertificationRequest(
                EntityAuthenticationServer.kCertificateSignatureAlg, entityName, keyPair.getPublic(), null,
                keyPair.getPrivate());
        byte[] encodedCertReq = certReq.getEncoded();
        EntityAuthentication authentication = client.authenticateServer(id, encodedCertReq);
        assertNotNull(authentication);
    } finally {
        client.close();
    }
}

From source file:com.soffid.iam.addons.federation.service.FederacioServiceImpl.java

@Override
protected String handleGeneratePKCS10(FederationMember federationMember) throws Exception {
    FederationMember fm = federationMember;
    if (fm.getPrivateKey() == null || "".equals(fm.getPrivateKey().trim()) || fm.getPublicKey() == null //$NON-NLS-1$
            || "".equals(fm.getPublicKey().trim())) { //$NON-NLS-1$
        throw new Exception(Messages.getString("FederacioServiceImpl.MakePKCS10Message")); //$NON-NLS-1$
    }/*  w  w  w.jav  a  2 s .  c  o  m*/

    java.security.PrivateKey _privateKey = null;
    java.security.PublicKey _publicKey = null;

    try {
        java.security.Security.addProvider(new BouncyCastleProvider());
    } catch (Throwable th) {

    }
    java.io.StringReader srpr = new java.io.StringReader(fm.getPrivateKey());
    org.bouncycastle.openssl.PEMReader prpr = new org.bouncycastle.openssl.PEMReader(srpr);
    Object prKey = prpr.readObject();
    if (prKey instanceof java.security.KeyPair) {
        java.security.KeyPair kp = ((java.security.KeyPair) prKey);
        _privateKey = kp.getPrivate();
    } else if (prKey instanceof java.security.PrivateKey) {
        _privateKey = (PrivateKey) prKey;
    }

    java.io.StringReader srpu = new java.io.StringReader(fm.getPublicKey());
    org.bouncycastle.openssl.PEMReader prpu = new org.bouncycastle.openssl.PEMReader(srpu);
    Object pubKey = prpu.readObject();
    if (pubKey instanceof java.security.KeyPair) {
        java.security.KeyPair kp = ((java.security.KeyPair) pubKey);
        _publicKey = kp.getPublic();
    } else if (pubKey instanceof java.security.PublicKey) {
        _publicKey = (PublicKey) pubKey;
    }

    org.bouncycastle.jce.PKCS10CertificationRequest pkcs10 = new org.bouncycastle.jce.PKCS10CertificationRequest(
            "SHA1withRSA", //$NON-NLS-1$
            new javax.security.auth.x500.X500Principal(
                    "CN=" + fm.getPublicId() + ",OU=" + fm.getEntityGroup().getName()), //$NON-NLS-1$ //$NON-NLS-2$
            _publicKey, null, _privateKey, "SunRsaSign"); //$NON-NLS-1$
    return new String(es.caib.seycon.util.Base64.encodeBytes(pkcs10.getEncoded()));

}

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

License:Open Source License

/**
 * Retrieves credentials from the MyProxy server.
 *///from  ww  w.j  av a 2 s .c  om
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:me.it_result.ca.bouncycastle.BouncyCAClient.java

License:Open Source License

@Override
public synchronized byte[] generateCSR(CertificateParameters certificateParameters) throws CAException {
    try {/*from w w  w  . ja  v  a 2 s .  co  m*/
        KeyPair keyPair;
        KeyStore keyStore = loadKeystore();
        String subjectDN = certificateParameters.getSubjectDN();
        String alias = Utils.generateAlias(subjectDN);
        boolean containsAlias = keyStore.containsAlias(alias);
        if (!containsAlias)
            keyPair = generateKeyPair();
        else
            keyPair = getKeypair(subjectDN);
        X509Certificate cert = assembleCertificate(keyPair.getPublic(), keyPair.getPublic(), subjectDN,
                subjectDN, new BigInteger("1"), false, selfSignedCertificateValidityDays)
                        .generate(keyPair.getPrivate());
        Profile profile = selectProfile(certificateParameters);
        PKCS10CertificationRequest csr = profile.generateCsr(keyPair, certificateParameters,
                signatureAlgorithm);
        byte[] csrBytes = csr.getEncoded();
        if (!containsAlias) {
            keyStore.setKeyEntry(alias, keyPair.getPrivate(), keystorePassword.toCharArray(),
                    new X509Certificate[] { cert });
            saveKeystore(keyStore);
        }
        return csrBytes;
    } catch (DuplicateSubjectException e) {
        throw new DuplicateSubjectException(e);
    } catch (Exception e) {
        throw new CAException(e);
    } finally {
        certGen.reset();
    }
}

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

License:Open Source License

/**
 * Creates a certificate request from the specified subject name, signing
 * algorithm, and a key pair./*  w w  w  .  ja va 2 s . com*/
 * 
 * @param subjectDN
 *            the subject name of the certificate request.
 * @param sigAlgName
 *            the signing algorithm name.
 * @param keyPair
 *            the key pair of the certificate request
 * @return the certificate request.
 * @exception GeneralSecurityException
 *                if security error occurs.
 */
public byte[] createCertificateRequest(X509Name subjectDN, String sigAlgName, KeyPair keyPair)
        throws GeneralSecurityException {
    DERConstructedSet attrs = null;
    PKCS10CertificationRequest certReq = null;
    certReq = new PKCS10CertificationRequest(sigAlgName, subjectDN, keyPair.getPublic(), attrs,
            keyPair.getPrivate());

    return certReq.getEncoded();
}

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

License:Open Source License

/**
 * @see CA#createRequest(Collection, String, Certificate, int)
 */// w ww .ja  v a  2 s.  c om
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
 *//*  ww  w  . ja v  a 2 s .c om*/
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;
}