后端生成的URL中含base64参数值,经tomcat重定向后偶发前端无法解密报错
现象最近定位到一个有意思的bug,后端生成的URL中包含base64参数值后,经过tomcat重定向后,偶发出现前端无法解密的现象。
原因
当出现问题时,经排查发现重定向的Location响应头中把+转成了 英文空格,导致解密失败。
重定向时如果特殊字符未经URLEncode转义,则tomcat会把+转换成英文空格。
处理方案
方案1、对Base64参数值进行UrlEncode。推荐
此方案会将所有特殊符号替换成%数字字母格式,如%2B,最后一个字母大小写不敏感。
Java代码:
String plainText = "hello>";
String encodedText = Base64.getEncoder().encodeToString(plainText.getBytes(StandardCharsets.UTF_8));
String urlEncodedText = URLEncoder.encode(url, StandardCharsets.UTF_8.toString());
response.sendRedirect("http://127.0.0.1:8080/test?encode=" + urlEncodedText); //http://127.0.0.1:8080/test?encode=aGVsbG8%2BJavaScript代码:
const encode = 'aGVsbG8%2B'
const decode = atob(decodeURIComponent(encode))
console.log(decode) //hello>方案2、Base64使用UrlEncoder进行加密。需前端配合
基于2006年的RFC规范:RFC4648 URL安全字符串替换(+替换成-,/替换成_),需要前端配合
Java代码:
String plainText = "hello>";
String encodedText = Base64.getUrlEncoder().encodeToString(plainText.getBytes(StandardCharsets.UTF_8));
response.sendRedirect("http://127.0.0.1:8080/test?encode=" + encodedText); //http://127.0.0.1:8080/test?encode=aGVsbG8-JavaScript代码:
//写法1:替换回-为+,_为/,补全=,使用atob()完成base64解密
const encodeText = 'aGVsbG8-'
let encode = encodeText.replace(/-/g, '+')
.replace(/_/g, '/')
.padEnd(encodeText.length + (4 - encodeText.length % 4) % 4, '=');
const result = atob(decodeURIComponent(encode))
console.log(result)
//写法2:使用TextDecoder解密方案3、调整tomcat配置。
不推荐,可自行搜索。
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! 感谢分享,学习下。 喜欢鼓捣这些软件,现在用得少,谢谢分享! 鼓励转贴优秀软件安全工具和文档! 喜欢鼓捣这些软件,现在用得少,谢谢分享! 分享、互助 让互联网精神温暖你我 鼓励转贴优秀软件安全工具和文档! 感谢分享 前排留名,哈哈哈 谢谢楼主提供! 这个好,看起来很实用 感谢分享,下载保存了,貌似很强大 感谢分享 感谢,下载保存了 感谢发布原创作品,程序园因你更精彩 用心讨论,共获提升! 新版吗?好像是停更了吧。 东西不错很实用谢谢分享 这个有用。 感谢分享
页:
[1]
2