Base64 string from JWT to json

问题: When I try to parse header from jwt as base64 to string then the output is : {"alg":"RS256","typ":"JWT","kid":"1234" without last bracket, but when I decode the...

问题:

When I try to parse header from jwt as base64 to string then the output is :

{"alg":"RS256","typ":"JWT","kid":"1234"

without last bracket, but when I decode the same base64 string for example here: https://www.base64decode.org/ then the json has correct format.

function that I use:

   public void test() {
            String encodedToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ";
            System.out.println(new String(DatatypeConverter.parseBase64Binary(encodedToken)));
        }

What can be wrong?

EDIT: Java 7 is mandatory.


回答1:

Try to encode {"alg":"RS256","typ":"JWT","kid":"1234"} in base64

You will see eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ==

== - is a padding

I think that problem is DatatypeConverter.parseBase64Binary use representation of xsd:base64Binary (RFC 2045). But in RFC 2045 padding is mandatory.

You can use this way (java.util.Base64):

public void test() {
    String encodedToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ";
    System.out.println(new String(Base64.getDecoder().decode(encodedToken.getBytes())));
}

java.util.Base64 uses RFC 4648 (padding is optional).


回答2:

and welcome on StackOverflow. According to this answer on Github, DatatypeConverter.parseBase64Binary() has some bugs and doesn't output the correct decoded string.

If you're using Java 8 or higher you can decode this way:

String base64 = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjEyMzQifQ";
byte[] temp = Base64.getDecoder().decode(base64.getBytes());

System.out.println(new String(temp));

importing class java.util.Base64

  • 发表于 2019-03-14 19:33
  • 阅读 ( 270 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除