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:net.gcolin.httpquery.RequestImpl.java

public Request setAuthBasic(String username, String password) {
    return header("Authorization", "Basic " + Base64.encodeBase64((username + ":" + password).getBytes()));
}

From source file:cascading.util.Util.java

public static String serializeBase64(Object object, boolean compress) throws IOException {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();

    ObjectOutputStream out = new ObjectOutputStream(compress ? new GZIPOutputStream(bytes) : bytes);

    try {/*from w ww  .java2 s.  com*/
        out.writeObject(object);
    } finally {
        out.close();
    }

    return new String(Base64.encodeBase64(bytes.toByteArray()));
}

From source file:info.staticfree.SuperGenPass.hashes.SuperGenPass.java

/**
 * Returns a base64-encoded string of the digest of the data. Caution: SuperGenPass-specific!
 * Includes substitutions to ensure that valid base64 characters '=', '/', and '+' get mapped to
 * 'A', '8', and '9' respectively, so as to ensure alpha/num passwords.
 *
 * @param data//from  w ww  .j a  v a 2 s .  c om
 * @return base64-encoded string of the hash of the data
 */
private String hashBase64(byte[] data) {

    String b64 = new String(Base64.encodeBase64(mHasher.digest(data)));
    // SuperGenPass-specific quirk so that these don't end up in the password.
    b64 = b64.replace('=', 'A').replace('/', '8').replace('+', '9');
    b64.trim();

    return b64;
}

From source file:com.flexive.shared.FxMailUtils.java

/**
 * Encode an input stream as email attachment
 *
 * @param mimeType mime type/*  w  w w . j a  v a 2 s . c  o m*/
 * @param fileName filename
 * @param input     the data to encode
 * @return file encoded as email attachment
 * @throws IOException on errors
 */
public static String encodeAttachment(String mimeType, String fileName, InputStream input) throws IOException {
    final byte[] data = IOUtils.toByteArray(input);
    final StringBuilder encoded = new StringBuilder(data.length * 4);
    encoded.append("Content-Type: ").append(mimeType).append(";\n");
    encoded.append(" name=\"").append(fileName).append("\"\n");
    encoded.append("Content-Transfer-Encoding: base64\n");
    encoded.append("Content-Disposition: attachment;\n");
    encoded.append(" filename=\"").append(fileName).append("\"\n\n");
    int k;
    final String attachmentEncoded = new String(Base64.encodeBase64(data), "UTF-8");
    int kLines = attachmentEncoded.length() / 74;
    for (k = 0; k < kLines; k++) {
        encoded.append(attachmentEncoded.substring(k * 74, k * 74 + 74)).append("\n");
    }
    if (kLines * 74 < attachmentEncoded.length())
        encoded.append(attachmentEncoded.substring(k * 74, attachmentEncoded.length())).append("\n");
    return encoded.toString();
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleTokenEncrypter.java

@Override
public String encrypt(String token) throws InvalidCipherTextException {
    //Convert the token into a byte[]
    final byte[] tokenBytes = token.getBytes(CHARSET);

    //Generate the Base64 encoded hash of the token
    final GeneralDigest digest = createDigester();
    digest.update(tokenBytes, 0, tokenBytes.length);
    final byte[] hashBytes = new byte[digest.getDigestSize()];
    digest.doFinal(hashBytes, 0);/* w  ww  .  ja  va 2 s.com*/
    final byte[] encodedHashBytes = Base64.encodeBase64(hashBytes);

    //Create the pre-encryption byte[] to hold the token, separator, and hash
    final byte[] tokenWithHashBytes = new byte[tokenBytes.length + SEPARATOR_BYTES.length
            + encodedHashBytes.length];

    //Copy in password bytes
    System.arraycopy(tokenBytes, 0, tokenWithHashBytes, 0, tokenBytes.length);

    //Copy in separator bytes
    System.arraycopy(SEPARATOR_BYTES, 0, tokenWithHashBytes, tokenBytes.length, SEPARATOR_BYTES.length);

    //Copy in encoded hash bytes
    System.arraycopy(encodedHashBytes, 0, tokenWithHashBytes, tokenBytes.length + SEPARATOR_BYTES.length,
            encodedHashBytes.length);

    AsymmetricBlockCipher e = getEncryptCipher();

    //Encrypt the bytes
    final byte[] encryptedTokenWithHash = e.processBlock(tokenWithHashBytes, 0, tokenWithHashBytes.length);

    //Encode the encrypted data and convert it into a string
    final String encryptedToken = new String(Base64.encodeBase64(encryptedTokenWithHash), CHARSET);
    return TOKEN_PREFIX + encryptedToken + TOKEN_SUFFIX;
}

From source file:com.microsoft.azure.iothub.auth.SignatureHelper.java

/**
 * Encodes the signature using Base64 and then further
 * encodes the resulting string using UTF-8 encoding.
 *
 * @param sig the HMAC-SHA256 encrypted signature.
 *
 * @return the Base64-encoded signature.
 *//*from w ww. ja  v  a  2 s  .  c o m*/
public static byte[] encodeSignatureBase64(byte[] sig) {
    // Codes_SRS_SIGNATUREHELPER_11_006: [The function shall encode the signature using Base64.]
    return Base64.encodeBase64(sig);
}

From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java

public static String encode(List<SecurityKeyData> devices, String encyrptionKeyName) throws Exception {
    ArrayList<KeyHolder> keys = new ArrayList<KeyHolder>();
    for (SecurityKeyData dr : devices) {
        KeyHolder kh = new KeyHolder();
        kh.setCounter(dr.getCounter());/*w w w  . j av  a 2s  .com*/
        kh.setEnrollmentTime(dr.getEnrollmentTime());
        kh.setKeyHandle(dr.getKeyHandle());
        kh.setPublicKey(dr.getPublicKey());
        kh.setTransports(dr.getTransports());
        keys.add(kh);
    }

    String json = gson.toJson(keys);
    EncryptedMessage msg = new EncryptedMessage();

    SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName);
    if (key == null) {
        throw new Exception("Queue message encryption key not found");
    }

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    msg.setMsg(cipher.doFinal(json.getBytes("UTF-8")));
    msg.setIv(cipher.getIV());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
            new Deflater(Deflater.BEST_COMPRESSION, true));

    compressor.write(gson.toJson(msg).getBytes("UTF-8"));
    compressor.flush();
    compressor.close();

    String b64 = new String(Base64.encodeBase64(baos.toByteArray()));

    return b64;

}

