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

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

Introduction

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

Prototype

public static String encodeBase64String(final byte[] binaryData) 

Source Link

Document

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

Usage

From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java

public static HTTPResponseData sendPost(String url, String body, String username, String pwd) throws Exception {

    CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build();

    int responseCode = 0;
    StringBuffer respo = null;/* ww w.  ja  v a 2s.c  o m*/
    String userPassword = username + ":" + pwd;
    //        String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes());
    String encoding = Base64.encodeBase64String(userPassword.getBytes());

    try {
        HttpPost request = new HttpPost(url);
        request.addHeader("Authorization", "Basic " + encoding);
        request.addHeader("User-Agent", USER_AGENT);
        request.addHeader("Accept-Language", "en-US,en;q=0.5");
        request.addHeader("Content-Type", "application/json; charset=UTF-8");
        request.setHeader("Accept", "application/json");
        System.out.println("Executing request " + request.getRequestLine());
        System.out.println("Executing request " + Arrays.toString(request.getAllHeaders()));
        StringEntity se = new StringEntity(body);
        request.setEntity(se);
        CloseableHttpResponse response = client.execute(request);
        try {
            responseCode = response.getStatusLine().getStatusCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Post body : " + body);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            respo = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                respo.append(inputLine);
            }
        } finally {
            response.close();
        }
    } finally {
        client.close();
    }

    HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString()));
    System.out.println(result.getStatusCode() + "/n" + result.getBody());
    return result;
}

From source file:com.aliyun.odps.account.AliyunRequestSigner.java

