Example usage for javax.security.auth.callback PasswordCallback setPassword

List of usage examples for javax.security.auth.callback PasswordCallback setPassword

Introduction

In this page you can find the example usage for javax.security.auth.callback PasswordCallback setPassword.

Prototype

public void setPassword(char[] password) 

Source Link

Document

Set the retrieved password.

Usage

From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java

private Builder loadKeyStore(final CertificateConfigEntry entry) throws KeyStoreException {
    final File f = new File(entry.getKeyStore());
    final KeyStoreType kt = entry.getKeyStoreType();
    if ("PKCS11".equals(kt.getName())) {
        String config = "name=" + f.getName() + "\nlibrary=" + f.getAbsoluteFile();
        try {/*from   ww  w .  j a v  a  2s.  c  o  m*/
            Class<?> pkcs11c = Class.forName("sun.security.pkcs11.SunPKCS11");
            Constructor<?> c = pkcs11c.getConstructor(InputStream.class);
            Provider p = (Provider) c.newInstance(new ByteArrayInputStream(config.getBytes()));
            Security.insertProviderAt(p, 0);
        } catch (Exception e) {
            logger.error(
                    "Tried to access the PKCS11 provider on an " + "unsupported platform or the load failed",
                    e);
        }
    }
    KeyStore.Builder ksBuilder = KeyStore.Builder.newInstance(kt.getName(), null, f,
            new KeyStore.CallbackHandlerProtection(new CallbackHandler() {
                public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                    for (Callback cb : callbacks) {
                        if (!(cb instanceof PasswordCallback))
                            throw new UnsupportedCallbackException(cb);

                        PasswordCallback pwcb = (PasswordCallback) cb;
                        if (entry.isSavePassword()) {
                            pwcb.setPassword(entry.getKeyStorePassword().toCharArray());
                            return;
                        } else {
                            AuthenticationWindowService authenticationWindowService = CertificateVerificationActivator
                                    .getAuthenticationWindowService();

                            if (authenticationWindowService == null) {
                                logger.error("No AuthenticationWindowService " + "implementation");
                                throw new IOException("User cancel");
                            }

                            AuthenticationWindowService.AuthenticationWindow aw = authenticationWindowService
                                    .create(f.getName(), null, kt.getName(), false, false, null, null, null,
                                            null, null, null, null);

                            aw.setAllowSavePassword(false);
                            aw.setVisible(true);
                            if (!aw.isCanceled())
                                pwcb.setPassword(aw.getPassword());
                            else
                                throw new IOException("User cancel");
                        }
                    }
                }
            }));
    return ksBuilder;
}

From source file:it.cnr.icar.eric.client.xml.registry.jaas.ThinClientCallbackHandler.java

/** Implementation of the handle method specified by
 * <code> javax.security.auth.callback.CallbackHandler </code>
 * @param callbacks <code>Array of 
 * javax.security.auth.callback.CallbackHandler</code>
 *
 *//*from   w  w w  . j  a va 2 s .com*/
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {

    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof TextOutputCallback) {
            // Ignore this section for now. This will be used when a generic callback handler
            // is being implemented. In our current implementation, we are only expecting the
            //login type callback handler.
        } else if (callbacks[i] instanceof NameCallback) {
            // For now hard-code the alias of the the RegistryOperator account
            NameCallback nc = (NameCallback) callbacks[i];
            String alias = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.alias");
            if (alias == null) {
                String message = "Error: the jaxr-ebxml.security.alias " + "property must be set";
                log.error(message);
                System.err.println(message);
                alias = "";
            }
            nc.setName(alias);
        } else if (callbacks[i] instanceof PasswordCallback) {
            // For now hard-code the password of the the RegistryOperator account
            PasswordCallback pc = (PasswordCallback) callbacks[i];
            char[] password = null;
            if (handleStorePass) {
                String storepass = ProviderProperties.getInstance()
                        .getProperty("jaxr-ebxml.security.storepass");
                if (storepass == null) {
                    storepass = "ebxmlrr";
                }
                password = storepass.toCharArray();
                handleStorePass = false;
            } else {
                String keypass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.keypass");
                if (keypass == null) {
                    String message = "Error: the jaxr-ebxml.security.keypass " + "property must be set";
                    log.error(message);
                    System.err.println(message);
                    keypass = "";
                }
                password = keypass.toCharArray();
            }
            pc.setPassword(password);
        } else if (callbacks[i] instanceof ConfirmationCallback) {
            ConfirmationCallback cc = (ConfirmationCallback) callbacks[i];
            cc.setSelectedIndex(ConfirmationCallback.OK);
        } else {
            throw new UnsupportedCallbackException(callbacks[i],
                    JAXRResourceBundle.getInstance().getString("message.error.unrecognized.callback"));
        }
    }
}

