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:club.jmint.crossing.specs.Security.java

public static String desEncrypt(String data, String key) throws CrossException {
    String ret = null;/*  w w  w.  j  a v a  2 s  .c  o m*/
    try {
        DESKeySpec desKey = new DESKeySpec(key.getBytes("UTF-8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);

        Cipher cipher = Cipher.getInstance(CIPHER_DES_ALGORITHM);
        SecureRandom random = new SecureRandom();
        cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
        byte[] results = cipher.doFinal(data.getBytes("UTF-8"));
        ret = Base64.encodeBase64String(results);
    } catch (Exception e) {
        CrossLog.printStackTrace(e);
        throw new CrossException(ErrorCode.COMMON_ERR_ENCRYPTION.getCode(),
                ErrorCode.COMMON_ERR_ENCRYPTION.getInfo());
    }
    return ret;
}

From source file:es.upm.oeg.examples.watson.service.LanguageIdentificationService.java

public String getLang(String text) throws IOException, URISyntaxException {

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("txt", text));
    qparams.add(new BasicNameValuePair("sid", "lid-generic"));
    qparams.add(new BasicNameValuePair("rt", "json"));

    Executor executor = Executor.newInstance().auth(username, password);

    URI serviceURI = new URI(baseURL).normalize();
    String auth = username + ":" + password;
    String resp = executor.execute(Request.Post(serviceURI)
            .addHeader("Authorization", "Basic " + Base64.encodeBase64String(auth.getBytes()))
            .bodyString(URLEncodedUtils.format(qparams, "utf-8"), ContentType.APPLICATION_FORM_URLENCODED))
            .returnContent().asString();

    JSONObject lang = JSONObject.parse(resp);

    return lang.get("lang").toString();

}

From source file:dualcontrol.CryptoClientDemo.java

private void call(Properties properties, MockableConsole console, String hostAddress, int port, byte[] data)
        throws Exception {
    Socket socket = SSLContexts.create(false, "cryptoclient.ssl", properties, console).getSocketFactory()
            .createSocket(hostAddress, port);
    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    dos.writeShort(data.length);// w  ww . j a  va 2 s. c o m
    dos.write(data);
    dos.flush();
    DataInputStream dis = new DataInputStream(socket.getInputStream());
    byte[] ivBytes = new byte[dis.readShort()];
    dis.readFully(ivBytes);
    byte[] bytes = new byte[dis.readShort()];
    dis.readFully(bytes);
    if (new String(data).contains("DECRYPT")) {
        System.err.printf("INFO CryptoClientDemo decrypted %s\n", new String(bytes));
    } else {
        System.out.printf("%s:%s\n", Base64.encodeBase64String(ivBytes), Base64.encodeBase64String(bytes));
    }
    socket.close();
}

From source file:fredboat.command.admin.TestCommand.java

@Override
public void onInvoke(Guild guild, TextChannel channel, Member invoker, Message message, String[] args) {
    try {/*from  w  w w  . jav  a  2 s  .  c o  m*/
        GuildPlayer player = PlayerRegistry.get(guild);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        AbstractPlayer.getPlayerManager().encodeTrack(new MessageOutput(baos),
                player.getPlayingTrack().getTrack());

        String msg = Base64.encodeBase64String(baos.toByteArray());

        ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decodeBase64(msg));
        AudioTrack at = AbstractPlayer.getPlayerManager().decodeTrack(new MessageInput(bais)).decodedTrack;
        channel.sendMessage("Loaded track " + at.getInfo().title).queue();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.hpe.caf.worker.testing.validation.Base64PropertyValidator.java

@Override
protected boolean isValid(Object testedPropertyValue, Object validatorPropertyValue) {
    if (validatorPropertyValue == null) {
        return testedPropertyValue == null;
    }//  w ww .  j a  v  a 2 s  . c o m

    if (testedPropertyValue == null) {
        return false;
    }

    if (!(testedPropertyValue instanceof byte[]) || !(validatorPropertyValue instanceof String)) {
        throw new AssertionError(
                "Unexpected types provided to Base64PropertyValidator. Expected byte array testedPropertyValue and String validatorPropertyValue. Provided were "
                        + testedPropertyValue.getClass().getSimpleName() + " and "
                        + validatorPropertyValue.getClass().getSimpleName() + ". Values: "
                        + testedPropertyValue.toString() + ", " + validatorPropertyValue.toString());
    }

    byte[] testedPropertyValueBytes = (byte[]) testedPropertyValue;

    if (validatorPropertyValue.toString().equals("*")) {
        return testedPropertyValueBytes.length > 0;
    }

    boolean areEqual = Arrays.equals(testedPropertyValueBytes,
            Base64.decodeBase64(validatorPropertyValue.toString()));

    if (!areEqual) {
        String actual = Base64.encodeBase64String(testedPropertyValueBytes);
        System.err.println("Unexpected result. Actual value: " + actual + ", expected value: "
                + validatorPropertyValue.toString());
    }

    return areEqual;
}

From source file:info.bonjean.beluga.util.ResourcesUtil.java

public static String getResourceBase64(String resource) {
    return Base64.encodeBase64String(getResourceAsByteArray(resource));
}

From source file:com.alta189.deskbin.util.DesEncrypter.java

public String encrypt(String str) {
    try {// ww w .j a va 2  s  .  c o m
        // Encode the string into bytes using utf-8
        byte[] utf8 = str.getBytes("UTF8");

        // Encrypt
        byte[] enc = ecipher.doFinal(utf8);

        // Encode bytes to base64 to get a string
        return Base64.encodeBase64String(enc);
    } catch (javax.crypto.BadPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:fiftyone.mobile.detection.webapp.ImageCache.java

/**
 * Gets a base 64 encoded version of the image URL.
 * @param imageLocal/*from  ww w .  j av  a  2s. c  o m*/
 * @return
 * @throws UnsupportedEncodingException 
 */
private static String getEncodedFile(String imageLocal) throws UnsupportedEncodingException {
    String encoded = Base64.encodeBase64String(imageLocal.getBytes("US-ASCII"));

    StringBuilder sb = new StringBuilder();
    int iteration = 0;
    int startIndex = iteration * SPLIT_COUNT;
    while (startIndex < encoded.length()) {
        int length = encoded.length() - startIndex;
        sb.append(encoded.substring(startIndex, (length > SPLIT_COUNT ? SPLIT_COUNT : length) + startIndex));
        iteration++;
        startIndex = iteration * SPLIT_COUNT;
        if (startIndex < encoded.length()) {
            sb.append("/");
        }
    }

    return sb.toString();
}

From source file:com.telefonica.euro_iaas.sdc.util.RSASignerImpl.java

/**
 * {@inheritDoc}// w ww  .  j  a va  2  s  .  c o  m
 */

public String sign(String message, File pemFile) {
    try {
        Security.addProvider(new BouncyCastleProvider());
        PrivateKey privateKey = readKeyPair(pemFile, "".toCharArray()).getPrivate();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        byte[] digest = cipher.doFinal(message.getBytes());
        return Base64.encodeBase64String(digest);
    } catch (IOException e) {
        throw new SdcRuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SdcRuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new SdcRuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new SdcRuntimeException(e);
    } catch (IllegalBlockSizeException e) {
        throw new SdcRuntimeException(e);
    } catch (BadPaddingException e) {
        throw new SdcRuntimeException(e);
    }
}

From source file:net.jmhertlein.core.crypto.Keys.java

/**
 * Saves the given key to the given file. This method will NOT clobber
 * existing files- will return false if file exists The file will be
 * created, along with any parent directories needed.
 *
 * @param file name of file to save to//  ww w . j a  v  a 2  s .c o  m
 * @param key  key to save
 *
 * @return true if successfully written, false otherwise
 */
public static boolean storeKey(String file, Key key) {
    File f = new File(file);
    if (!f.exists())
        try {
            if (f.getParentFile() != null)
                f.getParentFile().mkdirs();
            f.createNewFile();
        } catch (IOException ex) {
            Logger.getLogger(Keys.class.getName()).log(Level.SEVERE, null, ex);
        }
    else
        return false;

    try (FileOutputStream fos = new FileOutputStream(file); PrintStream ps = new PrintStream(fos)) {
        ps.println(Base64.encodeBase64String(key.getEncoded()));
        return true;
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return false;
    }
}