public String getSignature(String resource, Request req) {
    try {/*from w w  w  .j  av a2 s.c  o m*/
        resource = URLDecoder.decode(resource, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    String strToSign = SecurityUtils.buildCanonicalString(resource, req, "x-odps-");

    if (log.isLoggable(Level.FINE)) {
        log.fine("String to sign: " + strToSign);
    }

    byte[] crypto = new byte[0];
    try {
        crypto = SecurityUtils.hmacsha1Signature(strToSign.getBytes("UTF-8"), accessKey.getBytes());
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    String signature = Base64.encodeBase64String(crypto).trim();

    return "ODPS " + accessId + ":" + signature;
}

From source file:info.magnolia.setup.HashUsersPasswordsTest.java

@Test
public void testEncryption() throws Exception {
    HashUsersPasswords hash = new HashUsersPasswords();
    InstallContext installContext = mock(InstallContext.class);
    HierarchyManager hm = mock(HierarchyManager.class);
    when(installContext.getHierarchyManager("users")).thenReturn(hm);
    MockContent root = new MockContent("");
    MockContent folder = new MockContent("system", ItemType.FOLDER);
    root.addContent(folder);/*from ww  w .jav a 2 s. c  om*/
    MockContent superuser = new MockContent("superuser", ItemType.USER);
    folder.addContent(superuser);
    String encodedPwd = Base64.encodeBase64String("blaboo".getBytes());
    superuser.addNodeData("pswd", encodedPwd);
    when(hm.getContent("/")).thenReturn(root);
    hash.execute(installContext);
    String hashPwd = superuser.getNodeData("pswd").getString();
    assertFalse(encodedPwd.equals(hashPwd));
    assertTrue(SecurityUtil.matchBCrypted("blaboo", hashPwd));
}

From source file:com.jwt.security.auth.cryptographics.Crypto.java

public static String base64(byte[] bytes) {
    return Base64.encodeBase64String(bytes);
}

From source file:algorithm.AesEncryption.java

@Override
public void encryptFile(File clearFile, File encrypted) {

    try {/*from  www . ja  v a 2 s  .  co m*/

        encrypt.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        encryptedString = Base64.encodeBase64String(encrypt.doFinal(buildString(clearFile).getBytes("UTF-8")));

        writeBytes(new ByteArrayInputStream(encryptedString.getBytes(StandardCharsets.UTF_8)),
                new FileOutputStream(encrypted));
    } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException ex) {
        Logger.getLogger(AesEncryption.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.twinsoft.convertigo.beans.transactions.HttpTransaction.java

@Override
public void makeDocument(byte[] httpData) throws Exception {
    String t = context.statistics.start(EngineStatistics.GENERATE_DOM);

    try {//from w  w  w  .ja v a2s . c  o  m
        String stringData = "";

        if (httpData == null || httpData.length == 0) {
            // nothing to do
        } else if (dataEncoding == HTTP_DATA_ENCODING_STRING) {
            String charset = ((HttpConnector) parent).getCharset();

            if (charset == null) {
                charset = "ascii";
            }
            try {
                stringData = new String(httpData, charset);
            } catch (UnsupportedEncodingException e) {
                Engine.logBeans.warn(
                        "(HttpTransaction) Unsupported Encoding to decode the response, use ascii instead", e);
                stringData = new String(httpData, "ascii");
            }
        } else if (dataEncoding == HTTP_DATA_ENCODING_BASE64) {
            stringData = Base64.encodeBase64String(httpData);
        } else {
            throw new IllegalArgumentException("Unknown data encoding: " + dataEncoding);
        }

        CDATASection cdata = context.outputDocument.createCDATASection(stringData); // remove TextCodec.UTF8Encode for #453
        Element outputDocumentRootElement = context.outputDocument.getDocumentElement();
        outputDocumentRootElement.appendChild(cdata);
    } finally {
        context.statistics.stop(t);
    }
}

From source file:info.fcrp.keepitsafe.bean.CryptBeanTest.java

@Test
public void assymetric() throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair kp = kpg.generateKeyPair();
    PrivateKey priKey = kp.getPrivate();
    PublicKey pubKey = kp.getPublic();

    Cipher c = Cipher.getInstance("RSA");
    String plain = "plain";
    byte[] plainBytes = plain.getBytes();

    c.init(Cipher.ENCRYPT_MODE, pubKey);
    c.update(plainBytes);/*from w w  w. ja  v a2  s.c  om*/

    byte[] encBytes = c.doFinal();
    String enc = Base64.encodeBase64String(encBytes);
    assertNotSame(plain, enc);

    c.init(Cipher.DECRYPT_MODE, priKey);
    c.update(encBytes);
    byte[] decBytes = c.doFinal();
    String dec = new String(decBytes);

    assertEquals(plain, dec);
}

From source file:com.github.nlloyd.hornofmongo.adaptor.BinData.java

public void setValues(int type, Object obj) {
    // carried over from sm_db.cpp, not v8_db.cpp which doesn't have this
    // check for some reason
    if ((type < 0) || (type > 255)) {
        throw new IllegalArgumentException("invalid BinData subtype -- range is 0..255 see bsonspec.org");
    }/*  www .  jav a2s. com*/
    this.type = type;
    byte[] tmpData = new byte[] {};
    if (obj instanceof byte[]) {
        tmpData = (byte[]) obj;
        this.data = Base64.encodeBase64String(tmpData);
    } else {
        this.data = Context.toString(obj);
        tmpData = Base64.decodeBase64(this.data);
    }
    put("type", this, type);
    put("len", this, tmpData.length);
}

From source file:edu.kit.scc.cdmi.rest.CapabilitiesTest.java

@Test
public void testGetDataObjectCapabilities() {
    String authString = Base64.encodeBase64String((restUser + ":" + restPassword).getBytes());

    Response response = given().header("Authorization", "Basic " + authString).and()
            .header("Content-Type", "application/cdmi-capability").when().get("/cdmi_capabilities/dataobject")
            .then().statusCode(org.apache.http.HttpStatus.SC_OK).extract().response();

    log.debug("Response {}", response.asString());
}

From source file:com.streamsets.lib.security.http.SignedSSOTokenGenerator.java

@Override
protected String generateData(SSOUserPrincipal principal) {
    String data = super.generateData(principal);
    generateKeysIfNecessary();//w w  w  . ja  v a2  s  . com
    try {
        String signature = Base64.encodeBase64String(
                DataSignature.get().getSigner(signingKeys.getPrivate()).sign(data.getBytes()));
        return signature + SSOConstants.TOKEN_PART_SEPARATOR + data;
    } catch (GeneralSecurityException ex) {
        throw new RuntimeException(ex);
    }
}