From source file:edu.vt.middleware.ldap.jaas.AbstractLoginModule.java

/**
 * This attempts to retrieve credentials for the supplied name and password
 * callbacks. If useFirstPass or tryFirstPass is set, then name and password
 * data is retrieved from shared state. Otherwise a callback handler is used
 * to get the data. Set useCallback to force a callback handler to be used.
 *
 * @param  nameCb  to set name for/*from  w w  w .j av  a 2  s  .co m*/
 * @param  passCb  to set password for
 * @param  useCallback  whether to force a callback handler
 *
 * @throws  LoginException  if the callback handler fails
 */
protected void getCredentials(final NameCallback nameCb, final PasswordCallback passCb,
        final boolean useCallback) throws LoginException {
    if (this.logger.isTraceEnabled()) {
        this.logger.trace("Begin getCredentials");
        this.logger.trace("  useFistPass = " + this.useFirstPass);
        this.logger.trace("  tryFistPass = " + this.tryFirstPass);
        this.logger.trace("  useCallback = " + useCallback);
        this.logger.trace("  callbackhandler class = " + this.callbackHandler.getClass().getName());
        this.logger.trace("  name callback class = " + nameCb.getClass().getName());
        this.logger.trace("  password callback class = " + passCb.getClass().getName());
    }
    try {
        if ((this.useFirstPass || this.tryFirstPass) && !useCallback) {
            nameCb.setName((String) this.sharedState.get(LOGIN_NAME));
            passCb.setPassword((char[]) this.sharedState.get(LOGIN_PASSWORD));
        } else if (this.callbackHandler != null) {
            this.callbackHandler.handle(new Callback[] { nameCb, passCb });
        } else {
            throw new LoginException("No CallbackHandler available. "
                    + "Set useFirstPass, tryFirstPass, or provide a CallbackHandler");
        }
    } catch (IOException e) {
        if (this.logger.isErrorEnabled()) {
            this.logger.error("Error reading data from callback handler", e);
        }
        this.loginSuccess = false;
        throw new LoginException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
        if (this.logger.isErrorEnabled()) {
            this.logger.error("Unsupported callback", e);
        }
        this.loginSuccess = false;
        throw new LoginException(e.getMessage());
    }
}

From source file:it.cnr.icar.eric.client.xml.registry.jaas.DialogAuthenticationCallbackHandler.java

/** Implementation of the handle method specified by
 * <code> javax.security.auth.callback.CallbackHandler </code>
 * @param callbacks <code>Array of javax.security.auth.callback.CallbackHandler</code>
 *
 *//* w ww . ja v a2s .  c  o m*/
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
    int result = showDialog();

    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof TextOutputCallback) {
            // Ignore this section for now. This will be used when a generic callback handler
            // is being implemented. In our current implementation, we are only expecting the
            //login type callback handler.
        } else if (callbacks[i] instanceof NameCallback) {
            // prompt the user for a username
            NameCallback nc = (NameCallback) callbacks[i];
            String strPrompt = nc.getPrompt();
            String strName = "";

            //                if (strPrompt.equals(authResBundle.getString("Keystore alias: "))) {
            if (strPrompt.equals(authResBundle.getString("Keystore.alias."))) {
                strName = txtAlias.getText();
            }

            nc.setName(strName);
        } else if (callbacks[i] instanceof PasswordCallback) {
            // prompt the user for sensitive information
            PasswordCallback pc = (PasswordCallback) callbacks[i];
            String strPrompt = pc.getPrompt();
            char[] chrPass = new char[0];

            //                if (strPrompt.equals(authResBundle.getString("Keystore password: "))) {
            if (strPrompt.equals(authResBundle.getString("Keystore.password."))) {
                /* As of now hide the Keystore password part from the user and
                   read directly from the properties file
                   chrPass = txtStorepass.getPassword() ; */
                chrPass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storepass")
                        .toCharArray();

                if ((chrPass == null) || (chrPass.length == 0)) {
                    log.error("Property jaxr-ebxml.security.storepass is undefined");
                }
                //                } else if (strPrompt.equals(authResBundle.getString("Private key password (optional): "))) {
            } else if (strPrompt.equals(authResBundle.getString("Private.key.password.optional."))) {
                chrPass = txtKeypass.getPassword();
            }

            pc.setPassword(chrPass);
        } else if (callbacks[i] instanceof ConfirmationCallback) {
            ConfirmationCallback cc = (ConfirmationCallback) callbacks[i];

            if (result == OK) {
                cc.setSelectedIndex(ConfirmationCallback.OK);
            } else {
                cc.setSelectedIndex(ConfirmationCallback.CANCEL);
            }
        } else {
            throw new UnsupportedCallbackException(callbacks[i],
                    JAXRResourceBundle.getInstance().getString("message.error.unrecognized.callback"));
        }
    }
}

