| Real'sHowTo |
|
|
Custom Search
|
| Real'sHowTo |
|
|
Custom Search
|
Here some alternatives which are maybe easier (and safer) to use.
import javax.mail.internet.MimeUtility;
import java.io.*;
public class Base64Utils {
public static byte[] encode(byte[] b) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream b64os = MimeUtility.encode(baos, "base64");
b64os.write(b);
b64os.close();
return baos.toByteArray();
}
public static byte[] decode(byte[] b) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
InputStream b64is = MimeUtility.decode(bais, "base64");
byte[] tmp = new byte[b.length];
int n = b64is.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return res;
}
public static void main(String[] args) throws Exception {
String test = "realhowto";
byte res1[] = Base64Utils.encode(test.getBytes());
System.out.println(test + " base64 -> " + java.util.Arrays.toString(res1));
System.out.println(new String(res1));
byte res2[] = Base64Utils.decode(res1);
System.out.println("");
System.out.println( java.util.Arrays.toString(res1) + " string --> "
+ new String(res2));
/*
* output
* realhowto base64 ->
* [99, 109, 86, 104, 98, 71, 104, 118, 100, 51, 82, 118]
* cmVhbGhvd3Rv
* [99, 109, 86, 104, 98, 71, 104, 118, 100, 51, 82, 118]
* string --> realhowto
*/
}
}
Download at http://commons.apache.org/codec/
import org.apache.commons.codec.binary.Base64;
public class Codec {
public static void main(String[] args) {
try {
String clearText = "Hello world";
String encodedText;
// Base64
encodedText = new String(Base64.encodeBase64(clearText.getBytes()));
System.out.println("Encoded: " + encodedText);
System.out.println("Decoded:"
+ new String(Base64.decodeBase64(encodedText.getBytes())));
//
// output :
// Encoded: SGVsbG8gd29ybGQ=
// Decoded:Hello world
//
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Written and compiled by Réal Gagnon ©1998-2013
[ home ]