来自Oreilly 1、Encoder // Copyright (C) 1999-2001 by Jason Hunter <jhunter_AT_acm_DOT_org>. // All rights reserved. Use of this class is limited. // Please see the LICENSE for more information.package com.oreilly.servlet;import java.io.*;/** * A class to encode Base64 streams and strings. * See RFC 1521 section 5.2 for details of the Base64 algorithm. * <p> * This class can be used for encoding strings: * <blockquote><pre> * String unencoded = "webmaster:try2gueSS"; * String encoded = Base64Encoder.encode(unencoded); * </pre></blockquote> * or for encoding streams: * <blockquote><pre> * OutputStream out = new Base64Encoder(System.out); * </pre></blockquote> * * @author <b>Jason Hunter</b>, Copyright © 2000 * @version 1.1, 2000/11/17, fixed bug with sign bit for char values * @version 1.0, 2000/06/11 */ public class Base64Encoder extends FilterOutputStream { private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private int charCount; private int carryOver; /** * Constructs a new Base64 encoder that writes output to the given * OutputStream. * * @param out the output stream */ public Base64Encoder(OutputStream out) { super(out); } /** * Writes the given byte to the output stream in an encoded form. * * @exception IOException if an I/O error occurs */ public void write(int b) throws IOException { // Take 24-bits from three octets, translate into four encoded chars // Break lines at 76 chars // If necessary, pad with 0 bits on the right at the end // Use = signs as padding at the end to ensure encodedLength % 4 == 0 // Remove the sign bit, // thanks to Christian Schweingruber <[email protected]> if (b < 0) { b += 256; } // First byte use first six bits, save last two bits if (charCount % 3 == 0) { int lookup = b >> 2; carryOver = b & 3; // last two bits out.write(chars[lookup]); } // Second byte use previous two bits and first four new bits, // save last four bits else if (charCount % 3 == 1) { int lookup = ((carryOver << 4) + (b >> 4)) & 63; carryOver = b & 15; // last four bits out.write(chars[lookup]); } // Third byte use previous four bits and first two new bits, // then use last six new bits else if (charCount % 3 == 2) { int lookup = ((carryOver << 2) + (b >> 6)) & 63; out.write(chars[lookup]); lookup = b & 63; // last six bits out.write(chars[lookup]); carryOver = 0; } charCount++; // Add newline every 76 output chars (that's 57 input chars) if (charCount % 57 == 0) { out.write('\n'); } } /** * Writes the given byte array to the output stream in an * encoded form. * * @param b the data to be written * @param off the start offset of the data * @param len the length of the data * @exception IOException if an I/O error occurs */ public void write(byte[] b, int off, int len) throws IOException { // This could of course be optimized for (int i = 0; i < len; i++) { write(b[off + i]); } } /** * Closes the stream, this MUST be called to ensure proper padding is * written to the end of the output stream. * * @exception IOException if an I/O error occurs */ public void close() throws IOException { // Handle leftover bytes if (charCount % 3 == 1) { // one leftover int lookup = (carryOver << 4) & 63; out.write(chars[lookup]); out.write('='); out.write('='); } else if (charCount % 3 == 2) { // two leftovers int lookup = (carryOver << 2) & 63; out.write(chars[lookup]); out.write('='); } super.close(); } /** * Returns the encoded form of the given unencoded string. * * @param unencoded the string to encode * @return the encoded form of the unencoded string */ public static String encode(String unencoded) { ByteArrayOutputStream out = new ByteArrayOutputStream((int) (unencoded.length() * 1.37)); Base64Encoder encodedOut = new Base64Encoder(out);
byte[] bytes = null; try { bytes = unencoded.getBytes("8859_1"); } catch (UnsupportedEncodingException ignored) { } try { encodedOut.write(bytes); encodedOut.close(); return out.toString("8859_1"); } catch (IOException ignored) { return null; } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println( "Usage: java com.oreilly.servlet.Base64Encoder fileToEncode"); } Base64Encoder encoder = null; BufferedInputStream in = null; try { encoder = new Base64Encoder(System.out); in = new BufferedInputStream(new FileInputStream(args[0])); byte[] buf = new byte[4 * 1024]; // 4K buffer int bytesRead; while ((bytesRead = in.read(buf)) != -1) { encoder.write(buf, 0, bytesRead); } } finally { if (in != null) in.close(); if (encoder != null) encoder.close(); } } }
2、Decoder // Copyright (C) 1999-2001 by Jason Hunter <jhunter_AT_acm_DOT_org>. // All rights reserved. Use of this class is limited. // Please see the LICENSE for more information.package com.oreilly.servlet;import java.io.*;/** * A class to decode Base64 streams and strings. * See RFC 1521 section 5.2 for details of the Base64 algorithm. * <p> * This class can be used for decoding strings: * <blockquote><pre> * String encoded = "d2VibWFzdGVyOnRyeTJndWVTUw"; * String decoded = Base64Decoder.decode(encoded); * </pre></blockquote> * or for decoding streams: * <blockquote><pre> * InputStream in = new Base64Decoder(System.in); * </pre></blockquote> * * @author <b>Jason Hunter</b>, Copyright © 2000 * @version 1.0, 2000/06/11 */ public class Base64Decoder extends FilterInputStream { private static final char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; // A mapping between char values and six-bit integers private static final int[] ints = new int[128]; static { for (int i = 0; i < 64; i++) { ints[chars[i]] = i; } } private int charCount; private int carryOver; /** * Constructs a new Base64 decoder that reads input from the given * InputStream. * * @param in the input stream */ public Base64Decoder(InputStream in) { super(in); } /** * Returns the next decoded character from the stream, or -1 if * end of stream was reached. * * @return the decoded character, or -1 if the end of the * input stream is reached * @exception IOException if an I/O error occurs */ public int read() throws IOException { // Read the next non-whitespace character int x; do { x = in.read(); if (x == -1) { return -1; } } while (Character.isWhitespace((char)x)); charCount++; // The '=' sign is just padding if (x == '=') { return -1; // effective end of stream } // Convert from raw form to 6-bit form x = ints[x]; // Calculate which character we're decoding now int mode = (charCount - 1) % 4; // First char save all six bits, go for another if (mode == 0) { carryOver = x & 63; return read(); } // Second char use previous six bits and first two new bits, // save last four bits else if (mode == 1) { int decoded = ((carryOver << 2) + (x >> 4)) & 255; carryOver = x & 15; return decoded; } // Third char use previous four bits and first four new bits, // save last two bits else if (mode == 2) { int decoded = ((carryOver << 4) + (x >> 2)) & 255; carryOver = x & 3; return decoded; } // Fourth char use previous two bits and all six new bits else if (mode == 3) { int decoded = ((carryOver << 6) + x) & 255; return decoded; } return -1; // can't actually reach this line } /** * Reads decoded data into an array of bytes and returns the actual * number of bytes read, or -1 if end of stream was reached. * * @param buf the buffer into which the data is read * @param off the start offset of the data * @param len the maximum number of bytes to read * @return the actual number of bytes read, or -1 if the end of the * input stream is reached * @exception IOException if an I/O error occurs */ public int read(byte[] b, int off, int len) throws IOException { // This could of course be optimized int i; for (i = 0; i < len; i++) { int x = read(); if (x == -1 && i == 0) { // an immediate -1 returns -1 return -1; } else if (x == -1) { // a later -1 returns the chars read so far break; } b[off + i] = (byte) x; } return i; } /** * Returns the decoded form of the given encoded string. * * @param encoded the string to decode * @return the decoded form of the encoded string */ public static String decode(String encoded) { byte[] bytes = null; try { bytes = encoded.getBytes("8859_1"); } catch (UnsupportedEncodingException ignored) { } Base64Decoder in = new Base64Decoder( new ByteArrayInputStream(bytes));
ByteArrayOutputStream out = new ByteArrayOutputStream((int) (bytes.length * 0.67)); try { byte[] buf = new byte[4 * 1024]; // 4K buffer int bytesRead; while ((bytesRead = in.read(buf)) != -1) { out.write(buf, 0, bytesRead); } out.close(); return out.toString("8859_1"); } catch (IOException ignored) { return null; } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Base64Decoder fileToDecode"); } Base64Decoder decoder = null; try { decoder = new Base64Decoder( new BufferedInputStream( new FileInputStream(args[0]))); byte[] buf = new byte[4 * 1024]; // 4K buffer int bytesRead; while ((bytesRead = decoder.read(buf)) != -1) { System.out.write(buf, 0, bytesRead); } } finally { if (decoder != null) decoder.close(); } } }
或者 java mail 里有 encode decode
{
public BASE64()
{
}
public static void main(String arg[])
{
String aa="abc";
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder ();
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder ();
String encode222222;
encode222222=encoder.encode(aa.getBytes());
System.out.println("将 “"+aa+"” 通过Base64编码后的字符是星号中间的内容****"+encode222222+"****");
try
{
int length=decoder.decodeBuffer(encode222222).length;
System.out.println(length);
byte[] xxx=decoder.decodeBuffer(encode222222);
for (int i=0;i<aa.length();i++)
System.out.println((int)aa.charAt(i));
for (int i=0;i<length;i++)
{
String dddd=new String(xxx);
System.out.println(dddd);
System.out.println(xxx[i]);
Byte bb=null;
System.out.println(bb.toString(xxx[i]));
System.out.println("zuihou"+bb.toString(xxx[length-1]));
System.out.println(i);
}
}
catch(Exception e)
{ }
//String aa2=decoder();
}
}
================================================================CSDN 论坛助手 Ver 1.0 B0402提供下载。 改进了很多,功能完备!★ 浏览帖子速度极快![建议系统使用ie5.5以上]。 ★ 多种帖子实现界面。
★ 保存帖子到本地[html格式]★ 监视您关注帖子的回复更新。
★ 可以直接发贴、回复帖子★ 采用XML接口,可以一次性显示4页帖子,同时支持自定义每次显示帖子数量。可以浏览历史记录!
★ 支持在线检测程序升级情况,可及时获得程序更新的信息。★★ 签名 ●
可以在您的每个帖子的后面自动加上一个自己设计的签名哟。Http://www.ChinaOK.net/csdn/csdn.zip
Http://www.ChinaOK.net/csdn/csdn.rar
Http://www.ChinaOK.net/csdn/csdn.exe [自解压]
public static void main(String[] args){
if(args.length==0){
new Base64Form().show();
}else if(args.length==2){
make(args);
}else{
usage();
}
}
private static void usage(){
System.out.println("usage: ");
System.out.println(" \t java cong.base64.Base64 [<-g|-d> <string>]") ;
}
private static void make(String[] args){
if(args[0].equals("-g")){
System.out.println("after encode is " + Utils.encode(args[1]));
}else if(args[0].equals("-d")){
System.out.println("before encode is " + Utils.decode(args[1]));
}else{
usage();
}
}
}
class Utils{
public static String encode(String arg){
BASE64Encoder en = new BASE64Encoder();
return en.encode(arg.getBytes());
}
public static String decode(String arg){
BASE64Decoder de = new BASE64Decoder();
try{
byte[] b= de.decodeBuffer(arg);
for(int i=0;i<b.length; i++){
System.out.print(Integer.toHexString(b[i]));
}
return new String(b);
}catch(Exception e){
return e.toString();
}
}
}
1、Encoder
// Copyright (C) 1999-2001 by Jason Hunter <jhunter_AT_acm_DOT_org>.
// All rights reserved. Use of this class is limited.
// Please see the LICENSE for more information.package com.oreilly.servlet;import java.io.*;/**
* A class to encode Base64 streams and strings.
* See RFC 1521 section 5.2 for details of the Base64 algorithm.
* <p>
* This class can be used for encoding strings:
* <blockquote><pre>
* String unencoded = "webmaster:try2gueSS";
* String encoded = Base64Encoder.encode(unencoded);
* </pre></blockquote>
* or for encoding streams:
* <blockquote><pre>
* OutputStream out = new Base64Encoder(System.out);
* </pre></blockquote>
*
* @author <b>Jason Hunter</b>, Copyright © 2000
* @version 1.1, 2000/11/17, fixed bug with sign bit for char values
* @version 1.0, 2000/06/11
*/
public class Base64Encoder extends FilterOutputStream { private static final char[] chars = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
}; private int charCount;
private int carryOver; /**
* Constructs a new Base64 encoder that writes output to the given
* OutputStream.
*
* @param out the output stream
*/
public Base64Encoder(OutputStream out) {
super(out);
} /**
* Writes the given byte to the output stream in an encoded form.
*
* @exception IOException if an I/O error occurs
*/
public void write(int b) throws IOException {
// Take 24-bits from three octets, translate into four encoded chars
// Break lines at 76 chars
// If necessary, pad with 0 bits on the right at the end
// Use = signs as padding at the end to ensure encodedLength % 4 == 0 // Remove the sign bit,
// thanks to Christian Schweingruber <[email protected]>
if (b < 0) {
b += 256;
} // First byte use first six bits, save last two bits
if (charCount % 3 == 0) {
int lookup = b >> 2;
carryOver = b & 3; // last two bits
out.write(chars[lookup]);
}
// Second byte use previous two bits and first four new bits,
// save last four bits
else if (charCount % 3 == 1) {
int lookup = ((carryOver << 4) + (b >> 4)) & 63;
carryOver = b & 15; // last four bits
out.write(chars[lookup]);
}
// Third byte use previous four bits and first two new bits,
// then use last six new bits
else if (charCount % 3 == 2) {
int lookup = ((carryOver << 2) + (b >> 6)) & 63;
out.write(chars[lookup]);
lookup = b & 63; // last six bits
out.write(chars[lookup]);
carryOver = 0;
}
charCount++; // Add newline every 76 output chars (that's 57 input chars)
if (charCount % 57 == 0) {
out.write('\n');
}
} /**
* Writes the given byte array to the output stream in an
* encoded form.
*
* @param b the data to be written
* @param off the start offset of the data
* @param len the length of the data
* @exception IOException if an I/O error occurs
*/
public void write(byte[] b, int off, int len) throws IOException {
// This could of course be optimized
for (int i = 0; i < len; i++) {
write(b[off + i]);
}
} /**
* Closes the stream, this MUST be called to ensure proper padding is
* written to the end of the output stream.
*
* @exception IOException if an I/O error occurs
*/
public void close() throws IOException {
// Handle leftover bytes
if (charCount % 3 == 1) { // one leftover
int lookup = (carryOver << 4) & 63;
out.write(chars[lookup]);
out.write('=');
out.write('=');
}
else if (charCount % 3 == 2) { // two leftovers
int lookup = (carryOver << 2) & 63;
out.write(chars[lookup]);
out.write('=');
}
super.close();
} /**
* Returns the encoded form of the given unencoded string.
*
* @param unencoded the string to encode
* @return the encoded form of the unencoded string
*/
public static String encode(String unencoded) {
ByteArrayOutputStream out =
new ByteArrayOutputStream((int) (unencoded.length() * 1.37));
Base64Encoder encodedOut = new Base64Encoder(out);
byte[] bytes = null;
try {
bytes = unencoded.getBytes("8859_1");
}
catch (UnsupportedEncodingException ignored) { } try {
encodedOut.write(bytes);
encodedOut.close(); return out.toString("8859_1");
}
catch (IOException ignored) { return null; }
} public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println(
"Usage: java com.oreilly.servlet.Base64Encoder fileToEncode");
} Base64Encoder encoder = null;
BufferedInputStream in = null;
try {
encoder = new Base64Encoder(System.out);
in = new BufferedInputStream(new FileInputStream(args[0])); byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
encoder.write(buf, 0, bytesRead);
}
}
finally {
if (in != null) in.close();
if (encoder != null) encoder.close();
}
}
}
// Copyright (C) 1999-2001 by Jason Hunter <jhunter_AT_acm_DOT_org>.
// All rights reserved. Use of this class is limited.
// Please see the LICENSE for more information.package com.oreilly.servlet;import java.io.*;/**
* A class to decode Base64 streams and strings.
* See RFC 1521 section 5.2 for details of the Base64 algorithm.
* <p>
* This class can be used for decoding strings:
* <blockquote><pre>
* String encoded = "d2VibWFzdGVyOnRyeTJndWVTUw";
* String decoded = Base64Decoder.decode(encoded);
* </pre></blockquote>
* or for decoding streams:
* <blockquote><pre>
* InputStream in = new Base64Decoder(System.in);
* </pre></blockquote>
*
* @author <b>Jason Hunter</b>, Copyright © 2000
* @version 1.0, 2000/06/11
*/
public class Base64Decoder extends FilterInputStream { private static final char[] chars = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
}; // A mapping between char values and six-bit integers
private static final int[] ints = new int[128];
static {
for (int i = 0; i < 64; i++) {
ints[chars[i]] = i;
}
} private int charCount;
private int carryOver; /**
* Constructs a new Base64 decoder that reads input from the given
* InputStream.
*
* @param in the input stream
*/
public Base64Decoder(InputStream in) {
super(in);
} /**
* Returns the next decoded character from the stream, or -1 if
* end of stream was reached.
*
* @return the decoded character, or -1 if the end of the
* input stream is reached
* @exception IOException if an I/O error occurs
*/
public int read() throws IOException {
// Read the next non-whitespace character
int x;
do {
x = in.read();
if (x == -1) {
return -1;
}
} while (Character.isWhitespace((char)x));
charCount++; // The '=' sign is just padding
if (x == '=') {
return -1; // effective end of stream
} // Convert from raw form to 6-bit form
x = ints[x]; // Calculate which character we're decoding now
int mode = (charCount - 1) % 4; // First char save all six bits, go for another
if (mode == 0) {
carryOver = x & 63;
return read();
}
// Second char use previous six bits and first two new bits,
// save last four bits
else if (mode == 1) {
int decoded = ((carryOver << 2) + (x >> 4)) & 255;
carryOver = x & 15;
return decoded;
}
// Third char use previous four bits and first four new bits,
// save last two bits
else if (mode == 2) {
int decoded = ((carryOver << 4) + (x >> 2)) & 255;
carryOver = x & 3;
return decoded;
}
// Fourth char use previous two bits and all six new bits
else if (mode == 3) {
int decoded = ((carryOver << 6) + x) & 255;
return decoded;
}
return -1; // can't actually reach this line
} /**
* Reads decoded data into an array of bytes and returns the actual
* number of bytes read, or -1 if end of stream was reached.
*
* @param buf the buffer into which the data is read
* @param off the start offset of the data
* @param len the maximum number of bytes to read
* @return the actual number of bytes read, or -1 if the end of the
* input stream is reached
* @exception IOException if an I/O error occurs
*/
public int read(byte[] b, int off, int len) throws IOException {
// This could of course be optimized
int i;
for (i = 0; i < len; i++) {
int x = read();
if (x == -1 && i == 0) { // an immediate -1 returns -1
return -1;
}
else if (x == -1) { // a later -1 returns the chars read so far
break;
}
b[off + i] = (byte) x;
}
return i;
} /**
* Returns the decoded form of the given encoded string.
*
* @param encoded the string to decode
* @return the decoded form of the encoded string
*/
public static String decode(String encoded) {
byte[] bytes = null;
try {
bytes = encoded.getBytes("8859_1");
}
catch (UnsupportedEncodingException ignored) { } Base64Decoder in = new Base64Decoder(
new ByteArrayInputStream(bytes));
ByteArrayOutputStream out =
new ByteArrayOutputStream((int) (bytes.length * 0.67)); try {
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
out.close(); return out.toString("8859_1");
}
catch (IOException ignored) { return null; }
} public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java Base64Decoder fileToDecode");
} Base64Decoder decoder = null;
try {
decoder = new Base64Decoder(
new BufferedInputStream(
new FileInputStream(args[0])));
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = decoder.read(buf)) != -1) {
System.out.write(buf, 0, bytesRead);
}
}
finally {
if (decoder != null) decoder.close();
}
}
}