Java Base64 Encode base64encode(String s)

Here you can find the source of base64encode(String s)

Description

baseencode

License

Open Source License

Declaration

public static String base64encode(String s) 

Method Source Code

//package com.java2s;
/*/*  www .j a  va2  s  .  co m*/
 *  $File$ $Revision$ $Date$
 *
 *  ADOBE SYSTEMS INCORPORATED
 *    Copyright 2007 Adobe Systems Incorporated
 *    All Rights Reserved.
 *
 *  NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the 
 *  terms of the Adobe license agreement accompanying it.  If you have received this file from a 
 *  source other than Adobe, then your use, modification, or distribution of it requires the prior 
 *  written permission of Adobe.
 */

public class Main {
    private static String base64code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
            + "abcdefghijklmnopqrstuvwxyz" + "0123456789" + "+/";

    public static String base64encode(String s) {
        return base64encode(s.getBytes());
    }

    public static String base64encode(byte b[]) {
        StringBuilder encoded = new StringBuilder();
        int padding = (3 - (b.length % 3)) % 3;
        for (int i = 0; i < b.length; i += 3) {
            int j = (getPadded(b, i) << 16) + (getPadded(b, i + 1) << 8)
                    + getPadded(b, i + 2);
            encoded.append(base64code.charAt((j >> 18) & 0x3f));
            encoded.append(base64code.charAt((j >> 12) & 0x3f));
            encoded.append(base64code.charAt((j >> 6) & 0x3f));
            encoded.append(base64code.charAt((j >> 0) & 0x3f));
        }

        encoded.replace(encoded.length() - padding, encoded.length(),
                "==".substring(0, padding));

        return encoded.toString();
    }

    private static byte getPadded(byte b[], int i) {
        return i < b.length ? b[i] : 0;
    }
}

Related

  1. base64Encode(int value)
  2. base64Encode(String _s, String _enc)
  3. base64Encode(String plaintext)
  4. base64Encode(String plainTextString)
  5. base64Encode(String s)
  6. base64Encode(String s)
  7. base64Encode(String s)
  8. base64encode(String str)
  9. base64Encode(String string)