Windows API base64编码/解码

Windows API base64 encode/decod

本文关键字:解码 编码 base64 API Windows      更新时间:2023-10-16

我想base64一个大文件(500MB)

我使用此代码,但对大文件不起作用

i测试cryptStringTobiniary,但它不起作用

我该怎么办???

问题显然是没有足够的内存来存储500兆字节的字符串在32位应用程序中。

该链接提到了一个解决方案,该链接将数据写入字符串。假设代码正常工作,则将其调整为写入文件流并不难。

#include <windows.h>
#include <fstream>
static const wchar_t *Base64Digits = L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int Base64Encode(const BYTE* pSrc, int nLenSrc, std::wostream& pDstStrm, int nLenDst)
{
    wchar_t pDst[4];
    int nLenOut = 0;
    while (nLenSrc > 0) {
        if (nLenDst < 4) return(0); 
        int len = 0;
        BYTE s1 = pSrc[len++];
        BYTE s2 = (nLenSrc > 1) ? pSrc[len++] : 0;
        BYTE s3 = (nLenSrc > 2) ? pSrc[len++] : 0;
        pSrc += len;
        nLenSrc -= len;
        //------------------ lookup the right digits for output
        pDst[0] = Base64Digits[(s1 >> 2) & 0x3F];
        pDst[1] = Base64Digits[(((s1 & 0x3) << 4) | ((s2 >> 4) & 0xF)) & 0x3F];
        pDst[2] = Base64Digits[(((s2 & 0xF) << 2) | ((s3 >> 6) & 0x3)) & 0x3F];
        pDst[3] = Base64Digits[s3 & 0x3F];
        //--------- end of input handling
        if (len < 3) {  // less than 24 src bits encoded, pad with '='
            pDst[3] = L'=';
            if (len == 1)
                pDst[2] = L'=';
        }
        nLenOut += 4;
        // write the data to a file
        pDstStrm.write(pDst,4);
        nLenDst -= 4;
    }
    if (nLenDst > 0) *pDst = 0;
    return (nLenOut);
}

所做的唯一更改是将4个字节写入宽流,而不是将数据附加到字符串

这是一个示例调用:

int main()
{
    std::wofstream ofs(L"testfile.out");
    Base64Encode((BYTE*)"This is a test", strlen("This is a test"), ofs, 1000);
}

以上产生一个用base64字符串VGhpcyBpcyBhIHRlc3Q=的文件,该文件在解码时会产生This is a test

请注意,参数是std::wostream,这意味着任何宽的输出流类(例如std::wostringstream)也可以工作。