Example usage for java.security.cert X509Certificate getSubjectDN

List of usage examples for java.security.cert X509Certificate getSubjectDN

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectDN.

Prototype

public abstract Principal getSubjectDN();

Source Link

Document

Denigrated, replaced by #getSubjectX500Principal() .

Usage

From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java

private X509Certificate findCertIssuerInStore(X509Certificate x509cert, KeyStore kStore)
        throws CertificateException {
    X509Certificate x509issuer = null;

    debug("searching store for issuer: " + x509cert.getIssuerDN());

    // check in our local root CA Store
    Enumeration<String> enumAliases;
    try {//from w  ww  .  j  a  v a 2s. c om
        enumAliases = kStore.aliases();
        X509Certificate x509search = null;
        while (enumAliases.hasMoreElements()) {
            x509search = (X509Certificate) kStore.getCertificate(enumAliases.nextElement());

            if (checkSubjectMatchesIssuer(x509search.getSubjectX500Principal(),
                    x509cert.getIssuerX500Principal())) {
                x509issuer = x509search;
                debug("found issuer for current cert in chain in ROOT CA store: " + x509issuer.getSubjectDN());

                break;
            }
        }
    } catch (KeyStoreException e) {

        String errMsg = mContext.getString(R.string.error_problem_access_local_root_ca_store);
        debug(errMsg);

        throw new CertificateException(errMsg);
    }

    return x509issuer;
}

From source file:org.ejbca.core.protocol.ws.EjbcaWSTest.java

private void testCertificateRequestWithSpecialChars(String requestedSubjectDN, String expectedSubjectDN)
        throws Exception {
    String userName = "wsSpecialChars" + secureRandom.nextLong();
    final UserDataVOWS userData = new UserDataVOWS();
    userData.setUsername(userName);/*from  w w  w.  ja va  2 s .  co  m*/
    userData.setPassword(PASSWORD);
    userData.setClearPwd(true);
    userData.setSubjectDN(requestedSubjectDN);
    userData.setCaName(getAdminCAName());
    userData.setEmail(null);
    userData.setSubjectAltName(null);
    userData.setStatus(UserDataVOWS.STATUS_NEW);
    userData.setTokenType(UserDataVOWS.TOKEN_TYPE_P12);
    userData.setEndEntityProfileName("EMPTY");
    userData.setCertificateProfileName("ENDUSER");

    KeyStore ksenv = ejbcaraws.softTokenRequest(userData, null, "1024", AlgorithmConstants.KEYALGORITHM_RSA);
    java.security.KeyStore keyStore = KeyStoreHelper.getKeyStore(ksenv.getKeystoreData(), "PKCS12", PASSWORD);
    assertNotNull(keyStore);
    Enumeration<String> en = keyStore.aliases();
    String alias = en.nextElement();
    if (!keyStore.isKeyEntry(alias)) {
        alias = en.nextElement();
    }
    X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);

    String resultingSubjectDN = cert.getSubjectDN().toString();
    assertEquals(requestedSubjectDN + " was transformed into " + resultingSubjectDN + " (not the expected "
            + expectedSubjectDN + ")", expectedSubjectDN, resultingSubjectDN);
    try {
        endEntityManagementSession.deleteUser(intAdmin, userName);
    } catch (NotFoundException e) {
        // Ignore
    }
}

From source file:com.idevity.card.read.ShowCHUID.java

/**
 * Method onCreateView./* w  ww  .  j ava  2  s . c  o m*/
 * 
 * @param inflater
 *            LayoutInflater
 * @param container
 *            ViewGroup
 * @param savedInstanceState
 *            Bundle
 * @return View
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Globals g = Globals.getInstance();
    String issuer = new String();
    String subject = new String();
    String validfrom = new String();
    String validto = new String();
    boolean certvalid = true;
    boolean sigvalid = false;
    CMSSignedDataObject chuidSig = null;
    X509Certificate pcs = null;

    View chuidLayout = inflater.inflate(R.layout.activity_show_chuid, container, false);
    // get card data

    byte[] _data = g.getCard();
    CardData80073 carddata = new CardData80073(_data);

    // get chuid
    PIVCardHolderUniqueID chuid = null;
    PIVDataTempl chuidInDataTempl = carddata.getPIVCardHolderUniqueID();
    if (chuidInDataTempl != null) {
        byte[] chuidData = chuidInDataTempl.getData();
        if (chuidData == null) {
            chuidData = chuidInDataTempl.getEncoded();
        }
        chuid = new PIVCardHolderUniqueID(chuidData);
    }
    if (chuid != null) {
        try {
            // get chuid signature object
            chuidSig = new CMSSignedDataObject(chuid.getSignatureBytes(), chuid.getSignatureDataBytes());
            chuidSig.setProviderName("OpenSSLFIPSProvider");
            // validate the signature, don't do PDVAL
            sigvalid = chuidSig.verifySignature(false);
        } catch (SignatureException e) {
            Log.e(TAG, "Error: " + e.getMessage());
        }
        // get x509 cert
        if (chuidSig != null) {
            pcs = chuidSig.getSigner();
        }
        // get values from x509
        if (pcs != null) {
            issuer = pcs.getIssuerDN().getName();
            subject = pcs.getSubjectDN().getName();
            validfrom = pcs.getNotBefore().toString();
            validto = pcs.getNotAfter().toString();
        }

    }

    ImageView sigthumbs = (ImageView) chuidLayout.findViewById(R.id.chuidindicator1);
    TextView sigtext = (TextView) chuidLayout.findViewById(R.id.chuid1);
    if (sigvalid) {
        sigthumbs.setImageResource(R.drawable.cert_good);
    } else {
        sigthumbs.setImageResource(R.drawable.cert_bad);
        sigtext.setTextColor(getResources().getColor(R.color.idredmain));
    }

    /*
     * Note to self. I am not thrilled how Java almost forces you to assume
     * a certificate if valid unless an exception is thrown!
     */
    TextView vfText = (TextView) chuidLayout.findViewById(R.id.chuid4);
    TextView vtText = (TextView) chuidLayout.findViewById(R.id.chuid5);

    try {
        if (pcs != null) {
            pcs.checkValidity();
        }
    } catch (CertificateNotYetValidException e) {
        certvalid = false;
        vfText.setTextColor(getResources().getColor(R.color.idredmain));
        if (debug) {
            Log.d(TAG, "Error: Authentication Certificate Not Vaid Yet!");
        }
    } catch (CertificateExpiredException e) {
        certvalid = false;
        vtText.setTextColor(getResources().getColor(R.color.idredmain));
        if (debug) {
            Log.d(TAG, "Error: Card Authentication Certificate Expired!");
        }
    }
    ImageView certthumbs = (ImageView) chuidLayout.findViewById(R.id.chuidindicator2);
    TextView certtext = (TextView) chuidLayout.findViewById(R.id.chuid2);
    if (certvalid && pcs != null) {
        certthumbs.setImageResource(R.drawable.cert_good);
    } else {
        certthumbs.setImageResource(R.drawable.cert_bad);
        certtext.setTextColor(getResources().getColor(R.color.idredmain));
    }

    // setting all values in activity
    TextView editChuidSubject = (TextView) chuidLayout.findViewById(R.id.chuid_subject);
    editChuidSubject.setText(subject);

    TextView editValidFrom = (TextView) chuidLayout.findViewById(R.id.chuid_date);
    editValidFrom.setText(validfrom);

    TextView editValidTo = (TextView) chuidLayout.findViewById(R.id.chuid_expiry);
    editValidTo.setText(validto);

    TextView editIssuer = (TextView) chuidLayout.findViewById(R.id.chuid_issuer);
    editIssuer.setText(issuer);

    return chuidLayout;
}

From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean running_state = CMS.isInRunningState();

    if (!running_state)
        throw new IOException("CMS server is not ready to serve.");

    HttpServletRequest req = request;/*from  w  ww. j  a  v  a  2 s  .  co m*/
    HttpServletResponse resp = response;

    CMSRequest cmsRequest = newCMSRequest();

    // set argblock
    cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request)));

    // set http request
    cmsRequest.setHttpReq(request);

    // set http response
    cmsRequest.setHttpResp(response);

    // set servlet config.
    cmsRequest.setServletConfig(mConfig);

    // set servlet context.
    cmsRequest.setServletContext(mConfig.getServletContext());

    char[] content = null;
    String encodedreq = null;
    String method = null;
    int len = -1;
    IPKIMessage msg = null;
    IPKIMessage replymsg = null;

    // NOTE must read all bufer before redoing handshake for
    // ssl client auth for client auth to work.

    // get request method
    method = req.getMethod();

    // get content length
    len = request.getContentLength();

    // get content, a base 64 encoded serialized request.
    if (len > 0) {
        InputStream in = request.getInputStream();
        InputStreamReader inreader = new InputStreamReader(in, "UTF8");
        BufferedReader reader = new BufferedReader(inreader, len);

        content = new char[len];
        int done = reader.read(content, 0, len);
        int total = done;

        while (done >= 0 && total < len) {
            done = reader.read(content, total, len - total);
            total += done;
        }
        reader.close();
        encodedreq = new String(content);
    }

    // force client auth handshake, validate RA and get RA's Id.
    // NOTE must do this after all contents are read for ssl
    // redohandshake to work

    X509Certificate peerCert;

    try {
        peerCert = getPeerCert(req);
    } catch (EBaseException e) {
        mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    if (peerCert == null) {
        // XXX log something here.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // authenticate RA

    String RA_Id = null;
    String raUserId = null;
    IAuthToken token = null;

    try {
        token = authenticate(request);
        raUserId = token.getInString("userid");
        RA_Id = peerCert.getSubjectDN().toString();
    } catch (EInvalidCredentials e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } catch (EBaseException e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN());

    // authorize
    AuthzToken authzToken = null;

    try {
        authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit");
    } catch (Exception e) {
        // do nothing for now
    }

    if (authzToken == null) {
        cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED);
        return;
    }

    // after cert validated, check http request.
    if (!method.equalsIgnoreCase("POST")) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    if (len <= 0) {
        resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED);
        return;
    }

    // now process request.

    CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id);
    try {
        // decode request.
        msg = (IPKIMessage) mReqEncoder.decode(encodedreq);
        // process request
        replymsg = processRequest(RA_Id, raUserId, msg, token);
    } catch (IOException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (EBaseException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
    }

    CMS.debug("ConnectorServlet: done processRequest");

    // encode reply
    try {
        String encodedrep = mReqEncoder.encode(replymsg);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("text/html");
        resp.setContentLength(encodedrep.length());

        // send reply
        OutputStream out = response.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8");

        writer.write(encodedrep);
        writer.flush();
        writer.close();
        out.flush();
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: error writing e=" + e.toString());
    }
    CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id);
}

From source file:org.globus.gsi.trustmanager.TrustedCertPathFinder.java

/**
 * Method that validates the provided cert path to find a trusted certificate in the certificate store.
 * <p/>/*from w  ww  . j  av a  2 s.c om*/
 * For each certificate i in certPath, it is expected that the i+1 certificate is the issuer of the certificate
 * path. See CertPath.
 * <p/>
 * For each certificate i in certpath, validate signature of certificate i get issuer of certificate i get
 * certificate i+i ensure that the certificate i+1 is issuer of certificate i If not, throw an exception for
 * illegal argument validate signature of i+1 Throw exception if it does not validate check if i+1 is a trusted
 * certificate in the trust store. If so return certpath until i+1 If not, continue; If all certificates in the
 * certpath have been checked and none exisits in trust store, check if trust store has certificate of issuer of
 * last certificate in CertPath. If so, return certPath + trusted certificate from trust store If not, throw
 * an exception for lack of valid trust root.
 *
 * @param keyStore The key store containing CA trust root certificates
 * @param certPath The certpath from which to extract a valid cert path to a trusted certificate.
 * @return The valid CertPath.
 * @throws CertPathValidatorException If the CertPath is invalid.
 */
public static CertPath findTrustedCertPath(KeyStore keyStore, CertPath certPath)
        throws CertPathValidatorException {

    // This will be the cert path to return
    List<X509Certificate> trustedCertPath = new ArrayList<X509Certificate>();
    // This is the certs to validate
    List<? extends Certificate> certs = certPath.getCertificates();

    X509Certificate x509Certificate;
    int index = 0;
    int certsSize = certs.size();

    Certificate certificate = certs.get(index);
    if (!(certificate instanceof X509Certificate)) {
        throw new CertPathValidatorException(
                "Certificate of type " + X509Certificate.class.getName() + " required");
    }
    x509Certificate = (X509Certificate) certificate;

    while (index < certsSize) {
        CertPath finalCertPath = isTrustedCert(keyStore, x509Certificate, trustedCertPath);
        if (finalCertPath != null) {
            return finalCertPath;
        }

        if (index + 1 >= certsSize) {
            break;
        }

        index++;
        Certificate issuerCertificate = certs.get(index);
        x509Certificate = checkCertificate(trustedCertPath, x509Certificate, issuerCertificate);
    }

    X509CertSelector selector = new X509CertSelector();
    selector.setSubject(x509Certificate.getIssuerX500Principal());
    Collection<? extends Certificate> caCerts;
    try {
        caCerts = KeyStoreUtil.getTrustedCertificates(keyStore, selector);
    } catch (KeyStoreException e) {
        throw new CertPathValidatorException(e);
    }
    if (caCerts.size() < 1) {
        throw new CertPathValidatorException("No trusted path can be constructed");
    }

    boolean foundTrustRoot = false;

    for (Certificate caCert : caCerts) {
        if (!(caCert instanceof X509Certificate)) {
            logger.warn("Skipped a certificate: not an X509Certificate");
            continue;
        }
        try {
            trustedCertPath.add(checkCertificate(trustedCertPath, x509Certificate, caCert));
            // currently the caCert self-signature is not checked
            // to be consistent with the isTrustedCert() method
            foundTrustRoot = true;
            // we found a CA cert that signed the certificate
            // so we don't need to check any more
            break;
        } catch (CertPathValidatorException e) {
            // fine, just move on to check the next potential CA cert
            // after the loop we'll check whether any were successful
            logger.warn("Failed to validate signature of certificate with " + "subject DN '"
                    + x509Certificate.getSubjectDN() + "' against a CA certificate with issuer DN '"
                    + ((X509Certificate) caCert).getSubjectDN() + "'");
        }
    }

    if (!foundTrustRoot) {
        throw new CertPathValidatorException("No trusted path can be constructed");
    }

    try {
        CertificateFactory certFac = CertificateFactory.getInstance("X.509");
        return certFac.generateCertPath(trustedCertPath);
    } catch (CertificateException e) {
        throw new CertPathValidatorException("Error generating trusted certificate path", e);
    }
}

From source file:eu.eidas.auth.engine.SamlEngine.java

/**
 * Gets the country from X.509 Certificate.
 *
 * @param keyInfo the key info/* w w  w  .j  av  a2  s .com*/
 * @return the country
 */