From source file:org.apache.accumulo.core.rpc.SaslClientDigestCallbackHandler.java

@Override
public void handle(Callback[] callbacks) throws UnsupportedCallbackException {
    NameCallback nc = null;/*from ww  w  . j a v  a2 s.  c o  m*/
    PasswordCallback pc = null;
    RealmCallback rc = null;
    for (Callback callback : callbacks) {
        if (callback instanceof RealmChoiceCallback) {
            continue;
        } else if (callback instanceof NameCallback) {
            nc = (NameCallback) callback;
        } else if (callback instanceof PasswordCallback) {
            pc = (PasswordCallback) callback;
        } else if (callback instanceof RealmCallback) {
            rc = (RealmCallback) callback;
        } else {
            throw new UnsupportedCallbackException(callback, "Unrecognized SASL client callback");
        }
    }
    if (nc != null) {
        log.debug("SASL client callback: setting username: {}", userName);
        nc.setName(userName);
    }
    if (pc != null) {
        log.debug("SASL client callback: setting userPassword");
        pc.setPassword(userPassword);
    }
    if (rc != null) {
        log.debug("SASL client callback: setting realm: {}", rc.getDefaultText());
        rc.setText(rc.getDefaultText());
    }
}

From source file:org.apache.atlas.web.filters.AtlasAuthenticationKerberosFilterTest.java

protected Subject loginTestUser() throws LoginException, IOException {
    LoginContext lc = new LoginContext(TEST_USER_JAAS_SECTION, new CallbackHandler() {

        @Override//from   w  ww .j av  a 2s.  c  o m
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback callback : callbacks) {
                if (callback instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callback;
                    passwordCallback.setPassword(TESTPASS.toCharArray());
                }
                if (callback instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callback;
                    nameCallback.setName(TESTUSER);
                }
            }
        }
    });
    // attempt authentication
    lc.login();
    return lc.getSubject();
}

From source file:org.apache.atlas.web.filters.MetadataAuthenticationKerberosFilterIT.java

protected Subject loginTestUser() throws LoginException, IOException {
    LoginContext lc = new LoginContext(TEST_USER_JAAS_SECTION, new CallbackHandler() {

        @Override/* ww w .j a  v a  2s  . c om*/
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (int i = 0; i < callbacks.length; i++) {
                if (callbacks[i] instanceof PasswordCallback) {
                    PasswordCallback passwordCallback = (PasswordCallback) callbacks[i];
                    passwordCallback.setPassword(TESTPASS.toCharArray());
                }
                if (callbacks[i] instanceof NameCallback) {
                    NameCallback nameCallback = (NameCallback) callbacks[i];
                    nameCallback.setName(TESTUSER);
                }
            }
        }
    });
    // attempt authentication
    lc.login();
    return lc.getSubject();
}

From source file:org.apache.directory.server.ldap.handlers.sasl.AbstractSaslCallbackHandler.java

/**
 * SaslServer will use this method to call various callbacks, depending on the SASL
 * mechanism in use for a session./*from   w w  w .  j  ava2 s  .  c om*/
 * 
 * @param callbacks An array of one or more callbacks.
 */
