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.github.jinahya.codec.PercentBinaryEncoderProxyTest.java

@Test(invocationCount = 128)
public void testEncode() throws Exception {

    final BinaryEncoder encoder = (BinaryEncoder) PercentBinaryEncoderProxy.newInstance();

    try {/*from  ww w .j av a  2s  .co  m*/
        encoder.encode((Object) null);
        Assert.fail("passed: encode((Object) null)");
    } catch (final NullPointerException npe) {
        // expected
    }

    try {
        encoder.encode((byte[]) null);
        Assert.fail("passed: encode((byte[]) null)");
    } catch (final NullPointerException npe) {
        // expected
    }

    final byte[] origin = PercentCodecTestHelper.decodedBytes(1024);
    System.out.println("original ----------------------------------------");
    System.out.println(Base64.encodeBase64String(origin));

    final byte[] encoded = encoder.encode(origin);
    System.out.println("encoded -----------------------------------------");
    System.out.println(new String(encoded, "US-ASCII"));

    final byte[] decoded = PercentDecoder.decodeMultiple(encoded);
    System.out.println("decoded -----------------------------------------");
    System.out.println(Base64.encodeBase64String(decoded));

    Assert.assertEquals(decoded, origin);
}

From source file:net.ftb.util.CryptoUtils.java

/**
 * Method to AES encrypt string if fails, will attempt to use {@link #encryptLegacy(String str, byte[] key)}
 * @param str string to encrypt/*w ww .j a  v a  2s .com*/
 * @param key encryption key
 * @return encrypted string or "" if legacy fails
 */
public static String encrypt(String str, byte[] key) {
    try {
        Cipher aes = Cipher.getInstance("AES");
        aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(pad(key), "AES"));
        return Base64.encodeBase64String(aes.doFinal(("FDT:" + str).getBytes("utf8")));
    } catch (Exception e) {
        Logger.logError("Error Encrypting information, reverting to legacy format", e);
        return encryptLegacy(str, key);
    }
}

From source file:com.galenframework.storage.repository.LocalFileStorage.java

@Override
public FileInfo saveImageToStorage(InputStream inputStream) {
    try {/*from  w  ww  .  j  ava  2s.co  m*/
        MessageDigest md = MessageDigest.getInstance("MD5");

        String dirsPath = generateImageDirsPath();

        File dirs = new File(root.getPath() + File.separator + dirsPath);
        dirs.mkdirs();

        String fileName = UUID.randomUUID().toString();
        File file = new File(dirs.getPath() + File.separator + fileName);
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);

        DigestInputStream dis = new DigestInputStream(inputStream, md);

        IOUtils.copy(dis, fos);
        fos.flush();
        fos.close();

        byte[] digest = md.digest();
        String hash = Base64.encodeBase64String(digest);
        return new FileInfo(hash, dirsPath + File.separator + fileName);
    } catch (Exception ex) {
        throw new RuntimeException("Cannot save image to storage", ex);
    }
}

From source file:io.cloudslang.lang.entities.bindings.values.SensitiveValue.java

protected String encrypt(Serializable originalContent) {
    byte[] serialized = serialize(originalContent);
    String serializedAsString = Base64.encodeBase64String(serialized);
    Encryption encryption = EncryptionProvider.get();
    if (SensitivityLevel.OBFUSCATED == sensitivityLevel) {
        return encryption.obfuscate(serializedAsString);
    } else {//  ww  w.ja  v  a  2  s  .  c  om
        return encryption.encrypt(serializedAsString.toCharArray());
    }
}

From source file:energy.usef.core.data.participant.Participant.java

public void setPublicKeysFromString(String concatenatedKeys) {
    if (concatenatedKeys == null) {
        return;/*w  w  w  . ja v  a2  s  . c  om*/
    }
    if (!concatenatedKeys.startsWith(CS1_PREFIX)) {
        throw new IllegalArgumentException("Keys does not have an recognized prefix.");
    }
    String actualConcatenatedKey = concatenatedKeys.substring(CS1_PREFIX.length());
    byte[] decodedKey = Base64.decodeBase64(actualConcatenatedKey);
    byte[] firstKey = Arrays.copyOfRange(decodedKey, FIRST_KEY_INDEX, SECOND_KEY_INDEX);
    setPublicKeys(Arrays.asList(Base64.encodeBase64String(firstKey),
            Base64.encodeBase64String(new byte[SECOND_KEY_SIZE])));
}

From source file:edu.tamu.tcat.crypto.bouncycastle.PBKDF2Impl.java

