Example usage for org.apache.commons.codec.binary Base64 encodeBase64

List of usage examples for org.apache.commons.codec.binary Base64 encodeBase64

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base64 encodeBase64.

Prototype

public static byte[] encodeBase64(final byte[] binaryData) 

Source Link

Document

Encodes binary data using the base64 algorithm but does not chunk the output.

Usage

From source file:com.photon.phresco.framework.actions.forum.Forum.java

public String forum() {
    if (S_LOGGER.isDebugEnabled())
        S_LOGGER.debug("entered forumIndex()");

    if (debugEnabled) {
        S_LOGGER.debug("Entering Method Forum.forum()");
    }//from www  .  java2 s .c o  m

    try {

        ProjectAdministrator administrator = PhrescoFrameworkFactory.getProjectAdministrator();
        String serviceUrl = administrator.getJforumPath();

        User sessionUserInfo = (User) getHttpSession().getAttribute(REQ_USER_INFO);
        //         Credentials credentials = sessionUserInfo.getCredentials();
        Credentials credentials = null;

        String username = credentials.getUsername();
        byte[] usernameEncode = Base64.encodeBase64(username.getBytes());
        String encodedUsername = new String(usernameEncode);

        String password = credentials.getPassword();

        getHttpRequest().setAttribute(REQ_USER_NAME, encodedUsername);
        getHttpRequest().setAttribute(REQ_PASSWORD, password);

        URL sonarURL = new URL(serviceUrl);
        HttpURLConnection connection = (HttpURLConnection) sonarURL.openConnection();
        int responseCode = connection.getResponseCode();
        if (responseCode != 200) {
            getHttpRequest().setAttribute(REQ_ERROR, "Help is not available");
            return HELP;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(serviceUrl);
        sb.append(JFORUM_PARAMETER_URL);
        sb.append(JFORUM_USERNAME);
        sb.append(encodedUsername);
        sb.append(JFORUM_PASSWORD);
        sb.append(password);

        getHttpRequest().setAttribute(REQ_JFORUM_URL, sb.toString());

    } catch (Exception e) {
        if (debugEnabled) {
            S_LOGGER.error(
                    "Entered into catch block of Forum.forum()" + FrameworkUtil.getStackTraceAsString(e));
        }
    }
    return HELP;
}

From source file:br.ufsm.csi.hotelmanagementats.controller.UsuarioAdmController.java

@RequestMapping(value = "cadastrarAdministrador.html", method = RequestMethod.POST)
public ModelAndView cadastrarUsuarioAdm(UsuarioAdministrador u, HttpServletRequest rq)
        throws NoSuchAlgorithmException, UnsupportedEncodingException {
    System.out.println("-------------------------------");
    System.out.println("Submit Formulrio de Cadastro de Administrador...");

    ModelAndView mv = new ModelAndView("/WEB-INF/views/cadastroAdministrador");

    UsuarioAdmDao uD = new UsuarioAdmDao();

    if (u.getNome() != null && u.getCpf() != null && u.getTelFixo() != null && u.getTelCel() != null
            && u.getEmail() != null && u.getSenha() != null) {

        if (u.getNome().length() > 0 && u.getCpf().length() == 14 && u.getTelCel().length() == 15
                && u.getEmail().length() > 0 && u.getSenha().length() > 0) {

            byte[] senha = rq.getParameter("senha").getBytes();

            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hashSenha = md.digest(senha);

            byte[] hashSenhaBase = Base64.encodeBase64(hashSenha);
            String valorSenha = new String(hashSenhaBase, "ISO-8859-1");

            u.setSenha(valorSenha);//from w  ww.j  av a2  s.c  o  m

            try {
                boolean retorno = uD.cadastrarUsuarioAdm(u);

                if (retorno) {
                    mv = new ModelAndView("/WEB-INF/views/paginaInicial");
                    mv.addObject("mensagem", "<Strong>Sucesso</Strong> Cadastro feito com sucesso!");
                    mv.addObject("tipo", "success");
                    System.out.println("Cadastro Concludo!");
                } else {
                    mv.addObject("mensagem", "<Strong>Erro</Strong> Dados de cadastro j utilizados!");
                    mv.addObject("tipo", "danger");
                    System.out.println("Erro ao cadastrar!");
                }

            } catch (Exception e) {
                e.printStackTrace();
                mv.addObject("mensagem", "<Strong>Erro</Strong> Dados de cadastro j utilizados!");
                mv.addObject("tipo", "danger");
                System.out.println("Erro ao cadastrar!");
            }
        }
    }

    System.out.println("\n-------------------------------\n");

    return mv;
}

From source file:com.frame.Conf.Utilidades.java

/**
 * /*  w w w  .j a  v a 2 s.c om*/
 * @param keypass Es la llave plublica para enctriptar el texto
 * @param texto Texto a encriptar
 * @return retorna el hash del texto encriptado
 * @throws Exception 
 */
public String Encriptar(String keypass, String texto) throws Exception {

    String secretKey = keypass; //llave para encriptar datos
    String base64EncryptedString = "";

    try {

        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8"));
        byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);

        SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        byte[] plainTextBytes = texto.getBytes("utf-8");
        byte[] buf = cipher.doFinal(plainTextBytes);
        byte[] base64Bytes = Base64.encodeBase64(buf);
        base64EncryptedString = new String(base64Bytes);

    } catch (NoSuchAlgorithmException | UnsupportedEncodingException | NoSuchPaddingException
            | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
        throw new Exception(ex.getMessage());
    }
    return base64EncryptedString;
}