public void handle(Callback[] callbacks) {
    for (int i = 0; i < callbacks.length; i++) {
        Callback callback = callbacks[i];

        if (LOG.isDebugEnabled()) {
            LOG.debug("Processing callback {} of {}: {}", callback.getClass(), (i + 1), callbacks.length);
        }

        if (callback instanceof NameCallback) {
            NameCallback nameCB = (NameCallback) callback;
            LOG.debug("NameCallback default name:  {}", nameCB.getDefaultName());

            username = nameCB.getDefaultName();
        } else if (callback instanceof RealmCallback) {
            RealmCallback realmCB = (RealmCallback) callback;
            LOG.debug("RealmCallback default text:  {}", realmCB.getDefaultText());

            realm = realmCB.getDefaultText();
        } else if (callback instanceof PasswordCallback) {
            PasswordCallback passwordCB = (PasswordCallback) callback;
            Attribute userPassword = lookupPassword(getUsername(), getRealm());

            if (userPassword != null) {
                // We assume that we have only one password available
                byte[] password = userPassword.get().getBytes();

                String strPassword = Strings.utf8ToString(password);
                passwordCB.setPassword(strPassword.toCharArray());
            }
        } else if (callback instanceof AuthorizeCallback) {
            AuthorizeCallback authorizeCB = (AuthorizeCallback) callback;

            // hnelson (CRAM-MD5, DIGEST-MD5)
            // hnelson@EXAMPLE.COM (GSSAPI)
            LOG.debug("AuthorizeCallback authnID:  {}", authorizeCB.getAuthenticationID());

            // hnelson (CRAM-MD5, DIGEST-MD5)
            // hnelson@EXAMPLE.COM (GSSAPI)
            LOG.debug("AuthorizeCallback authzID:  {}", authorizeCB.getAuthorizationID());

            // null (CRAM-MD5, DIGEST-MD5, GSSAPI)
            LOG.debug("AuthorizeCallback authorizedID:  {}", authorizeCB.getAuthorizedID());

            // false (CRAM-MD5, DIGEST-MD5, GSSAPI)
            LOG.debug("AuthorizeCallback isAuthorized:  {}", authorizeCB.isAuthorized());

            try {
                authorize(authorizeCB);
            } catch (Exception e) {
                // TODO - figure out how to handle this properly.
                throw new RuntimeException(I18n.err(I18n.ERR_677), e);
            }
        }
    }
}

From source file:org.apache.hadoop.io.crypto.bee.key.sasl.KeySaslClient.java

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof NameCallback) {
            // logger.debug("set name");
            NameCallback ncb = (NameCallback) callbacks[i];
            ncb.setName(keyToken.getUser());
        } else if (callbacks[i] instanceof PasswordCallback) {
            // logger.debug("set password");
            PasswordCallback pcb = (PasswordCallback) callbacks[i];
            pcb.setPassword(new String(keyToken.getPassword()).toCharArray());
            // logger.debug("set password:" +
            // Hex.encodeHexString(keyToken.getPassword()));
        } else if (callbacks[i] instanceof RealmCallback) {
            // logger.debug("set realm");
            RealmCallback rcb = (RealmCallback) callbacks[i];
            rcb.setText(SaslUtil.KEY_REALM);
        } else {//from   w  ww. ja  v a 2  s  . c  o m
            throw new UnsupportedCallbackException(callbacks[i]);
        }
    }
}

From source file:org.apache.ws.security.NamePasswordCallbackHandler.java

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        Callback callback = callbacks[i];
        if (handleCallback(callback)) {
            continue;
        } else if (callback instanceof NameCallback) {
            ((NameCallback) callback).setName(username);
        } else if (callback instanceof PasswordCallback) {
            PasswordCallback pwCallback = (PasswordCallback) callback;
            pwCallback.setPassword(password.toCharArray());
        } else if (!invokePasswordCallback(callback)) {
            log.error("Unsupported callback type " + callbacks[i].getClass().getName());
            throw new UnsupportedCallbackException(callbacks[i],
                    "Unsupported callback type " + callbacks[i].getClass().getName());
        }/*from w w  w .  j  av a  2s. co  m*/
    }
}