吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1911|回复: 18
收起左侧

[求助] 求助编程实现判断一个字符串是否是base64加密?

[复制链接]
bypasshwid 发表于 2024-11-12 12:45
75吾爱币
请用C++实现一个判断函数,判断一个字符串是否是base64加密过的字符串,如:1234肯定不是被某个字符串加密过,
“MTIzNA==”是被某个字符串BASE64加密过,MTIzNA==是1234的BASE64编码过的,反正就是这个意思。

如BOOL bIsBase64String(string str)或BOOL bIsBase64String(char *str),传入一个参数,判断后,是的话,
返回TRUE,不是的话返回FALSE,谢谢各位大佬。

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| bypasshwid 发表于 2024-11-12 12:59
addwy 发表于 2024-11-12 12:56
#include
#include
#include

用正则表达式这种方法应该是不对的,1234和MTIzNA==这两个字符串,我只是打比方,不是真实的,很明显,这个函数有问题,有漏网之鱼,可能有些字符串符合BASE64格式,但是并不是BASE64加密过的。
zunmx 发表于 2024-11-12 13:04
1. 通过正则只能简单判断是否满足base64的规则,不能判断是否是base64编码。
2. base64编码后的长度一定是4的倍数,虽然后面的等号有时候会省略也能解码,但是这个base64编码并不规范。
3. 尝试解码操作,这个只能看出来是不是字符串被编码了,如果是二进制数据,就不太好分析了,只能看头部的特征了。
4. 如果多重编码,比如说一个字符串经过AES或者RSA加密后在进行Base64编码,那么解密后依然是不可读的。

综上:好像没有什么更加直接的判断方式了,因为我随便写一个八位的字符串,满足base64编码的风格,也是可以解码的,但是并没有什么意义。
xiadengma 发表于 2024-11-12 13:07
[Python] 纯文本查看 复制代码
import base64
import re

def is_base64(s):
    # Step 1: 检查字符串是否符合Base64的字符集格式
    base64_pattern = re.compile(r'^[A-Za-z0-9+/]+={0,2}$')
    
    if not base64_pattern.match(s):
        return False
    
    try:
        # Step 2: 尝试解码并验证
        decoded_data = base64.b64decode(s, validate=True)
        
        # Step 3: 可以根据需求进一步验证解码后的数据,这里暂时返回True表示是Base64编码
        return True
    except (base64.binascii.Error, ValueError):
        # 如果解码失败,则返回False
        return False

# 测试示例
test_strings = [
    "U29tZSB0ZXh0IGVuY29kaW5nIGluIEJhc2U2NA==",  # Base64编码的字符串 (对应 "Some text encoding in Base64")
    "12345==",  # 非Base64编码的字符串
    "QmFzZTY0IGVuY29kaW5n",  # Base64编码的字符串 (对应 "Base64 encoding")
    "VGhpcyBpcyBhbiBpbnZhbGlkIHRleHQ=",  # Base64编码的字符串 (对应 "This is an invalid text"
]

for s in test_strings:
    result = is_base64(s)
    print(f"'{s}' is base64 encoded: {result}")

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
bypasshwid + 1 + 1 老兄看要求,是C++代码。

查看全部评分

asq56747277 发表于 2024-11-12 13:10
尝试进行Base64解码,成功就是编码后的。只能验证格式正确,内容有没有实际意义不好判断

点评

你的意思应该和这个文章中判断方法一样。 https://cloud.tencent.com/developer/information/%E5%A6%82%E4%BD%95%E6%A3%80%E6%9F%A5base64%E6%A0%BC%E5%BC%8F%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%98%AF%E5%90%  详情 回复 发表于 2024-11-12 13:16

免费评分

参与人数 1吾爱币 +1 收起 理由
董督秀 + 1 这个才是正解!

查看全部评分

 楼主| bypasshwid 发表于 2024-11-12 13:16
asq56747277 发表于 2024-11-12 13:10
尝试进行Base64解码,成功就是编码后的。只能验证格式正确,内容有没有实际意义不好判断

你的意思应该和这个文章中判断方法一样。
https://cloud.tencent.com/develo ... 9%E6%95%88%EF%BC%9F
xwei2017 发表于 2024-11-12 13:35
#include <string>
#include <cctype>

