Example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getSubject

List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest getSubject

Introduction

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

Prototype

public X500Name getSubject() 

Source Link

Document

Return the subject on this request.

Usage

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void odfSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    signGenericDocument(workerId, readFile(odfSampleFile));
}

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void ooxmlSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    signGenericDocument(workerId, readFile(ooxmlSampleFile));
}

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void msauthTSSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .addExtension(org.bouncycastle.asn1.x509.X509Extension.extendedKeyUsage, true,
                            new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping))
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    GenericSignRequest signRequest = new GenericSignRequest(678, MSAUTHCODE_REQUEST_DATA.getBytes());
    final GenericSignResponse res = (GenericSignResponse) workerSession.process(workerId, signRequest,
            new RequestContext());
    Certificate signercert = res.getSignerCertificate();
    assertNotNull(signercert);/*from   w  w w . java  2s.c o m*/

    byte[] buf = res.getProcessedData();
    CMSSignedData s = new CMSSignedData(Base64.decode(buf));

    int verified = 0;
    Store certStore = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder signerCert = (X509CertificateHolder) certIt.next();

        if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(signerCert))) {
            verified++;
        }
    }

    assertEquals("signer verified", 1, verified);
}

From source file:org.signserver.server.dispatchers.FirstActiveDispatcherTest.java

License:Open Source License

private void addCertificate(PrivateKey issuerPrivateKey, int workerId, String workerName)
        throws CryptoTokenOfflineException, InvalidWorkerIdException, IOException, CertificateException,
        OperatorCreationException {//from  w  w  w .ja  v  a  2 s .c  o m
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) workerSession.getCertificateRequest(workerId,
            new PKCS10CertReqInfo("SHA1withRSA", "CN=" + workerName, null), false);
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo()).build(
                    new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC").build(issuerPrivateKey));
    workerSession.setWorkerProperty(workerId, "SIGNERCERTCHAIN", new String(
            CertTools.getPEMFromCerts(Arrays.asList(new JcaX509CertificateConverter().getCertificate(cert)))));
    workerSession.reloadConfiguration(workerId);
}

From source file:org.signserver.server.log.SystemLoggingTest.java

License:Open Source License

/**
 * Tests that importing a certificate chain to a token is audit logged
 * including the complete chain.//from   w w  w.java2 s .com
 * @throws Exception 
 */
