public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key)} /** * BASE64加密 * * @param key * @return * @throws Exception */ public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key)}
在开发的时候遇到个现象。对方用PHP base64_encode() 对字符串进行加米。但我这边是用Java解马。导致出现问题。问题如下:[java] view plain copy
package com.tudou.test
import java.io.IOException
/**
* <p>java base64编码和解码的演示类
* 注:base64编码后通过url传递时,获得时"="会给替换掉,* 处理方式:在编码前将"=","/","+" 替换成别的字符,在解码之前替换回来* </p>
* @author tw 2010-03-01
*
*/
public class TestBase64Net {
/**
* 编马
* @param filecontent
* @return String
*/
public static String encode(byte[] bstr){return new sun.misc.BASE64Encoder().encode(bstr)}
/**
* 解码
* @param filecontent
* @return string
*/
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
}
/**
* @param args
*/
public static void main(String[] args) {
TestBase64Net te = new TestBase64Net()
//PHP 用base64 将union_id=102155_100001_01_01 加米后的字符串为: dW5pb25faWQ9MTAyMTU1XzEwMDAwMV8wMV8wMQ//java 用sun.misc.BASE64Encoder().encode()进行解马,结果为:union_id=102155_100001_01_01乱码0System.out.println(new String(te.decode("dW5pb25faWQ9MTAyMTU1XzEwMDAwMV8wMV8wMQ")))//java 用sun.misc.BASE64Decoder 将union_id=102155_100001_01_01进行加米,结果为:dW5pb25faWQ9MTAyMTU1XzEwMDAwMV8wMV8wMQ==System.out.println(new String(te.encode("union_id=102155_100001_01_01".getBytes())))}
}
经过对比不难发现用php的base64_encode() 方法进行加米,JAVA 不能用sun.misc.BASE64Encoder().encode() 进行解米。那该怎么办?!
可以用apache的commons包 commons-codec-1.7.jar 中的org.apache.commons.codec.binary.Base64 进行解米。
[java] view plain copy
import org.apache.commons.codec.binary.Base64public class TestBase64 {
public static void main(String[] args) {
System.out.println(new String(Base64.decodeBase64("dW5pb25faWQ9MTAyMTU1XzEwMDAwMV8wMV8wMQ".getBytes())))}
}
?
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)