From source file:davmail.util.IOUtil.java

/**
 * Base64 encode value.//  w w  w . j  av  a  2  s. c  o  m
 *
 * @param value input value
 * @return base64  value
 * @throws IOException on error
 */
public static byte[] encodeBase64(String value) throws IOException {
    return Base64.encodeBase64(value.getBytes("UTF-8"));
}

From source file:com.canoo.cog.sonar.SonarServiceTest.java

@Test
public void testAuthenticationSonar() throws IOException {
    try {//from ww w. ja  v a 2  s.c o m
        URL url = new URL("https://ci.canoo.com/sonar/api/resources");
        String encoding = new String(Base64.encodeBase64("christophh:".getBytes()));

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setRequestProperty("Authorization", "Basic " + encoding);
        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.ikon.util.SecureStore.java

/**
 * Base64 encoder//  w  w  w  . j  av a  2  s  . co m
 */
public static String b64Encode(byte[] src) {
    return new String(Base64.encodeBase64(src));
}

From source file:jedi.util.serialization.Pickle.java

/**
 * Serializes a object on the main memory and returns a sequence of bytes as a String.
 * /*www  . j  a  v  a2s .  co m*/
 * @param o Object to be serialized.
 * @return String
 */

public static String dumps(Object o) {
    String s = "";

    try {
        // Serializing.

        // Reference to a sequence of bytes on the memory.
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(o);
        oos.close();

        // Converts a array of bytes into a String.
        // The default conversion doesn't works on the other hand Base64 works fine.
        s = new String(Base64.encodeBase64(baos.toByteArray()));

        baos.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return s;
}

From source file:com.moviejukebox.tools.WebBrowser.java

private static String encodePassword() {
    if (PROXY_USERNAME != null) {
        return ("Basic " + new String(Base64.encodeBase64((PROXY_USERNAME + ":" + PROXY_PASSWORD).getBytes())));
    }/*from  w w w  .  j ava  2s  .c  o m*/
    return StringUtils.EMPTY;
}

From source file:com.AES256Util.java

public String aesEncode(String str) throws java.io.UnsupportedEncodingException, NoSuchAlgorithmException,

        NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,

        IllegalBlockSizeException, BadPaddingException {

    Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");

    c.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv.getBytes()));

    byte[] encrypted = c.doFinal(str.getBytes("UTF-8"));

    String enStr = new String(Base64.encodeBase64(encrypted));

    return enStr;

}

From source file:core.TestConfig.java

public static String encodeAuth(String sUserName, String sPassword) {
    StringBuilder sb = new StringBuilder();
    sb.append(sUserName);/*  w  w w. j av  a 2  s. co m*/
    sb.append(":");
    sb.append(sPassword);
    String sRet = "Basic " + new String(Base64.encodeBase64(sb.toString().getBytes()));

    return sRet.replace("\n", "");
}