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.google.nigori.common.Revision.java

@Override
public String toString() {
    return bytesToString(Base64.encodeBase64(revision));
}

From source file:net.bryansaunders.jee6divelog.util.HashUtils.java

/**
 * Generates a HMAC-SHA1 Hash of the given String using the specified key.
 * /* w  ww.  ja  va  2s. c  o  m*/
 * @param stringToHash
 *            String to Hash
 * @param key
 *            Key to Sign the String with
 * @return Hashed String
 */
public static String toHmacSha1(final String stringToHash, final String key) {
    String result = "";
    try {
        // Get an hmac_sha1 key from the raw key bytes
        final byte[] keyBytes = key.getBytes();
        final SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        final byte[] rawHmac = mac.doFinal(stringToHash.getBytes());

        // Convert raw bytes to Hex
        final byte[] base64 = Base64.encodeBase64(rawHmac);

        // Covert array of Hex bytes to a String
        result = new String(base64);
    } catch (GeneralSecurityException e) {
        HashUtils.LOGGER.error("An Error Occured Generating an HMAC-SHA1 Hash!", e);
    }

    return result;
}

From source file:com.openbravo.webservicesimplementation.ButSystemClient.java

public ButSystemClient(String ip, String port) {
    serverIP = ip;//from   w  ww  . j a v a2s  .co m
    serverPort = port;
    String userPassword = USERNAME + ":" + PASSWORD;
    encoding = Base64.encodeBase64(userPassword.getBytes());
}

From source file:com.aimluck.eip.util.ALCellularUtils.java

/**
 * ?? ID ??? URL ??????/*from  ww w .  ja v a  2s.c o  m*/
 * 
 * @param username
 * @return
 */
public static String getCheckValueForCellLogin(String username, String userid) {
    if (username == null || username.length() == 0 || userid == null) {
        return "";
    }

    String marge = username + userid;
    CRC32 crc32 = new CRC32();
    crc32.update(marge.getBytes());
    long value = crc32.getValue();
    String base64value = null;
    try {
        base64value = new String(Base64.encodeBase64(String.valueOf(value).getBytes()));
    } catch (Exception e) {
    }

    return (base64value == null) ? "" : base64value.toLowerCase();
}

From source file:com.climate.oada.security.oauth.TokenServicesImpl.java

@Override
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    LOG.debug("Generating OAuth Token for principal: " + authentication.getName());
    DefaultOAuth2AccessToken result = null;
    String randomUUID = UUID.randomUUID().toString();
    MessageDigest md = null;//from w  w w .ja  va 2s .  co  m
    try {
        byte[] emailBytes = authentication.getName().getBytes("UTF-8");
        md = MessageDigest.getInstance("MD5");
        String emailDigest = new String(Base64.encodeBase64(md.digest(emailBytes)));
        String token = randomUUID + emailDigest;
        result = new DefaultOAuth2AccessToken(token);
        int validitySeconds = getAccessTokenValiditySeconds(authentication.getAuthorizationRequest());
        if (validitySeconds > 0) {
            result.setExpiration(new Date(System.currentTimeMillis() + (validitySeconds * SEC_TO_MSEC)));
        }
        result.setTokenType("Bearer");
        tokenStore.storeAccessToken(result, authentication);
    } catch (Exception e) {
        LOG.error("Unable to generate OAuth token: " + e.getMessage());
    }
    return result;
}

From source file:com.att.api.speech.controller.TextToSpeechController.java

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

    final JSONObject jresponse = new JSONObject();
    try {//from w w  w .  j  a  v  a2s.co  m

        final OAuthToken token = this.getFileToken();
        final TtsService srvc = new TtsService(appConfig.getApiFQDN(), token);

        final String contentType = request.getParameter("contentType");
        final String plaintext = request.getParameter("plaintext");
        final String ssml = request.getParameter("ssml");
        final String xArg = request.getParameter("x_arg");
        String speechText = null;
        if (contentType.equals("text/plain")) {
            speechText = plaintext;
            if (speechText.length() > 250) {
                throw new Exception("Character limited of 250 reached");
            }
        } else {
            speechText = ssml;
        }
        final byte[] wavBytes = srvc.sendRequest(contentType, speechText, xArg);

        JSONObject jaudio = new JSONObject().put("type", "audio/wav").put("base64",
                new String(Base64.encodeBase64(wavBytes)));
        jresponse.put("success", true).put("audio", jaudio);
    } catch (Exception e) {
        jresponse.put("success", false).put("text", e.getMessage());
    }

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.print(jresponse);
    writer.flush();
}

