php - 有没有一种可靠的方法来检测 php 中字符串中的 base64 编码?

标签 php json base64 detection

<分区>

我目前正在一个网站上工作,我的数据库中存储了混合值,我想找到一个解决方案来检测字符串是否进行 base64 加密。到目前为止,我在这篇文章 ( Detect base64 encoding in PHP? ) 上的 Abhinav bhardwaj 的帮助下想出了这段代码:

function IsBase64($s)
{
    // Check if there are valid base64 characters
    if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s)) return false;
    // Decode the string in strict mode and check the results
    $decoded = base64_decode($s, true);
    if(false === $decoded) return false;
    // if string returned contains not printable chars
    if (0 < preg_match('/((?![[:graph:]])(?!\s)(?!\p{L}))./', $decoded, $matched)) return false;
    // Encode the string again
    if(base64_encode($decoded) != $s) return false;
    return true;
}

它只工作一半,例如 1234、7000、reno 和其他 4 字母和数字输入等值解析为真,即使它们不是......现在我的问题:是否有任何可靠的方法进行 base64 检测或我是否必须保留未编码和编码表的列表并将它们区别对待?

我的计划是最终将数据(其中一些需要解密,一些不需要)合并到一个 php 结果对象中,并将其作为 JSON 文本返回。

非常感谢对此的任何帮助!

先谢谢你!

编辑:在 Yoshi 的回答之后,我想将我的结论放在首位,以供其他正在寻找一种简单的解决方案来编码/解码特定数据的人使用:

I think the best way would rather be, to keep the encoded data under a specific key in the db and look out in the query dataset result if this specific key is contained to keep track of the content that needs to be decrypted...

仅供引用:我已经针对此行为更新了我的网站,我不得不承认它非常有效!

最佳答案

我将发布 Yoshi 的评论作为最终结论:

I think you're out of luck. The false positives you mention, still are valid base64 encodings. You'd need to judge whether the decoded version makes any sense, but that will probably be a never ending story, and ultimately would probably also result in false positives. – Yoshi

关于php - 有没有一种可靠的方法来检测 php 中字符串中的 base64 编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46946912/

相关文章:

php - 使用 CDBCriteria 进行 Join 查询

java - 使用 JSONPath 迭代大型 JSON 数组

c# - C#和Java的Base64区别

python - base64 编码和解码 a != b 的问题

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

php将某些字段更新到数据库

php - 如何将url存储在数据库中并生成唯一id

json - ElasticSearch,特定字段不返回

c# - 尝试将具有空属性名称的 JSON 转换为 XML 时出现异常

javascript - 有没有办法将背景图像设置为 base64 编码图像?