@Override
protected String deriveHash(byte[] password, int rounds, byte[] salt) {
    int outputSize = bouncyDigest.getDigestSize();

    String hashType;//from  w  w  w.  j  av a 2  s.  c  om
    if (digest == DigestType.SHA1)
        hashType = "pbkdf2";
    else
        hashType = "pbkdf2-" + digest.name().toLowerCase();
    byte[] output = deriveKey(password, salt, rounds, outputSize);
    // Use "$" as separator between entries in the field. Returning a single string is helpful to store as a single
    // value e.g. in a database table, but multiple pieces of information are required. The separator is used elsewhere, so is
    // just as good as another field separator.
    //NOTE: convert '+' to '.' to avoid issues with URL encoding of the derived hash (converting '+' to "%2B")
    return "$" + hashType + "$" + rounds + "$" + Base64.encodeBase64String(salt).replace('+', '.') + "$"
            + Base64.encodeBase64String(output).replace('+', '.');
}

From source file:com.ritesh.idea.plugin.reviewboard.ReviewBoardClient.java

private String getAuthorizationHeader(String userName, String password) {
    return "Basic " + Base64.encodeBase64String((userName + ":" + password).getBytes());
}

From source file:net.arccotangent.pacchat.net.KeyUpdateClient.java

public void run() {
    Socket socket;/* ww  w  . j a  va 2  s .  c om*/
    BufferedReader input;
    BufferedWriter output;

    kuc_log.i("Connecting to server at " + server_ip);

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server_ip), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        kuc_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        kuc_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        kuc_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        kuc_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        kuc_log.i("Requesting a key update.");
        output.write("302 request key update");
        output.newLine();
        output.flush();

        kuc_log.i("Awaiting response from server.");
        String update = input.readLine();
        switch (update) {
        case "303 update":
            kuc_log.i("Server accepted update request, sending public key.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "304 no update":
            kuc_log.i("Server rejected update request, closing connection.");
            input.close();
            output.close();
            break;
        case "305 update unavailable":
            kuc_log.i("Server cannot update at this time, try again later.");
            input.close();
            output.close();
            break;
        default:
            kuc_log.i("Server sent back invalid response");
            input.close();
            output.close();
            break;
        }
    } catch (IOException e) {
        kuc_log.e("Error in key update request!");
        e.printStackTrace();
    }
}

From source file:net.bryansaunders.jee6divelog.dao.user.UserAccountDaoIT.java

/**
 * Test method for save().//from ww  w .  j  a  va2  s.  c om
 */
@Test
@UsingDataSet("Empty.yml")
@ShouldMatchDataSet("expected/GenericDaoIT-ifNotNullThenSave.yml")
public void ifNotNullThenSave() {
    // given
    final String pass = "abcdef1A@";

    final UserAccount validUser = new UserAccount();
    validUser.setFirstName("Bryan");
    validUser.setLastName("Saunders");
    validUser.setEmail("bryan@test.com");
    validUser.setCity("Charleston");
    validUser.setState("SC");
    validUser.setCountry("USA");
    validUser.setPassword(pass);

    // when
    final UserAccount savedUser = this.userDao.save(validUser);

    // check the password
    final String hashedEncodedPass = Base64.encodeBase64String(DigestUtils.sha256Hex(pass).getBytes());
    assertEquals(hashedEncodedPass, savedUser.getPassword());
}

From source file:fitmon.DietAPI.java

public ArrayList<Food> getFood(String foodID) throws ClientProtocolException, IOException,
        NoSuchAlgorithmException, InvalidKeyException, SAXException, ParserConfigurationException {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api&"
            + "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1408230438&"
            + "oauth_nonce=abc&oauth_version=1.0&method=food.get&food_id=33691");
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    String base = URLEncoder.encode("GET") + "&";
    base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";

    String params;/*  w  w w. j a v  a2s. c  om*/

    params = "food_id=" + foodID + "&";
    params += "method=food.get&";
    params += "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&"; // ur consumer key 
    params += "oauth_nonce=123&";
    params += "oauth_signature_method=HMAC-SHA1&";
    Date date = new java.util.Date();
    Timestamp ts = new Timestamp(date.getTime());
    params += "oauth_timestamp=" + ts.getTime() + "&";
    params += "oauth_version=1.0";
    //params += "search_expression=apple"; 

    String params2 = URLEncoder.encode(params);
    base += params2;
    System.out.println(base);
    String line = "";

    String secret = "76172de2330a4e55b90cbd2eb44f8c63&";
    Mac sha256_HMAC = Mac.getInstance("HMACSHA1");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HMACSHA1");
    sha256_HMAC.init(secret_key);
    String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(base.getBytes()));

    //$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig); 

    String url = "http://platform.fatsecret.com/rest/server.api?" + params + "&oauth_signature="
            + URLEncoder.encode(hash);
    System.out.println(url);
    xmlParser xParser = new xmlParser();
    ArrayList<Food> foodList = xParser.Parser(url);
    return foodList;
    //while ((line = rd.readLine()) != null) {
    //  System.out.println(line);
    //}
}