From source file:com.centurylink.mdw.util.CryptUtil.java

private static String encodeBase64(byte[] inputBytes) {
    return new String(Base64.encodeBase64(inputBytes));
}

From source file:dal.arris.RequestArrisAlter.java

public RequestArrisAlter(Integer deviceId, Autenticacao autenticacao, String frequency)
        throws UnsupportedEncodingException, IOException {
    Autenticacao a = AuthFactory.getEnd();
    String auth = a.getUser() + ":" + a.getPassword();
    String url = a.getLink() + "capability/execute?capability="
            + URLEncoder.encode("\"getLanWiFiInfo\"", "UTF-8") + "&deviceId=" + deviceId + "&input="
            + URLEncoder.encode(frequency, "UTF-8");

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(1);//w w  w  . ja  va2  s. c  o  m
    cm.setDefaultMaxPerRoute(1);
    HttpHost localhost = new HttpHost("10.200.6.150", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);

    // Cookies
    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm)
            .setDefaultRequestConfig(globalConfig).build();

    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("UTF-8")));
    String authHeader = "Basic " + new String(encodedAuth);

    //        CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        httpget.setHeader(HttpHeaders.CONTENT_TYPE, "text/html");
        httpget.setHeader("Cookie", "JSESSIONID=aaazqNDcHoduPbavRvVUv; AX-CARE-AGENTS-20480=HECDMIAKJABP");

        RequestConfig localConfig = RequestConfig.copy(globalConfig).setCookieSpec(CookieSpecs.STANDARD_STRICT)
                .build();

        HttpGet httpGet = new HttpGet("/");
        httpGet.setConfig(localConfig);

        //            httpget.setHeader(n);
        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            // If the response does not enclose an entity, there is no need
            // to bother about connection release
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    instream.read();
                    BufferedReader rd = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));
                    String line = "";
                    while ((line = rd.readLine()) != null) {
                        System.out.println(line);
                    }
                    // do something useful with the response
                } catch (IOException ex) {
                    // In case of an IOException the connection will be released
                    // back to the connection manager automatically
                    throw ex;
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } finally {
            response.close();
            for (Header allHeader : response.getAllHeaders()) {
                System.out.println("Nome: " + allHeader.getName() + " Valor: " + allHeader.getValue());
            }
        }
    } finally {
        httpclient.close();
    }
    httpclient.close();
}

From source file:edu.harvard.iq.dvn.unf.Base64Encoding.java

/**
 *
 * @param digest byte array for encoding in base 64,
 * @param  chngByteOrd boolean indicating if to change byte order
 * @return String the encoded base64 of digest
 *///from   www . java 2 s.  c o  m
public static String tobase64(byte[] digest, boolean chngByteOrd) {

    byte[] tobase64 = null;
    ByteOrder local = ByteOrder.nativeOrder();
    String ordbyte = local.toString();
    mLog.finer("Native byte order is: " + ordbyte);
    ByteBuffer btstream = ByteBuffer.wrap(digest);
    btstream.order(ByteOrder.BIG_ENDIAN);
    byte[] revdigest = null;
    if (chngByteOrd) {
        revdigest = changeByteOrder(digest, local);
    }
    if (revdigest != null) {
        btstream.put(revdigest);
    } else {
        btstream.put(digest);
    }

    tobase64 = Base64.encodeBase64(btstream.array());

    return new String(tobase64);

}

From source file:ext.services.network.Proxy.java

/**
 * Gets the connection./*  ww  w  .  ja va  2s .c om*/
 * 
 * @param u 
 * 
 * @return the connection
 * 
 * @throws IOException Signals that an I/O exception has occurred.
 */
public URLConnection getConnection(URL u) throws IOException {
    URLConnection con = u.openConnection(this);
    String encodedUserPwd = new String(Base64.encodeBase64((user + ':' + password).getBytes()));
    con.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
    return con;
}