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

Is there a bulletproof way to detect base64 encoding in a string in php?

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

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 结果对象中,然后 return 它作为 JSON文字。

非常感谢任何帮助!

在此先感谢您!

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

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...

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

base64编码的字符串基本上是(A-Z),(a-z),(0-9)用=填充到mod4.So,任何4的倍数的字母组合都是有效的base64.

function IsBase64($str) {
    if (strlen($str) % 4 == 0) {
        return true;
    } else {
        return false;
    }
}

我将postYoshi的评论作为最终结论:

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

我找到了一个完美的函数,它检查一个字符串是否有效 base64:

Returns 布尔值真或假

function is_base64($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;

    // Encode the string again
    if(base64_encode($decoded) != $s) return false;

    return true;
}

谢谢 #merlucin, Link