One BASE64 encryption
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
public class Base64utils {
private static final char[] Legalchars = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/". ToCharArray ();
/**
* data[] to encode
*
* @param data
* @return
*/
public static String encode (byte[] data) {
int start = 0;
int len = data.length;
StringBuffer buf = new StringBuffer (data.length * 3/2);
int end = Len-3;
int i = start;
int n = 0;
while (I <= end) {
int d = ((((int) data[i]) & 0X0FF) << 16)
| (((((int) Data[i + 1]) & 0X0FF) << 8)
| (((int) Data[i + 2]) & 0X0FF);
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >> 6) & 63]);
Buf.append (Legalchars[d & 63]);
i + = 3;
if (n++ >= 14) {
n = 0;
Buf.append ("");
}
}
if (i = = start + len-2) {
int d = ((((int) data[i]) & 0X0FF) << 16)
| (((((int) Data[i + 1]) & 255) << 8);
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >> 6) & 63]);
Buf.append ("=");
} else if (i = = start + len-1) {
int d = (((int) data[i]) & 0X0FF) << 16;
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >>) & 63]);
Buf.append ("= =");
}
return buf.tostring ();
}
private static int decode (char c) {
if (c >= ' A ' && C <= ' Z ')
return ((int) c)-65;
else if (c >= ' a ' && c <= ' z ')
return ((int) c)-97 + 26;
else if (c >= ' 0 ' && C <= ' 9 ')
return ((int) c)-48 + 26 + 26;
Else
Switch (c) {
Case ' + ':
Return 62;
Case '/':
return 63;
Case ' = ':
return 0;
Default
throw new RuntimeException ("Unexpected code:" + C);
}
}
/**
* Decodes the given BASE64 encoded String to a new byte array. The byte
* Array holding the decoded data is returned.
*/
public static byte[] Decode (String s) {
Bytearrayoutputstream BOS = new Bytearrayoutputstream ();
try {
Decode (S, BOS);
} catch (IOException e) {
throw new RuntimeException ();
}
byte[] decodedbytes = Bos.tobytearray ();
try {
Bos.close ();
BOS = NULL;
} catch (IOException ex) {
System.err.println ("Error while decoding BASE64:" + ex.tostring ());
}
return decodedbytes;
}
private static void Decode (String s, OutputStream os) throws IOException {
int i = 0;
int len = S.length ();
while (true) {
while (i < Len && S.charat (i) <= ")
i++;
if (i = = len)
Break
int tri = (decode (S.charat (i)) << 18)
+ (Decode (S.charat (i + 1)) << 12)
+ (Decode (S.charat (i + 2)) << 6)
+ (Decode (S.charat (i + 3)));
Os.write (Tri >>) & 255);
if (S.charat (i + 2) = = ' = ')
Break
Os.write (Tri >> 8) & 255);
if (S.charat (i + 3) = = ' = ')
Break
Os.write (Tri & 255);
i + = 4;
}
}
}
Android BASE64 Encryption