@Test
public void test01LogCertChainInstalledToToken() throws Exception {
    LOG.info(">test01LogCertChainInstalledToToken");

    final String tokenName = "TestCryptoTokenP12_001";
    final String alias = "testkeyalias10";

    try {
        setupCryptoToken(WORKERID_CRYPTOWORKER1, tokenName, "foo123");
        workerSession.generateSignerKey(WORKERID_CRYPTOWORKER1, "RSA", "512", alias, null);

        PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=testkeyalias10,C=SE", null);
        ICertReqData req = workerSession.getCertificateRequest(WORKERID_CRYPTOWORKER1, certReqInfo, false);
        Base64SignerCertReqData reqData = (Base64SignerCertReqData) req;
        PKCS10CertificationRequest csr = new PKCS10CertificationRequest(
                Base64.decode(reqData.getBase64CertReq()));

        int linesBefore = readEntriesCount(auditLogFile);

        // Test with uploadSignerCertificateChain method (global scope)
        KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
        final X509Certificate issuerCert = new JcaX509CertificateConverter().getCertificate(
                new CertBuilder().setSelfSignKeyPair(issuerKeyPair).setSubject("CN=Issuer, C=SE").build());
        final X509Certificate cert = new JcaX509CertificateConverter()
                .getCertificate(new X509v3CertificateBuilder(new X500Name("CN=Issuer, C=SE"), BigInteger.ONE,
                        new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)),
                        csr.getSubject(), csr.getSubjectPublicKeyInfo())
                                .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                                        .build(issuerKeyPair.getPrivate())));

        workerSession.importCertificateChain(WORKERID_CRYPTOWORKER1,
                Arrays.asList(cert.getEncoded(), issuerCert.getEncoded()), alias, null);

        List<String> lines = readEntries(auditLogFile, linesBefore, 2);
        LOG.info(lines);

        String line = getTheLineContaining(lines, "EVENT: CERTCHAININSTALLED");
        assertNotNull("Contains event", line);
        assertTrue("Contains module", line.contains("MODULE: KEY_MANAGEMENT"));
        assertTrue("Contains worker id", line.contains("WORKER_ID: " + WORKERID_CRYPTOWORKER1));
        assertTrue("Contains crypto token", line.contains("CRYPTOTOKEN: " + tokenName));
        assertTrue("Contains key alias", line.contains("KEYALIAS: " + alias));
        assertTrue("Contains certificate",
                line.contains(new String(org.cesecore.util.CertTools
                        .getPemFromCertificateChain(Arrays.<Certificate>asList(cert, issuerCert)))
                                .replace("\r\n", "\n")));
    } finally {
        removeWorker(WORKERID_CRYPTOWORKER1);
        if (keystoreFile != null) {
            FileUtils.deleteQuietly(keystoreFile);
        }
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

License:Open Source License

    public X509Certificate generateCertificateFromCSR(PrivateKey privateKey,
                                                      PKCS10CertificationRequest request,
                                                      String issueSubject)
            throws KeystoreException {

        CommonUtil commonUtil = new CommonUtil();
        Date validityBeginDate = commonUtil.getValidityStartDate();
        Date validityEndDate = commonUtil.getValidityEndDate();

        X500Name certSubject = new X500Name(CertificateManagementConstants.DEFAULT_PRINCIPAL);
        //X500Name certSubject = request.getSubject();

        Attribute attributes[] = request.getAttributes();

//        if (certSubject == null) {
//            certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
//        } else {
//            org.bouncycastle.asn1.x500.RDN[] rdn = certSubject.getRDNs();
///*from ww  w .  j a v a2  s.  c  o m*/
//            if (rdn == null || rdn.length == 0) {
//                certSubject = new X500Name(ConfigurationUtil.DEFAULT_PRINCIPAL);
//            }
//        }


        RDN[] certUniqueIdRDN;
        BigInteger certUniqueIdentifier;

        // IMPORTANT: "Serial-Number" of the certificate used when creating it, is set as its "Alias" to save to
        // keystore.
        if (request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER).length != 0) {
            // if certificate attribute "UNIQUE_IDENTIFIER" exists use its hash as the "Serial-Number" for the
            // certificate.
            certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.UNIQUE_IDENTIFIER);
            certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode());

        } else if (request.getSubject().getRDNs(BCStyle.SERIALNUMBER).length != 0) {
            // else if certificate attribute "SERIAL_NUMBER" exists use its hash as the "Serial-Number" for the
            // certificate.
            certUniqueIdRDN = request.getSubject().getRDNs(BCStyle.SERIALNUMBER);
            certUniqueIdentifier = BigInteger.valueOf(certUniqueIdRDN[0].getFirst().getValue().toString().hashCode());

        } else {
            // else get the BigInteger Value of the integer that is the current system-time in millis as the
            // "Serial-Number".
            certUniqueIdentifier = CommonUtil.generateSerialNumber();
        }

        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
                new X500Name(issueSubject), certUniqueIdentifier, validityBeginDate, validityEndDate, certSubject,
                request.getSubjectPublicKeyInfo());

        ContentSigner sigGen;
        X509Certificate issuedCert;

        try {
            certificateBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(
                    KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

            if (attributes != null) {
                ASN1Encodable extractedValue = getChallengePassword(attributes);

                if (extractedValue != null) {
                    certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, true,
                                                    extractedValue);
                }
            }

            sigGen = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA)
                    .setProvider(CertificateManagementConstants.PROVIDER).build(privateKey);
            issuedCert = new JcaX509CertificateConverter().setProvider(
                    CertificateManagementConstants.PROVIDER).getCertificate(
                    certificateBuilder.build(sigGen));
            org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate =
                    new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
            List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
            certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
            certificate.setCertificate(issuedCert);
            certificates.add(certificate);
            saveCertInKeyStore(certificates);
        } catch (CertIOException e) {
            String errorMsg = "Certificate Input output issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        } catch (OperatorCreationException e) {
            String errorMsg = "Operator creation issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        } catch (CertificateException e) {
            String errorMsg = "Certificate issue occurred when generating generateCertificateFromCSR";
            throw new KeystoreException(errorMsg, e);
        }

        return issuedCert;
    }

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java