private String getCountry(KeyInfo keyInfo) {
    LOG.trace("Recover country information.");
    try {
        org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0).getX509Certificates()
                .get(0);

        // Transform the KeyInfo to X509Certificate.
        X509Certificate cert = CertificateUtil.toCertificate(xmlCert.getValue());

        String distName = cert.getSubjectDN().toString();

        distName = StringUtils.deleteWhitespace(StringUtils.upperCase(distName));

        String countryCode = "C=";
        int init = distName.indexOf(countryCode);

        String result = "";
        if (init > StringUtils.INDEX_NOT_FOUND) {
            // Exist country code.
            int end = distName.indexOf(',', init);

            if (end <= StringUtils.INDEX_NOT_FOUND) {
                end = distName.length();
            }

            if (init < end && end > StringUtils.INDEX_NOT_FOUND) {
                result = distName.substring(init + countryCode.length(), end);
                //It must be a two characters value
                if (result.length() > 2) {
                    result = result.substring(0, 2);
                }
            }
        }
        return result.trim();
    } catch (EIDASSAMLEngineException e) {
        LOG.error(SAML_EXCHANGE, "BUSINESS EXCEPTION : Procces getCountry from certificate: " + e.getMessage(),
                e);
        throw new EIDASSAMLEngineRuntimeException(e);
    }
}

From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeMultipleKeyIdRequestTest.java

@Test
public void test06CrmfTcpOkUserKeyId3() throws Exception {

    byte[] nonce = CmpMessageHelper.createSenderNonce();
    byte[] transid = CmpMessageHelper.createSenderNonce();

    PKIMessage one = genCertReq(this.issuerDN2, userDN2, this.keys, this.cacert2, nonce, transid, true, null,
            null, null, null, null, null);
    PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "KeyId3", 567);

    CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
    int reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
    assertNotNull(req);//from  www  .  j  av a  2s  .c o m
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    DEROutputStream out = new DEROutputStream(bao);
    out.writeObject(req);
    byte[] ba = bao.toByteArray();
    // Send request and receive response
    byte[] resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    X509Certificate cert = checkCmpCertRepMessage(userDN2, this.cacert2, resp, reqId);
    // FileOutputStream fos = new FileOutputStream("/home/tomas/foo.crt");
    // fos.write(cert.getEncoded());
    // fos.close();
    String altNames = CertTools.getSubjectAlternativeName(cert);
    assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1);
    assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1);

    // Check key usage that it is digitalSignature, keyEncipherment and
    // nonRepudiation for KeyId3
    // Because keyUsage for keyId3 should be taken from the request (see
    // genCertReq)
    boolean[] ku = cert.getKeyUsage();
    assertTrue(ku[0]);
    assertTrue(ku[1]);
    assertTrue(ku[2]);
    assertFalse(ku[3]);
    assertFalse(ku[4]);
    assertFalse(ku[5]);
    assertFalse(ku[6]);
    assertFalse(ku[7]);
    assertFalse(ku[8]);
    // Check DN that must be SE for KeyId1 and NO for KeyId2
    assertEquals("NO", CertTools.getPartFromDN(cert.getSubjectDN().getName(), "C"));

    // Send a confirm message to the CA
    String hash = "foo123";
    PKIMessage confirm = genCertConfirm(userDN2, this.cacert2, nonce, transid, hash, reqId);
    assertNotNull(confirm);
    PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567);
    bao = new ByteArrayOutputStream();
    out = new DEROutputStream(bao);
    out.writeObject(req1);
    ba = bao.toByteArray();
    // Send request and receive response
    resp = sendCmpTcp(ba, 5);
    checkCmpResponseGeneral(resp, this.issuerDN2, userDN2, this.cacert2, nonce, transid, false, PBEPASSWORD,
            PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
    checkCmpPKIConfirmMessage(userDN2, this.cacert2, resp);
}

From source file:xtremweb.dispatcher.HTTPHandler.java

/**
 * This retrieves the user from its X509 certificate
 *
 * @throws IOException/*from   w  w w  . ja v  a2 s.c  o  m*/
 * @throws NoSuchAlgorithmException 
 */
