如何将二进制字符串转换为base64编码数据

问题描述 投票:0回答:2

我正在接收字符串中的二进制数据。我想将其编码为 Base64。是否有任何类可以执行该操作(我想要一个 API)。

c++ class encoding base64 binary-data
2个回答
4
投票

CryptBinaryToString ...如果您的目标是 Windows 平台

这是一个小样本:

#include <Windows.h>

#pragma comment(lib, "crypt32.lib")

int main()
{
    LPCSTR pszSource = "Man is distinguished, not only by his reason, but ...";
    DWORD nDestinationSize;
    if (CryptBinaryToString(reinterpret_cast<const BYTE*> (pszSource), strlen(pszSource), CRYPT_STRING_BASE64, nullptr, &nDestinationSize))
    {
        LPTSTR pszDestination = static_cast<LPTSTR> (HeapAlloc(GetProcessHeap(), HEAP_NO_SERIALIZE, nDestinationSize * sizeof(TCHAR)));
        if (pszDestination)
        {
            if (CryptBinaryToString(reinterpret_cast<const BYTE*> (pszSource), strlen(pszSource), CRYPT_STRING_BASE64, pszDestination, &nDestinationSize))
            {
                // Succeeded: 'pszDestination' is 'pszSource' encoded to base64.
            }
            HeapFree(GetProcessHeap(), HEAP_NO_SERIALIZE, pszDestination);
        }
    }
    return 0;
}

0
投票

这里是基于 @ruslan-garipov 的答案和 msdn 的代码片段。添加“To/From”方法和一些 RAII。

std::string ToBase64(const BYTE* pBuf, DWORD cbSize)
{
    if (!pBuf || !cbSize) { return {}; }

    DWORD cchWith0{};
    if (!CryptBinaryToStringA(pBuf, cbSize, CRYPT_STRING_BASE64, nullptr, &cchWith0)) { return {}; }

    std::vector<char> base64Str(cchWith0, '\0');
    if (!CryptBinaryToStringA(pBuf, cbSize, CRYPT_STRING_BASE64, &base64Str[0], &cchWith0)) { return {}; }

    return base64Str.data();
}

std::vector<BYTE> FromBase64(const char* szBase64, DWORD cchWith0 = 0)
{
    if (!szBase64) { return {}; }

    cchWith0 = cchWith0 ? cchWith0 : DWORD(strlen(szBase64)) + 1;
    DWORD cbRequired{}, dwSkip{}, dwFlags{};
    if (!CryptStringToBinaryA(szBase64, cchWith0, CRYPT_STRING_BASE64, nullptr, &cbRequired, &dwSkip, &dwFlags)) { return {}; }

    std::vector<BYTE> binaryBuf(cbRequired);
    if (!CryptStringToBinaryA(szBase64, cchWith0, CRYPT_STRING_BASE64, &binaryBuf[0], &cbRequired, &dwSkip, &dwFlags)) { return {}; }

    return binaryBuf;
}
© www.soinside.com 2019 - 2024. All rights reserved.