convert a string "0cc175b9c0f1b6a831c399e269772661" to Base64 encoding with two type of methods, get different results, why???the program is as following:// Base64.java
package digeststring;import javax.mail.internet.MimeUtility;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;public class Base64 {public static String decodeAsString(String b64string) throws Exception {
return new String(decodeAsByteArray(b64string));
}public static byte[] decodeAsByteArray(String b64string) throws Exception {
InputStream in = MimeUtility.decode(new ByteArrayInputStream(b64string
.getBytes()), "base64");ByteArrayOutputStream out = new ByteArrayOutputStream();while (true) {
int b = in.read();
if (b == -1)
break;
else
out.write(b);
}return out.toByteArray();
}public static String encodeAsString(String plaintext) throws Exception {
return encodeAsString(plaintext.getBytes());
}public static String encodeAsString(byte[] plaindata) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream inStream = new ByteArrayOutputStream();inStream.write(plaindata, 0, plaindata.length);// pad
if ((plaindata.length % 3) == 1) {
inStream.write(0);
inStream.write(0);
} else if ((plaindata.length % 3) == 2) {
inStream.write(0);
}inStream.writeTo(MimeUtility.encode(out, "base64"));
return out.toString();
}
}
// Test.java
package digeststring;
import sun.misc.BASE64Encoder;public class Test {public static void main(String[] args) {
try {
String tes = "0cc175b9c0f1b6a831c399e269772661";
String res = Base64.encodeAsString(tes);
System.out.println(res);
BASE64Encoder be = new BASE64Encoder();
String res1 = be.encode(tes.getBytes());
System.out.println(res1);
Base64 b64 = new Base64();}
catch(Exception ex) {}
}
}
The output results are:MGNjMTc1YjljMGYxYjZhODMxYzM5OWUyNjk3NzI2NjEA
MGNjMTc1YjljMGYxYjZhODMxYzM5OWUyNjk3NzI2NjE=在C#下面得到的也是“MGNjMTc1YjljMGYxYjZhODMxYzM5OWUyNjk3NzI2NjE=”结果,为何会最后一位不一样?

解决方案 »

  1.   

    Its a flushing problem.1 - you shouldn't need to pad the bytes manually. The base64 encode will do it for you
    2 - you needed to flush the output stream returned from the MimeUtils class
    3 - Wrapping around the byte array output stream was unnecessary, and may have caused some problems.The problem was you didn't keep a reference to the OuputStream returned by the MimeUtility class. As such, you couldn't flush it.This should accomplish what you intend:    public static String encodeAsString(byte[] plaindata) throws Exception {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            OutputStream inStream = MimeUtility.encode(out, "base64");
            inStream.write(plaindata, 0, plaindata.length);
            inStream.flush();
            return out.toString();
        }