From source file:com.redhat.rhn.frontend.xmlrpc.serializer.ScriptResultSerializer.java

/** {@inheritDoc} */
protected void doSerialize(Object value, Writer output, XmlRpcSerializer serializer)
        throws XmlRpcException, IOException {
    ScriptResult scriptResult = (ScriptResult) value;
    SerializerHelper helper = new SerializerHelper(serializer);
    helper.add("serverId", scriptResult.getServerId());
    helper.add("startDate", scriptResult.getStartDate());
    helper.add("stopDate", scriptResult.getStopDate());
    helper.add("returnCode", scriptResult.getReturnCode());
    String outputContents = scriptResult.getOutputContents();
    if (StringUtil.containsInvalidXmlChars2(outputContents)) {
        helper.add("output_enc64", Boolean.TRUE);
        helper.add("output", new String(Base64.encodeBase64(outputContents.getBytes("UTF-8")), "UTF-8"));
    } else {//  w ww  . j a  v  a2s  .  c o  m
        helper.add("output_enc64", Boolean.FALSE);
        helper.add("output", scriptResult.getOutputContents());
    }
    helper.writeTo(output);
}

From source file:cascalog.TupleMemoryInputFormat.java

public static String encodeBytes(byte[] bytes) {
    String byteString = null;//from  w ww  .j a  va  2 s  . co  m
    try {
        byteString = new String(Base64.encodeBase64(bytes), "US-ASCII");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
    return byteString;
}

From source file:com.bjtct.controller.BaseController.java

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String printWelcome(ModelMap model) throws SQLException {

    // got all team list
    List<Team> teamList = TeamDataDAO.getAllTeams();
    List<TeamForm> teamFormList = new ArrayList<TeamForm>();
    TeamForm tf = null;/*from  w  w  w.j a  v  a 2s  . c  o  m*/
    try {
        // preparing team form
        if (null != teamList && teamList.size() > 0) {

            for (Team t : teamList) {
                tf = new TeamForm();
                Blob b = t.getLogo();
                byte[] blobAsBytes = b.getBytes(1, (int) b.length());
                byte[] encoded = Base64.encodeBase64(blobAsBytes);
                String pic = new String(encoded);

                tf.setId(t.getId());
                tf.setLogo(pic);
                teamFormList.add(tf);
                // model.addAttribute(t.getId().toString(), pic);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    model.addAttribute(teamFormList);
    System.out.println(teamList.size());
    return "teams/home";

}