如下代码:public class t {

private static String x = "sending...";

// 编码
public static String encode(byte[] bstr) {
sun.misc.BASE64Encoder encode = new sun.misc.BASE64Encoder();
String s = encode.encodeBuffer(bstr);
return s;
} // 解码
public static byte[] decode(String str) {
byte[] bt = null;
try {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
bt = decoder.decodeBuffer(str);
} catch (IOException e) {
e.printStackTrace();
}
return bt;
}

public static void main(String args[]) throws UnsupportedEncodingException
{
//System.out.println("加密前:"+new String(x.getBytes()));
System.out.println("加密前:"+x.getBytes());
String a = new BASE64Encoder().encode(x.getBytes());
System.out.println("加密后:"+a);
//System.out.println("解密后:"+new String(t.decode(a)));
System.out.println("解密后:"+t.decode(a)); }

}
为什么加密前的字节数组和解密后的字节数组不一致?

解决方案 »

  1.   


    public String setBase64(String sValue){//Base64加密
    String str;
    BASE64Encoder base=new BASE64Encoder();
    if(sValue==null){
    str=null;
    }else{
    str=base.encode(sValue.getBytes());
    }
    return str;
    }
    public String getBase64(String str){//Base64解密
    String sValue="";
    if(str==null){
    sValue=null;
    }else{
    BASE64Decoder base=new BASE64Decoder();
    try {
    byte[] b=base.decodeBuffer(str);
    sValue=new String(b);
    } catch (IOException e) {

    }
    }
    return sValue;
    }
    你试试这个吧   呵呵 
      

  2.   

    System.out.println("解密后:"+t.decode(a));
    这里返回的是一个数组用new String(t.decode(a));就对了
      

  3.   

    你打印的只是 System.out.println("加密前:"+x.getBytes());这个数组的toString而已,
    解密前后当然是两个不同地址的byte[],打印的结果当然不一样。你应该是打印new String(x.getBytes());
    和new String(t.decode(a)),这个才是里面的内容