在Java中解码base64Url

发布于 2024-11-01 05:12:15 字数 762 浏览 3 评论 0原文

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

谈论base64Url -解码


存在 URL 变体的修改后的 Base64,其中不会使用填充“=”,并且标准 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;
}

:返回非常小的字符集,甚至与预期结果都不相似。 有什么想法吗?

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

talks about base64Url - Decode


a modified Base64 for URL variant exists, where no padding '=' will be used, and the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '_'


I created the following 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;
}

it returns a very small set of characters that don't even resemble to the expected results.
any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

Spring初心 2024-11-08 05:12:16

Java8+

import java.util.Base64;


return Base64.getUrlEncoder().encodeToString(bytes);

Java8+

import java.util.Base64;


return Base64.getUrlEncoder().encodeToString(bytes);
孤寂小茶 2024-11-08 05:12:16

Base64 编码自 Java 8 起成为 JDK 的一部分。 URL 安全编码 也支持 java.util.Base64.getUrlEncoder() 和“= " 可以通过另外使用 java.util.Base64.Encoder.withoutPadding() 方法:

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public String encode(String raw) {
    return Base64.getUrlEncoder()
            .withoutPadding()
            .encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}

Base64 encoding is part of the JDK since Java 8. URL safe encoding is also supported with java.util.Base64.getUrlEncoder(), and the "=" padding can be skipped by additionally using the java.util.Base64.Encoder.withoutPadding() method:

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public String encode(String raw) {
    return Base64.getUrlEncoder()
            .withoutPadding()
            .encodeToString(raw.getBytes(StandardCharsets.UTF_8));
}
世态炎凉 2024-11-08 05:12:16

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

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 安全。

With the usage of Base64 from Apache Commons, who can be configured to URL safe, I created the following 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;
}

The constructor Base64(true) makes the decoding URL-safe.

瑶笙 2024-11-08 05:12:16

在Android SDK中,Base64类中有一个专用标志:Base64.URL_SAFE,像这样使用它来解码为字符串:

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

In the Android SDK, there's a dedicated flag in the Base64 class: Base64.URL_SAFE, use it like so to decode to a String:

import android.util.Base64;
byte[] byteData = Base64.decode(body, Base64.URL_SAFE);
str = new String(byteData, "UTF-8");
混吃等死 2024-11-08 05:12:16
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);
}
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);
}
你穿错了嫁妆 2024-11-08 05:12:16

立刻,看起来你的 replace() 是向后的;该方法用第二个字符替换第一个字符的出现,而不是相反。

Right off the bat, it looks like your replace() is backwards; that method replaces the occurrences of the first character with the second, not the other way around.

野鹿林 2024-11-08 05:12:16

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

文档

@ufk's answer works, but you don't actually need to set the urlSafe flag when you're just decoding.

urlSafe is only applied to encode operations. Decoding seamlessly
handles both modes.

Also, there are some static helpers to make it shorter and more explicit:

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

Docs

你在看孤独的风景 2024-11-08 05:12:16

本课程可以帮助:

import android.util.Base64;

public class Encryptor {

    public static String encode(String input) {
        return Base64.encodeToString(input.getBytes(), Base64.URL_SAFE);
    }

    public static String decode(String encoded) {
        return new String(Base64.decode(encoded.getBytes(), Base64.URL_SAFE));
    }
}

This class can help:

import android.util.Base64;

public class Encryptor {

    public static String encode(String input) {
        return Base64.encodeToString(input.getBytes(), Base64.URL_SAFE);
    }

    public static String decode(String encoded) {
        return new String(Base64.decode(encoded.getBytes(), Base64.URL_SAFE));
    }
}
迷途知返 2024-11-08 05:12:16

我知道答案已经存在,但是,如果有人想要...

import java.util.Base64; 

public class Base64BasicEncryptionExample {  

    public static void main(String[] args) {  

       // Getting encoder  
       Base64.Encoder encoder = Base64.getUrlEncoder();  
       // Encoding URL  
       String eStr = encoder.encodeToString
                               ("http://www.javatpoint.com/javatutorial/".getBytes());  
       System.out.println("Encoded URL: "+eStr);  

       // Getting decoder  
       Base64.Decoder decoder = Base64.getUrlDecoder();  
       // Decoding URl  
       String dStr = new String(decoder.decode(eStr));  
       System.out.println("Decoded URL: "+dStr);  
    }  
}  

从以下位置获取帮助: https://www.javatpoint.com/java-base64-encode-decode

I know the answer is already there, but still, if someone wants...

import java.util.Base64; 

public class Base64BasicEncryptionExample {  

    public static void main(String[] args) {  

       // Getting encoder  
       Base64.Encoder encoder = Base64.getUrlEncoder();  
       // Encoding URL  
       String eStr = encoder.encodeToString
                               ("http://www.javatpoint.com/javatutorial/".getBytes());  
       System.out.println("Encoded URL: "+eStr);  

       // Getting decoder  
       Base64.Decoder decoder = Base64.getUrlDecoder();  
       // Decoding URl  
       String dStr = new String(decoder.decode(eStr));  
       System.out.println("Decoded URL: "+dStr);  
    }  
}  

Took help from: https://www.javatpoint.com/java-base64-encode-decode

听,心雨的声音 2024-11-08 05:12:16

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


Base64.getUrlEncoder() already using -, _ instead of +, /.

See:

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


最冷一天 2024-11-08 05:12:16

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

In Java try the method Base64.encodeBase64URLSafeString() from Commons Codec library for encoding.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文