License:Open Source License

/**
 * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key
 * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed
 * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the
 * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its
 * PublicKey for future payload encryption.
 *
 * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if
 *                                     there is an error creating a self-sign certificate to present to the
 *                                     server (whilst trying to get the CSR signed)
 *///w  ww. jav  a2 s.co m
public void beginEnrollmentFlow() throws AgentCoreOperationException {
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    this.privateKey = keyPair.getPrivate();
    this.publicKey = keyPair.getPublic();

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n");
    }

    PKCS10CertificationRequest certSignRequest = generateCertSignRequest();

    /**
     *  -----------------------------------------------------------------------------------------------
     *  Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request.
     *  In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this.
     *  -----------------------------------------------------------------------------------------------
     */
    X500Name issuer = new X500Name("CN=Temporary Issuer");
    BigInteger serial = new BigInteger(32, new SecureRandom());
    Date fromDate = new Date();
    Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L));

    // Build the self-signed cert using BC, sign it with our private key (self-signed)
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate,
            certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo());
    ContentSigner sigGen;
    X509Certificate tmpCert;

    try {
        sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate());
        tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER)
                .getCertificate(certBuilder.build(sigGen));
    } catch (OperatorCreationException e) {
        String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }
    /**
     *  -----------------------------------------------------------------------------------------------
     */

    this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest);
    this.serverPublicKey = initPublicKeyOfServer();

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey()
                + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n");
    }

}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

License:Open Source License

/**
 * Method to control the entire enrollment flow. This method calls the method to create the Private-Public Key
 * Pair, calls the specific method to generate the Certificate-Sign-Request, creates a one time self signed
 * certificate to present to the SCEP server with the initial CSR, calls the specific method to connect to the
 * SCEP Server and to get the SCEP Certificate and also calls the method that requests the SCEP Server for its
 * PublicKey for future payload encryption.
 *
 * @throws AgentCoreOperationException if the private method generateCertSignRequest() fails with an error or if
 *                                     there is an error creating a self-sign certificate to present to the
 *                                     server (whilst trying to get the CSR signed)
 *///w  ww .j a  v a2  s .c  om
public void beginEnrollmentFlow() throws AgentCoreOperationException {
    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    this.privateKey = keyPair.getPrivate();
    this.publicKey = keyPair.getPublic();

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER + "DevicePrivateKey:\n[\n" + privateKey + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "DevicePublicKey:\n[\n" + publicKey + "\n]\n");
    }

    PKCS10CertificationRequest certSignRequest = generateCertSignRequest();

    /**
     *  -----------------------------------------------------------------------------------------------
     *  Generate an ephemeral self-signed certificate. This is needed to present to the CA in the SCEP request.
     *  In the future, add proper EKU and attributes in the request. The CA does NOT have to honour any of this.
     *  -----------------------------------------------------------------------------------------------
     */
    X500Name issuer = new X500Name("CN=Temporary Issuer");
    BigInteger serial = new BigInteger(32, new SecureRandom());
    Date fromDate = new Date();
    Date toDate = new Date(System.currentTimeMillis() + (CERT_VALIDITY * 86400000L));

    // Build the self-signed cert using BC, sign it with our private key (self-signed)
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, fromDate, toDate,
            certSignRequest.getSubject(), certSignRequest.getSubjectPublicKeyInfo());
    ContentSigner sigGen;
    X509Certificate tmpCert;

    try {
        sigGen = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER).build(keyPair.getPrivate());
        tmpCert = new JcaX509CertificateConverter().setProvider(PROVIDER)
                .getCertificate(certBuilder.build(sigGen));
    } catch (OperatorCreationException e) {
        String errorMsg = "Error occurred whilst creating a ContentSigner for the Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred whilst trying to create Temp-Self-Signed Certificate.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }
    /**
     *  -----------------------------------------------------------------------------------------------
     */

    this.SCEPCertificate = getSignedCertificateFromServer(tmpCert, certSignRequest);
    this.serverPublicKey = initPublicKeyOfServer();

    storeCertificateToStore(AgentConstants.DEVICE_CERT_ALIAS, SCEPCertificate);
    storeKeyToKeyStore(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS, this.privateKey, SCEPCertificate);

    if (log.isDebugEnabled()) {
        log.info(AgentConstants.LOG_APPENDER
                + "SCEPCertificate, DevicePrivateKey, ServerPublicKey was saved to device keystore ["
                + AgentConstants.DEVICE_KEYSTORE + "]");
        log.info(AgentConstants.LOG_APPENDER + "TemporaryCertPublicKey:\n[\n" + tmpCert.getPublicKey()
                + "\n]\n");
        log.info(AgentConstants.LOG_APPENDER + "ServerPublicKey:\n[\n" + serverPublicKey + "\n]\n");
    }
}