bool isBase64(const std::string& str) {
    if (str.empty()) {
        return false;
    } else {
        size_t len = str.length();
        if (len % 4 != 0) {
            return false;
        }

        for (char c : str) {
            if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
                (c >= '0' && c <= '9') || c == '+' || c == '/' || c == '=') {
                continue;
            } else {
                return false;
            }
        }
        return true;
    }
}
xwei2017 发表于 2024-11-12 13:41
#include <string>
#include <cctype>

bool isBase64(const std::string& str) {
    // Check for empty or null input
    if (str.empty()) return false;

    size_t len = str.length();
    bool hasNonAlphaNum = false;
    int numPaddedChars = 0;

    for (char c : str) {
        switch (c) {
            case '=': { // padding character, allowed only at the end
                if (!isBase64Padding(str, len)) return false;
                break;
            }
            case '+': case '/': case '=':
                hasNonAlphaNum = true; // allow these special chars
                continue;

            default:
                if (std::iscntrl(c) || c < 'A' || c > 'Z') {
                    // non-alphanumeric char, not allowed in base64
                    return false;
                }
        }

        numPaddedChars += (c == '=');
    }

    // Check for correct padding at the end of the string
    if (!isBase64Padding(str, len)) return false;

    return !hasNonAlphaNum && (len % 4 == 0 || numPaddedChars > 0);
}

bool isBase64Padding(const std::string& str, size_t len) {
    // Check for correct padding at the end of the string
    if (len < 3) return false; // too short to be a valid base64-encoded string

    char lastChar = str[len - 1];
    char secondLastChar = str[len - 2];

    switch (lastChar) {
        case '=':
            return true;
        default: break;

        case 'A': case 'B':
            if (secondLastChar == '=') return false; // not a valid padding
            break;
        case 'C': case 'D':
            if (secondLastChar != '=') return false; // not a valid padding
            break;
    }

    return false;
}
boy666 发表于 2024-11-12 13:55

#include <iostream>
#include <string>
#include <cctype>
#include <vector>

using namespace std;

bool bIsBase64String(const string &str) {
    // 检查长度是否为4的倍数
    if (str.length() % 4 != 0) {
        return false;
    }

    // 检查字符是否符合Base64编码标准
    for (size_t i = 0; i < str.length(); ++i) {
        char c = str[i];
        if (!isalnum(c) && c != '+' && c != '/' && c != '=') {
            return false;
        }
    }

    // 检查填充字符规则:最多允许2个'='且只能出现在字符串末尾
    size_t padding = 0;
    if (str.length() >= 2 && str[str.length() - 1] == '=') {
        padding++;
        if (str[str.length() - 2] == '=') {
            padding++;
        }
    }

    return padding <= 2;
}

string Base64Decode(const string &encoded) {
    const string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    vector<int> decoding_table(256, -1);
    for (int i = 0; i < 64; i++) {
        decoding_table[base64_chars[i]] = i;
    }

    string decoded;
    int val = 0, valb = -8;
    for (char c : encoded) {
        if (decoding_table[c] == -1) break;
        val = (val << 6) + decoding_table[c];
        valb += 6;
        if (valb >= 0) {
            decoded.push_back(char((val >> valb) & 0xFF));
            valb -= 8;
        }
    }
    return decoded;
}

int main() {
    string testStr = "MTIzNA=="; // 示例Base64字符串
    if (bIsBase64String(testStr)) {
        string decodedStr = Base64Decode(testStr);
        cout << "是\"" << decodedStr << "\"的Base64编码" << endl;
        return true;
    } else {
        cout << "不是Base64编码的字符串" << endl;
        return false;
    }
    }
geesehoward 发表于 2024-11-12 14:15
base64不是加密,是编码,而解码也不是解密,根本不存在失败的可能。任何字符串都能base64编码。base64编码和网址中的encodeUrl的意义差不多,避免乱码,把数据转换为标准字符串。
所以,根本不可能判断一个字符串是不是base64的,想判断,只能在元数据上加校验,比如元数据后面跟上MD5,解码后把后32位拿出来,对前面数据进行MD5运算,看看MD5是否一致。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-9-5 11:38

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表