6

I am receiving binary data in a string. I want to encode that into Base64. Is there any class to do that operation (I want an API).

1
  • What language(s) are you familiar with? Commented Jun 17, 2011 at 11:52

2 Answers 2

3

CryptBinaryToString ...if you target to Windows platform

Here is a little sample:

#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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

this is windows only answer
-1

Here is the code snippets based on @ruslan-garipov 's answer and msdn. Add To/From methods and some 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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.