java中的base64url

http://en.wikipedia.org/wiki/Base64#URL_applications

谈论base64Url – 解码


存在修改后的Base64 for URL变体,其中不使用填充’=’,标准Base64的’+’和’/’字符分别替换为’ – ‘和’_’


我创建了以下function:

public static String base64UrlDecode(String input) { String result = null; BASE64Decoder decoder = new BASE64Decoder(); try { result = decoder.decodeBuffer(input.replace('-','+').replace('/','_')).toString(); } catch (IOException e) { System.out.println(e.getMessage()); } return result; } 

它返回一组非常小的字符,甚至与预期的结果不相似。 有任何想法吗?

Java8 +

 import java.util.Base64; return Base64.getUrlEncoder().encodeToString(bytes); 

通过使用Apache Commons的Base64 ,可以配置为URL安全,我创建了以下function:

 import org.apache.commons.codec.binary.Base64; public static String base64UrlDecode(String input) { String result = null; Base64 decoder = new Base64(true); byte[] decodedBytes = decoder.decode(input); result = new String(decodedBytes); return result; } 

构造函数Base64(true)使解码URL安全。

自Java 8以来, Base64编码是JDK的一部分。还支持URL安全编码。

 import java.nio.charset.StandardCharsets; import java.util.Base64; public String encode(String raw) { return Base64.getUrlEncoder() .withoutPadding() .encodeToString(raw.getBytes(StandardCharsets.UTF_8)); } 
 public static byte[] encodeUrlSafe(byte[] data) { byte[] encode = Base64.encode(data); for (int i = 0; i < encode.length; i++) { if (encode[i] == '+') { encode[i] = '-'; } else if (encode[i] == '/') { encode[i] = '_'; } } return encode; } public static byte[] decodeUrlSafe(byte[] data) { byte[] encode = Arrays.copyOf(data, data.length); for (int i = 0; i < encode.length; i++) { if (encode[i] == '-') { encode[i] = '+'; } else if (encode[i] == '_') { encode[i] = '/'; } } return Base64.decode(encode); } 

在Android SDK中, Base64类中有一个专用标志: Base64.URL_SAFE ,使用它来解码为String:

 import android.util.Base64; byte[] byteData = Base64.decode(body, Base64.URL_SAFE); str = new String(byteData, "UTF-8"); 

蝙蝠,看起来你的replace()是倒退; 该方法用第二个字符替换第一个字符的出现,而不是相反。

@ ufk的答案有效,但实际上你不需要在解码时设置urlSafe标志。

urlSafe仅适用于编码操作。 解码无缝地处理两种模式。

此外,还有一些静态帮助程序可以使它更短更明确:

 import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.StringUtils; public static String base64UrlDecode(String input) { StringUtils.newStringUtf8(Base64.decodeBase64(input)); } 

文件

  • newStringUtf8()
  • decodeBase64()

在Java中,尝试使用Commons Codec库中的Base64.encodeBase64URLSafeString()方法进行编码。