在Java中解码base64Url

52

https://web.archive.org/web/20110422225659/https://en.wikipedia.org/wiki/Base64#URL_applications

该链接介绍了base64Url - 解码。


存在一种修改后的Base64变体,称为base64Url,它不使用填充符“=”,并且将标准Base64中的“+”和“/”字符分别替换为“-”和“_”。


我创建了以下函数:

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;
}

它返回了一个非常小的字符集,甚至不像预期结果。


3
不应使用sun.misc.BASE64Decoder,因为它是内部Sun/Oracle代码(不是J2SE的一部分),并且随时可能消失。Apache Commons中的类Base64应该为您提供所需的所有功能。 - Benjamin Muschko
我的问题是如何在Java中正确解码base64url字符串。谢谢,我会尝试使用Apache Commons。 - ufk
@Benjamin,哇,我没想到BASE64Decoder是Sun的类,无论是内部还是其他。我想知道他们为什么要打破自己的命名约定。+1 - Pops
@BenjaminMuschko 可能最好澄清一下,对于那些没有意识到这是您评论中的链接的人来说,它特别是在Apache Commons_Codec_中! :) - Sled
3
应该改为 replace('_','/') - Vishal John
12个回答

0

Base64.getUrlEncoder() 已经使用 -_ 替代了 +/

参见:

java-1.8.0/src.zip!/java/util/Base64.java

java.util.Base64

    /* Returns a Base64.Encoder that encodes using the URL and Filename safe type 
     * base64 encoding scheme.
     * Returns: A Base64 encoder.
     * */


    public static Encoder getUrlEncoder() {
         return Encoder.RFC4648_URLSAFE;
    }

...

    /*
     * It's the lookup table for "URL and Filename safe Base64" as specified in 
     * Table 2 of the RFC 4648, with the '+' and '/' changed to '-' and '_'. This 
     * table is used when BASE64_URL is specified.
     * */

    private static final char[] toBase64URL = {
        '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', '-', '_'
    };

...

    static final Encoder RFC4648_URLSAFE = new Encoder(true, null, -1, true);



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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接