private UserInterface userFromCertificate(final HttpServletRequest request)
        throws IOException, NoSuchAlgorithmException {

    final Object certChain = request.getAttribute("javax.servlet.request.X509Certificate");

    if (certChain == null) {
        return null;
    }

    final Logger logger = getLogger();

    final UserInterface client = new UserInterface();

    final X509Certificate certs[] = (X509Certificate[]) certChain;
    int i = 0;
    for (final X509Certificate cert : certs) {
        final String dn = cert.getSubjectDN().getName();
        logger.debug("SubjectDN[" + i++ + "] = " + dn);
        try {
            final String dnu = dn.toUpperCase();
            final int idx = dnu.indexOf(DNHEADER_EMAIL);
            if (idx != -1) {
                final int startemail = idx + DNHEADERLENGTH_EMAIL;
                int endemail = dnu.indexOf(',', startemail);
                if (endemail == -1) {
                    endemail = dnu.length() - startemail;
                }
                final String email = dn.substring(startemail, endemail);
                logger.debug("email = " + email);
                if (email != null) {
                    client.setEMail(email);
                }
            }
        } catch (final Exception e) {
        }
    }
    final String subjectName = certs[0].getSubjectX500Principal().getName();
    final String issuerName = certs[0].getIssuerX500Principal().getName();
    final String loginName = subjectName + "_" + issuerName;
    final String random = loginName + Math.random() + System.currentTimeMillis();
    final String shastr = XWTools.sha256(random);
    client.setLogin(loginName); // login may be truncated; see
    // UserIntergace.USERLOGINLENGTH

    final UserInterface ret = DBInterface.getInstance()
            .user(UserInterface.Columns.LOGIN.toString() + "= '" + client.getLogin() + "'");

    if (ret != null) {
        ret.setEMail(client.getEMail());
        logger.debug(("user = " + ret) == null ? "null" : ret.toXml());
        return ret;
    }

    final UserInterface admin = Dispatcher.getConfig().getProperty(XWPropertyDefs.ADMINLOGIN) == null ? null
            : DBInterface.getInstance()
                    .user(SQLRequest.MAINTABLEALIAS + "." + UserInterface.Columns.LOGIN.toString() + "='"
                            + Dispatcher.getConfig().getProperty(XWPropertyDefs.ADMINLOGIN) + "'");
    if (admin == null) {
        throw new IOException("can't insert new certified user");
    }

    client.setUID(new UID());
    client.setLogin(loginName);
    client.setPassword(shastr);
    if (client.getEMail() == null) {
        client.setEMail(loginName);
    }
    client.setOwner(Dispatcher.getConfig().getAdminUid());
    client.setRights(UserRightEnum.STANDARD_USER);

    try {
        DBInterface.getInstance().addUser(admin, client);
        return client;
    } catch (final Exception e) {
        throw new IOException("user certification error : " + e.getMessage());
    }
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

void install(String[] redirectEndpointUrls, String[] postLogoutRedirectUrls, String logoutUrl)
        throws Exception {
    String domainControllerFQDN = this.relyingPartyConfig.getOpFQDN();
    int domainControllerPort = Integer.parseInt(this.relyingPartyConfig.getOpListeningPort());
    String tenant = this.relyingPartyConfig.getTenant();

    // retrieve OIDC meta data
    MetadataHelper metadataHelper = new MetadataHelper.Builder(domainControllerFQDN)
            .domainControllerPort(domainControllerPort).tenant(tenant).keyStore(this.keyStore).build();

    ProviderMetadata providerMetadata = metadataHelper.getProviderMetadata();
    RSAPublicKey providerPublicKey = metadataHelper.getProviderRSAPublicKey(providerMetadata);

    // create a non-registered OIDC client and get bearer tokens by admin user name/password
    ConnectionConfig connectionConfig = new ConnectionConfig(providerMetadata, providerPublicKey,
            this.keyStore);
    ClientConfig clientConfig = new ClientConfig(connectionConfig, null, null);
    OIDCClient nonRegisteredClient = new OIDCClient(clientConfig);
    TokenSpec tokenSpec = new TokenSpec.Builder(TokenType.BEARER)
            .resourceServers(Arrays.asList("rs_admin_server")).build();
    OIDCTokens oidcTokens = nonRegisteredClient.acquireTokensByPassword(
            this.relyingPartyConfig.getAdminUsername(), this.relyingPartyConfig.getAdminPassword(), tokenSpec);

    // create a private/public key pair, generate a certificate and assign it to a solution user name.
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
    keyGen.initialize(1024, new SecureRandom());
    KeyPair keypair = keyGen.generateKeyPair();
    String solutionUserName = this.relyingPartyConfig.getClientPrefix() + UUID.randomUUID().toString();
    X509Certificate clientCertificate = generateCertificate(keypair, solutionUserName);

    // create REST idm client
    IdmClient idmClient = createIdmClient(oidcTokens.getAccessToken(), domainControllerFQDN,
            domainControllerPort);//  w w w  . j  a  v a  2 s.c o m

    VmdirClient vmdirClient = createVMdirClient(oidcTokens.getAccessToken(), domainControllerFQDN,
            domainControllerPort);

    // create a solution user
    CertificateDTO certificateDTO = new CertificateDTO.Builder()
            .withEncoded(convertToBase64PEMString(clientCertificate)).build();
    SolutionUserDTO solutionUserDTO = new SolutionUserDTO.Builder().withName(solutionUserName)
            .withDomain(tenant).withCertificate(certificateDTO).build();
    vmdirClient.solutionUser().create(tenant, solutionUserDTO);

    // add the solution user to ActAs group
    List<String> members = Arrays.asList(solutionUserName + "@" + tenant);
    vmdirClient.group().addMembers(tenant, "ActAsUsers", tenant, members,
            com.vmware.directory.rest.common.data.MemberType.USER);

    // register a OIDC client
    OIDCClientMetadataDTO oidcClientMetadataDTO = new OIDCClientMetadataDTO.Builder()
            .withRedirectUris(Arrays.asList(redirectEndpointUrls))
            .withPostLogoutRedirectUris(Arrays.asList(postLogoutRedirectUrls)).withLogoutUri(logoutUrl)
            .withTokenEndpointAuthMethod("private_key_jwt")
            .withCertSubjectDN(clientCertificate.getSubjectDN().getName())
            .withAuthnRequestClientAssertionLifetimeMS(2 * 60 * 1000L).build();
    OIDCClientDTO oidcClientDTO = idmClient.oidcClient().register(tenant, oidcClientMetadataDTO);

    // persist data involved installation in files so they can be picked up in case server reboots
    savePublicKey(this.relyingPartyConfig.getOpPublickeyFile(), providerPublicKey);
    savePrivateKey(this.relyingPartyConfig.getRpPrivatekeyFile(), keypair.getPrivate());
    writeObject(this.relyingPartyConfig.getRpCertificateFile(), clientCertificate);
    writeObject(this.relyingPartyConfig.getRpInfoFile(), oidcClientDTO.getClientId());
    writeObject(this.relyingPartyConfig.getRpListeningPortFile(), this.relyingPartyConfig.getRpListeningPort());
}

From source file:org.globus.workspace.client.modes.DeployRun.java

private void delegate() throws Exception {

    final GlobusCredential credential = GlobusCredential.getDefaultCredential();

    final ClientSecurityDescriptor csd = WSUtils.getClientSecDesc(this.d.delegationSecMechanism,
            this.d.delegationProtection, this.d.delegationAuthorization);

    final EndpointReferenceType delegEpr = AddressingUtils.createEndpointReference(this.d.delegationFactoryUrl,
            null);//w w  w . j  av a  2s  . c o  m

    final X509Certificate[] certsToDelegateOn = DelegationUtil.getCertificateChainRP(delegEpr, csd);

    final X509Certificate certToSign = certsToDelegateOn[0];

    if (this.pr.enabled()) {
        final String msg = "Delegating for staging credential(s).";
        if (this.pr.useThis()) {
            this.pr.infoln(PrCodes.DELEGATE__ALLMESSAGES, msg);
        } else if (this.pr.useLogging()) {
            logger.info(msg);
        }
    }

    if (this.pr.enabled()) {
        final StringBuffer buf = new StringBuffer(512);

        buf.append("\nAbout to call delegation.\n  - Client credential: ").append(credential.getIdentity())
                .append("\n  - Factory URL: ").append(this.d.delegationFactoryUrl)
                .append("\n  - Security mechanism: ").append(this.d.delegationSecMechanism)
                .append("\n  - Protection mechanism: ").append(this.d.delegationProtection)
                .append("\n  - Authorization: ").append(this.d.delegationAuthorization.getClass().getName())
                .append("\n  - Cert to sign: ").append(certToSign.getSubjectDN().getName());

        final String dbg = buf.toString();
        if (this.pr.useThis()) {
            this.pr.dbg(dbg);
        } else if (this.pr.useLogging()) {
            logger.debug(dbg);
        }
    }

    final Delegate delegate = new Delegate(credential, csd, this.d.delegationFactoryUrl, certToSign,
            this.d.delegationLifetime, true);

    delegate.validateAll();

    if (this.d.dryrun) {
        if (this.pr.enabled()) {
            final String msg = "Dryrun, not calling delegation service.";
            if (this.pr.useThis()) {
                // part of PRCODE_CREATE__DRYRUN as a whole
                this.pr.infoln(PrCodes.CREATE__DRYRUN, msg);
            } else if (this.pr.useLogging()) {
                logger.info(msg);
            }
        }

        return; // *** EARLY RETURN ***
    }

    final EndpointReferenceType epr = delegate.delegate();

    //this.delegationWasPerformed = true;

    final OptionalParameters_Type opt = this.d.optionalParameters;
    if (opt == null) {
        throw new ParameterProblem("(?) optional parameters is missing, but delegation " + "was performed?");
    }

    if (opt.getStageIn() != null && opt.getStageIn().getStagingCredential() == null) {

        opt.getStageIn().setStagingCredential(epr);

        if (this.d.delegationXferCredToo) {
            opt.getStageIn().setTransferCredential(epr);
        }
    }

    if (opt.getStageOut() != null && opt.getStageOut().getStagingCredential() == null) {

        opt.getStageOut().setStagingCredential(epr);

        if (this.d.delegationXferCredToo) {
            opt.getStageOut().setTransferCredential(epr);
        }
    }

    // TODO: fish out delegation resource key for printing
    //if (this.pr.enabled()) {
    //    final String uri = EPRUtils.getServiceURIAsString(epr);
    //    final String key = ________;
    //    final String msg =
    //            "Delegation performed, EPR: '" + key + "' @ '" + uri + "'";
    //    if (this.pr.useThis()) {
    //        this.pr.infoln(PrCodes.PRCODE_DELEGATE__ALLMESSAGES,
    //                       msg);
    //    } else if (this.pr.useLogging()) {
    //        logger.info(msg);
    //    }
    //}

    if (this.pr.enabled()) {

        final StringBuffer buf = new StringBuffer("\nDelegated. New " + "optional parameters:\n");

        // serialized version, for severe problems
        //StringWriter writer = null;
        //try {
        //    writer = new StringWriter();
        //    final QName qName = new QName("", "optionalParameters");
        //    writer.write(ObjectSerializer.toString(opt, qName));
        //    buf.append(writer.toString());
        //    buf.append("\n\n");
        //} finally {
        //    if (writer != null) {
        //        writer.close();
        //    }
        //}

        buf.append(StringUtils.debugDumpOptional(opt));

        final String dbg = buf.toString();
        if (this.pr.useThis()) {
            this.pr.dbg(dbg);
        } else if (this.pr.useLogging()) {
            logger.debug(dbg);
        }
    }
}