2016-01-24 174 views
1

下面的Java代码:Base64的Java和PHP

String ss = Base64.encodeBase64URLSafeString(xmlRequest.getBytes()); 
System.out.println(ss); 

产地:

PHJlcXVlc3Q-PG1lcmNoYW50X2lkPjQ2PC9tZXJjaGFudF9pZD48b3JkZXJfaWQ-MzM8L29yZGVyX2lkPjxhbW91bnQ-MzwvYW1vdW50PjxkZXNjcmlwdGlvbj5oZWhlPC9kZXNjcmlwdGlvbj48L3JlcXVlc3Q- 

虽然这PHP代码:

$xml='<request><merchant_id>46</merchant_id><order_id>33</order_id><amount>3</amount><description>hehe</description></request>'; 
$xml_encoded = base64_encode($xml); 

产地: PHJlcXVlc3Q + PG1lcmNoYW50X2lkPjQ2PC9tZXJjaGFudF9pZD48b3JkZXJfaWQ + MzM8L29yZGVyX2lkPjxhbW91bnQ + MzwvYW1vdW50PjxkZXNjcmlwdGlvbj5oZWhlPC9kZXNjcmlwdGl vbj48L3JlcXVlc3Q +

其中之一有-个字符,而另一个有+。差异从哪里来?

+0

请参阅[我的回答](http://stackoverflow.com/a/34976227/2071828) - 当JDK中有工具时,请勿使用神秘的第3部分库。 –

回答

4

请参阅this article了解使用的一些变体。看起来像-用于表示需要安全地包含在网址中,例如作为查询参数。又见Base64源代码:

/** 
* This array is a lookup table that translates 6-bit positive integer index values into their "Base64 Alphabet" 
* equivalents as specified in Table 1 of RFC 2045. 
* 
* Thanks to "commons" project in ws.apache.org for this code. 
* http://svn.apache.org/repos/asf/webservices/commons/trunk/modules/util/ 
*/ 
private static final byte[] STANDARD_ENCODE_TABLE = { 
     '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', '+', '/' 
}; 

/** 
* This is a copy of the STANDARD_ENCODE_TABLE above, but with + and/
* changed to - and _ to make the encoded Base64 results more URL-SAFE. 
* This table is only used when the Base64's mode is set to URL-SAFE. 
*/ 
private static final byte[] URL_SAFE_ENCODE_TABLE = { 
     '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', '-', '_' 
}; 
+1

谢谢你的回答。 –

0

这是因为通过使用Base64.encodeBase64URLSafeString() “网址安全base64变” 取代+/-_

使用URL-二进制数据编码base64算法的安全变体,但不输出输出。网址安全变体发出-_而不是+/个字符。注意:不添加填充。

你可以简单地通过改变+/-_翻译两种格式。

要得到与PHP相同的输出,只需使用Base64.encodeBase64String()即可。

+1

谢谢你的回答。 –

+0

没问题,很高兴帮助! :) – Will

2

基数64是最后两个字符a-zA-Z0-9以及+/

为了使编码的URL安全,我们不能使用/,所以最后两个字符被URL安全变体_-所取代。

如果你使用:

final Base64.Encoder encoder = Base64.getEncoder(); 
encoder.encodeToString(...) 

您将得到输出作为PHP例子一样。

P.S.这是JDK内置的新类java.util.Base64类 - 不需要使用奥术通用库。

+0

谢谢你的回答。 –