From source file:org.wso2.carbon.identity.certificateauthority.dao.CsrDAO.java

License:Open Source License

private String addCsr(PKCS10CertificationRequest request, String userName, int tenantID, String userStoreDomain,
        String transactionId) throws CaException {
    String csrSerialNo = new BigInteger(32, new SecureRandom()).toString();
    Connection connection = null;
    Date requestDate = new Date();
    String sql = null;//from  w  w  w  .  j  a  v a  2s.c om
    PreparedStatement prepStmt = null;
    RDN[] orgRdNs = request.getSubject().getRDNs(BCStyle.O);
    String organization = "";
    if (orgRdNs.length > 0) {
        organization = orgRdNs[0].getFirst().getValue().toString();
    }
    RDN[] cnRdNs = request.getSubject().getRDNs(BCStyle.CN);
    String commonName = "";
    if (cnRdNs.length > 0) {
        commonName = cnRdNs[0].getFirst().getValue().toString();
    }
    try {
        log.debug("adding csr file to database");
        connection = JDBCPersistenceManager.getInstance().getDBConnection();
        sql = "INSERT INTO CA_CSR_STORE (CSR_CONTENT, STATUS, USER_NAME, REQUESTED_DATE, SERIAL_NO, TENANT_ID,COMMON_NAME,ORGANIZATION,UM_DOMAIN_NAME,TRANSACTION_ID) VALUES (?,?,?,?,?,?,?,?,?,?) ";
        prepStmt = connection.prepareStatement(sql);
        prepStmt.setBlob(1, new ByteArrayInputStream(request.getEncoded()));
        prepStmt.setString(2, CsrStatus.PENDING.toString());
        prepStmt.setString(3, userName);
        prepStmt.setTimestamp(4, new Timestamp(requestDate.getTime()));
        prepStmt.setString(5, csrSerialNo);
        prepStmt.setInt(6, tenantID);
        prepStmt.setString(7, commonName);
        prepStmt.setString(8, organization);
        prepStmt.setString(9, userStoreDomain);
        prepStmt.setString(10, transactionId);
        prepStmt.execute();
        connection.commit();
    } catch (IdentityException e) {
        String errorMsg = "Error when getting an Identity Persistence Store instance.";
        log.error(errorMsg, e);
        throw new CaException(errorMsg, e);
    } catch (SQLException e) {
        log.error("Error when executing the SQL : " + sql, e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt);
    }
    return csrSerialNo;
}

From source file:org.wso2.carbon.identity.certificateauthority.utils.CsrUtils.java

License:Open Source License

public static HashMap<String, String> getSubjectInfo(PKCS10CertificationRequest csr) {
    String name = csr.getSubject().toString();
    HashMap<String, String> map = new HashMap<String, String>();
    if (name.split("C").length > 1) {
        String country = name.split("C=")[1].split(",")[0];
        map.put("C", country);
    }/*from  ww w  .  java2s  .c o  m*/
    if (name.split("CN").length > 1) {
        String commonName = name.split("CN=")[1].split(",")[0];
        map.put("CN", commonName);
    }
    if (name.split("O").length > 1) {
        String organization = name.split("O=")[1].split(",")[0];
        map.put("O", organization);
    }
    if (name.split("L").length > 1) {
        String l = name.split("L=")[1].split(",")[0];
        map.put("L", l);
    }
    if (name.split("OU").length > 1) {
        String ou = name.split("OU=")[1].split(",")[0];
        map.put("OU", ou);
    }
    if (name.split("ST").length > 1) {
        String st = name.split("ST=")[1].split(",")[0];
        map.put("ST", st);
    }
    return map;
}