Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Base64编码和解码咨询 #3520

Closed
reixuemin opened this issue Mar 19, 2024 · 4 comments
Closed

Base64编码和解码咨询 #3520

reixuemin opened this issue Mar 19, 2024 · 4 comments
Labels

Comments

@reixuemin
Copy link

版本情况

JDK版本: java version "1.8.0_401"
hutool版本: 5.8.25(请确保最新尝试是否还有问题)

问题描述(包括截图)

  1. 复现代码
    image

就是如果编码后的数据再加一个字符,也能解码成功,这个是BUG还是说是Base64就是这样的?

@looly
Copy link
Member

looly commented Mar 19, 2024

image

做了一些兼容。

@looly looly closed this as completed Mar 19, 2024
@looly looly added the question label Mar 19, 2024
@reixuemin
Copy link
Author

这是我用最新的版本跑出来的结果,它没有走你截图的else部分

@changhr2013
Copy link
Contributor

mark 一下,有空展开讲讲原理 😂,最近求知的同学好多。

如果你仅仅是想知道答案的话,你可以认为你添加的字母 s(指代 6 个比特) 因为不满足 Base64 要求的最小置换单元长度(8 个比特),被 hutool 库丢弃了,至于是丢弃还是报错,这其实跟库的解码行为有关,看库是倾向于尽量解码出更多的内容,还是库要对内容做严格的合法性校验。

@looly looly reopened this Mar 20, 2024
@looly
Copy link
Member

looly commented Mar 20, 2024

@changhr2013 @reixuemin 解码逻辑大概是解析固定位数,的整数倍,然后多余的字符忽略掉了。

Hutool的解码相对宽松,最终目标是“尽可能”解析出Base64内容。

举个例子,加入给定内容中有Base64和非Base64混合内容,通过宽松方式解码,就会尽可能的找出被解码的内容。

final String str ="我是不需要解码的内容5Lym5a625piv5LiA5Liq6Z2e5bi46ZW/55qE5a2X56ym5LiyNjY我是不需要解码的内容";
// 伦家是一个非常长的字符串66
Base64.decodeStr(str);

你会发现前面和后面的内容都会被丢弃,重要的逻辑在这里:

image

如果你需要严格的解码,考虑使用java.util.Base64.getDecoder().decode(in)

@looly looly closed this as completed Mar 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants