开发者

Decode base64Url in Java

开发者 https://www.devze.com 2023-02-24 09:17 出处:网络
https://web.archive.org/web/20110422225659/https://en.wikipedia.org/wiki/Base64#URL_applications talks about base64Url - Decode

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开发者_Python百科 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?


Java8+

import java.util.Base64;


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


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


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.


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


Guava now has Base64 decoding built in.

https://google.github.io/guava/releases/17.0/api/docs/com/google/common/io/BaseEncoding.html


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


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.


@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

  • newStringUtf8()
  • decodeBase64()


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


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

import java.util.Base64; public 

class Base64BasicEncryptionExample {  

    publicstaticvoid 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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号