简体   繁体   English

base64_encode转义与否

[英]base64_encode escaping or not

$token = base64_encode( openssl_random_pseudo_bytes(32));

<input type="hidden" name="csrf_token" value="<?=$token?>">

Do I need to escape the $token on output? 我是否需要在输出中转义$token

转义base64编码数据毫无意义,根据定义,它内部不会有任何控制字符(或引号等)。

Actually, you might . 实际上, 你可能会 The problem lies in the fact that one of the base64 encoding characters , the one with index 62, is actually encoded by PHP as a plus character (+), and that plus might get URL-decoded as a space by the browser when sending it along (or rather, by something between the browser and the server - a proxy, a load balancer, a filter...). 问题在于,其中一个base64编码字符 (索引为62的字符 )实际上是由PHP编码为加号字符(+),并且该优先级可能会在发送时被浏览器的URL解码为空格沿着(或者说,通过浏览器和服务器之间的某种东西 - 代理,负载均衡器,过滤器......)。

Therefore, some data risks being encoded in a form that will then be decoded as a different string (and actually not be decoded at all, since space will break the base64 scheme). 因此, 某些数据可能会以一种形式进行编码,然后将其解码为不同的字符串(实际上根本不进行解码,因为空间会破坏base64方案)。

Both modern Firefox and Chrome correctly encode that + into %2B (I just tested), and the standards seem to dictate that the + must always be encoded and base64 does not need further escaping but the problem arises in some cases (see URLs and plus signs ). 现代Firefox和Chrome都正确编码+到%2B(我刚测试过),标准似乎要求+必须始终编码,而base64不需要进一步转义,但在某些情况下会出现问题(请参阅URL和plus迹象 )。

Rather than risking the token working 99.97% of the time (the 0.03% being the day you needed it the most, as Murphy rules), a simple workaround would be to convert the token to hexadecimal byte representation: 而不是让令牌冒着99.97%的时间工作(0.03%是你最需要它的那天,如墨菲规则),一个简单的解决方法是将令牌转换为十六进制字节表示:

$token = bin2hex(openssl_random_pseudo_bytes(32));

<input type="hidden" name="csrf_token" value="<?=$token?>">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM