Base64编码解码类

C++ 图片、文件转base64编码 不要用这个版本https://github.com/hopzebordah/base64encoder/blob/master/encode.cpp有坑,会死在result[i] = '='; 可以用这个版本https://blog.csdn.net/qq_31681017/article/details/93161285亲测好用 #include "stdafx.h" #include <Windows.h> #include <iostream> #include &.. 阅读详情

// Base64.h: interface for the CBase64 class.
/**///////////////////////////////////////////////////////////////////////

#if !defined(AFX_BASE64_H__FD6A25D1_EE0E_11D1_870E_444553540001__INCLUDED_)
#define AFX_BASE64_H__FD6A25D1_EE0E_11D1_870E_444553540001__INCLUDED_

#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000

#include "MIMECode.h"

// CBase64
// An encoding agent that handles Base64
//
class CBase64 : public CMIMECode
...{
public:
    CBase64();
    virtual ~CBase64();

// Override the base class mandatory functions
    virtual int Decode( LPCTSTR szDecoding, LPTSTR szOutput );
    virtual CString Encode( LPCTSTR szEncoding, int nSize );

protected:
    void write_bits( UINT nBits, int nNumBts, LPTSTR szOutput, int& lp );
    UINT read_bits( int nNumBits, int* pBitsRead, int& lp );

    int m_nInputSize;
    int m_nBitsRemaining;
    ULONG m_lBitStorage;
    LPCTSTR m_szInput;

    static int m_nMask[];
    static CString m_sBase64Alphabet;
private:
};

CString Base64String(CString str,CString Charset = "gb2312" );

#endif // !defined(AFX_BASE64_H__FD6A25D1_EE0E_11D1_870E_444553540001__INCLUDED_)






// Base64.cpp: implementation of the CBase64 class.
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Base64.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

// Static Member Initializers
//

// The 7-bit alphabet used to encode binary information
CString CBase64::m_sBase64Alphabet =
_T( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" );

int CBase64::m_nMask[] = { 0, 1, 3, 7, 15, 31, 63, 127, 255 };

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CBase64::CBase64()
{

     m_nInputSize=0;
     m_nBitsRemaining=0;
     m_lBitStorage=0;
}

CBase64::~CBase64()
{
}

CString Base64String(CString str, CString Charset)
{
    //"“From: =?gb2312?B?us7TsQ==?= <hy@ipiinfo.com>”"
    CBase64 code;
    CString strok=code.Encode(str,str.GetLength());
    CString rt;
    rt.Format("=?%s?B?%s==?=",Charset,strok);
  
    return rt;

}


CString CBase64::Encode(LPCTSTR szEncoding, int nSize)
{
    CString sOutput = _T( "" );
    int nNumBits = 6;
    UINT nDigit;
    int lp = 0;

    ASSERT( szEncoding != NULL );
    if( szEncoding == NULL )
        return sOutput;
    m_szInput = szEncoding;
    m_nInputSize = nSize;

    m_nBitsRemaining = 0;
    nDigit = read_bits( nNumBits, &nNumBits, lp );
    while( nNumBits > 0 )
    {
        sOutput += m_sBase64Alphabet[ (int)nDigit ];
        if((sOutput.GetLength()-76) % 78 == 0)
            sOutput+=" ";
        nDigit = read_bits( nNumBits, &nNumBits, lp );
    }
    // Pad with '=' as per RFC 1521
    while( sOutput.GetLength() % 4 != 0 )
    {
        sOutput += '=';
    }
    return sOutput;
}

// The size of the output buffer must not be less than
// 3/4 the size of the input buffer. For simplicity,
// make them the same size.
int CBase64::Decode(LPCTSTR szDecoding, LPTSTR szOutput)
{
    CString sInput;
    int c, lp =0;
    int nDigit;
    int nDecode[ 256 ];

    ASSERT( szDecoding != NULL );
    ASSERT( szOutput != NULL );
    if( szOutput == NULL )
        return 0;
    if( szDecoding == NULL )
        return 0;
    sInput = szDecoding;
    if( sInput.GetLength() == 0 )
        return 0;

    // Build Decode Table
    //
    for( int i = 0; i < 256; i++ )
        nDecode[i] = -2; // Illegal digit
  
    for( i=0; i < 64; i++ )
    {
        nDecode[ m_sBase64Alphabet[ i ] ] = i;
        nDecode[ m_sBase64Alphabet[ i ] | 0x80 ] = i; // Ignore 8th bit
        nDecode[ '=' ] = -1;
        nDecode[ '=' | 0x80 ] = -1; // Ignore MIME padding char
    }

    // Clear the output buffer
    memset( szOutput, 0, sInput.GetLength() + 1 );

    // Decode the Input
    //
    for( lp = 0, i = 0; lp < sInput.GetLength(); lp++ )
    {
        c = sInput[ lp ];
        nDigit = nDecode[ c & 0x7F ];
        if( nDigit < -1 )
        {
            return i;
        }
        else if( nDigit >= 0 )
            // i (index into output) is incremented by write_bits()
            write_bits( nDigit & 0x3F, 6, szOutput, i );
    }  
    return i;
}




UINT CBase64::read_bits(int nNumBits, int * pBitsRead, int& lp)
{
    ULONG lScratch;
    while( ( m_nBitsRemaining < nNumBits ) &&
           ( lp < m_nInputSize ) )
    {
        int c = m_szInput[ lp++ ];
        m_lBitStorage <<= 8;
        m_lBitStorage |= (c & 0xff);
        m_nBitsRemaining += 8;
    }
    if( m_nBitsRemaining < nNumBits )
    {
        lScratch = m_lBitStorage << ( nNumBits - m_nBitsRemaining );
        *pBitsRead = m_nBitsRemaining;
        m_nBitsRemaining = 0;
    }
    else
    {
        lScratch = m_lBitStorage >> ( m_nBitsRemaining - nNumBits );
        *pBitsRead = nNumBits;
        m_nBitsRemaining -= nNumBits;
    }
    return (UINT)lScratch & m_nMask[nNumBits];
}


void CBase64::write_bits(UINT nBits,
                         int nNumBits,
                         LPTSTR szOutput,
                         int& i)
{
    UINT nScratch;

    m_lBitStorage = (m_lBitStorage << nNumBits) | nBits;
    m_nBitsRemaining += nNumBits;
    while( m_nBitsRemaining > 7 )
    {
        nScratch = m_lBitStorage >> (m_nBitsRemaining - 8);
        szOutput[ i++ ] = nScratch & 0xFF;
        m_nBitsRemaining -= 8;
    }
} 

 

(原创)昨天为了测试我的终端,自己写了个模拟服务器,用到BASE64 编解码,已用了GoAhead的代码,发现不支持中文,自己改造一下,解决了问题。现在把代码发上来给大家借鉴。


/*
* base64.c -- Base64 Mime encoding
*
* Copyright (c) GoAhead Software Inc., 1995-2000. All Rights Reserved.
*
* See the file "license.txt" for usage and redistribution license requirements
*
* $Id: base64.c,v 1.1 2005/08/12 06:50:14 archfree Exp $
*/

/******************************** Description *********************************/

/*
* The base64 command encodes and decodes a string in mime base64 format
*/


/******************************** Local Data **********************************/
/*
* Mapping of ANSI chars to base64 Mime encoding alphabet (see below)
*/

#if 0
static char map64[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
#endif
static char map64[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26,
27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1,
-1, -1,-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};

static char alphabet64[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/',
};

/*********************************** Code *************************************/
/*
* Decode a buffer from "string" and into "outbuf"
*/

int websDecode64(char *outbuf, char *string, int outlen)
{
unsigned long shiftbuf;
char *cp, *op;
int c, i, j, shift;

op = outbuf;
*op = '/0';
cp = string;
while (*cp && *cp != '=') {
/*
* Map 4 (6bit) input bytes and store in a single long (shiftbuf)
*/
shiftbuf = 0;
shift = 18;
for (i = 0; i < 4 && *cp && *cp != '='; i++, cp++) {
c = map64[*cp & 0xff];
if (c == -1) {
#if zwhtemp
error(E_L, E_LOG, T("Bad string: %s at %c index %d"), string,
c, i);
#endif
return -1;
}
shiftbuf = shiftbuf | (c << shift);
shift -= 6;
}
/*
* Interpret as 3 normal 8 bit bytes (fill in reverse order).
* Check for potential buffer overflow before filling.
*/
--i;
if ((op + i) >= &outbuf[outlen]) {
//gstrcpy(outbuf, T("String too big"));]
//strcpy(outbuf, T("String too big"));
strcpy(outbuf, "String too big");

return -1;
}
for (j = 0; j < i; j++) {
*op++ = (char) ((shiftbuf >> (8 * (2 - j))) & 0xff);
}
*op = '/0';
}
return 0;
}


/******************************************************************************/
/*
* Encode a buffer from "string" into "outbuf"
*/

void websEncode64(char *outbuf, char *string, int outlen)
{
unsigned long shiftbuf;
char *cp, *op;
int x, i, j, shift;

op = outbuf;
*op = '/0';
cp = string;
while (*cp) {
/*
* Take three characters and create a 24 bit number in shiftbuf
*/
shiftbuf = 0;
for (j = 2; j >= 0 && *cp; j--, cp++) {
shiftbuf |= ((*cp & 0xff) << (j * 8));
}
/*
* Now convert shiftbuf to 4 base64 letters. The i,j magic calculates
* how many letters need to be output.
*/
shift = 18;
for (i = ++j; i < 4 && op < &outbuf[outlen] ; i++) {
x = (shiftbuf >> shift) & 0x3f;
*op++ = alphabet64[(shiftbuf >> shift) & 0x3f];
shift -= 6;
}
/*
* Pad at the end with '='
*/
while (j-- > 0) {
*op++ = '=';
}
*op = '/0';
}
}


=============

// Base64.h: interface for the Base64 class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_BASE64_H__D1CE45BE_2DDD_47A2_9777_CA3BA8A42AE4__INCLUDED_)
#define AFX_BASE64_H__D1CE45BE_2DDD_47A2_9777_CA3BA8A42AE4__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include <afx.h>

class Base64
{
public:

 // 将ANSI字符串转成Base64字符串
 static CString encode(const CString in_str);
 static void encode(LPSTR pIn, DWORD dwInLen, LPSTR pOut, LPDWORD pdwOutLen);
 
 // 将Base64字符串转成ANSI字符串
 static CString decode(const CString in_str);
 static void decode(LPSTR pIn, DWORD dwInLen, LPSTR pOut, LPDWORD pdwOutLen);

 // 将ANSI格式文件转成Base64格式文件
 static BOOL encode(const CString cstrSrc, const CString cstrDes);
 static BOOL encodeMemMap(LPCTSTR fIn, LPCTSTR fOut);

 // 将Base64格式文件转成ANSI格式文件
 static BOOL decode(const CString cstrSrc, const CString cstrDes);
 static BOOL decodeMemMap(LPCTSTR fIn, LPCTSTR fOut);

 static inline PSTR AllocMemBase64(DWORD dwANSILen);
 static inline PSTR AllocMemANSI(DWORD dwBase64Len);
 static inline void FreeMemBase64(PSTR pBase64);
 static inline void FreeMemANSI(PSTR pANSI);
 
protected:
 static inline DWORD CalcANSItoBase64Len(DWORD dwANSILen);
 static inline DWORD CalcBase64toANSILen(DWORD dwBase64Len, const CString strBase64End2 = "");

private:

    // encode table(编码表)
    const static CString _base64_encode_chars;
 
    // decode table(解码表)
    const static char _base64_decode_chars[128];


};


//////////////////////////////////////////////////////////////////////////
// 函数:    DWORD CalcANSItoBase64Len()
// 功能:    计算ANSI字符串转成Base64字符串需要多少内存
// 参数:    dwANSILen ANSI字符串的长度
// 返回值:  DWORD Base64字符串的长度
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
inline DWORD Base64::CalcANSItoBase64Len(DWORD dwANSILen)
{
 return (dwANSILen%3) ? (dwANSILen+3)/3*4 : dwANSILen/3*4;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    DWORD CalcBase64toANSILen()
// 功能:    计算Base64字符串转成ANSI字符串需要多少内存
// 参数:    dwANSILen Base64字符串的长度
//   strBase64End2 Base64字符串结尾的二个字符串
// 返回值:  DWORD ANSI字符串的长度
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
inline DWORD Base64::CalcBase64toANSILen(DWORD dwBase64Len, const CString strBase64End2)
{
 //计算'='出现的次数,
 int count = 0;
 for (int i=0; i<strBase64End2.GetLength(); i++)
  if (strBase64End2[i] == '=')
   count ++;

 DWORD dwANSILen = (dwBase64Len%4) ? (dwBase64Len+4)/4*3 : dwBase64Len/4*3;
 dwANSILen -= count;
 return dwANSILen;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    PSTR AllocMemBase64()
// 功能:    分配Base64字符串所需要的空间,这个内存需要用户手动删除
// 参数:    dwANSILen ANSI字符串的长度
// 返回值:  PSTR Base64内存地址
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
inline PSTR Base64::AllocMemBase64(DWORD dwANSILen)
{
 int len = Base64::CalcANSItoBase64Len(dwANSILen);
 char* pBase64 = new char[len+1];
 ZeroMemory(pBase64, len+1);
 
 return pBase64;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    PSTR AllocMemANSI()
// 功能:    分配Base64字符串所需要的空间,这个内存需要用户手动删除
// 参数:    dwANSILen ANSI字符串的长度
// 返回值:  PSTR Base64内存地址
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
inline PSTR Base64::AllocMemANSI(DWORD dwBase64Len)
{
 int len = Base64::CalcBase64toANSILen(dwBase64Len);
 char* pANSI = new char[len+1];
 ZeroMemory(pANSI, len+1);
 
 return pANSI;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    void FreeMemBase64()
// 功能:    删除用AllocMemBase64分配的内存
// 参数:    pBase64 分配内在的地址
// 返回值:  void
// 日期:    [6/25/2005]
//////////////////////////////////////////////////////////////////////////
inline void Base64::FreeMemBase64(PSTR pBase64)
{
 ASSERT(pBase64);
 delete[] pBase64;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    void FreeMemANSI()
// 功能:    删除用AllocMemANSI分配的内存
// 参数:    pANSI 分配内在的地址
// 返回值:  void
// 日期:    [6/25/2005]
//////////////////////////////////////////////////////////////////////////
inline void Base64::FreeMemANSI(PSTR pANSI)
{
 ASSERT(pANSI);
 delete[] pANSI;
}


#endif // !defined(AFX_BASE64_H__D1CE45BE_2DDD_47A2_9777_CA3BA8A42AE4__INCLUDED_)


// Base64.cpp: implementation of the Base64 class.
//
// 作者:王军
//
// 用途:Base64的编码与解码
//
// 创建日期:2004-06-08

//////////////////////////////////////////////////////////////////////
#include "Base64.h"
#include <windows.h>

// 用于编码的字符
const CString Base64::_base64_encode_chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// 用于解码的字符
const char Base64::_base64_decode_chars[] =
{
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
    52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
    -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
    15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
    -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
    41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1
};


//////////////////////////////////////////////////////////////////////////
// 函数:    CString encode()
// 功能:    将ANSI字符串转成Base64字符串
// 参数:    in_str ANSI字符串
// 返回值:  CString Base64字符串
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
CString Base64::encode(const CString in_str)
{
    CString out_str;
    unsigned char c1, c2, c3;
    int i = 0;
    int len = in_str.GetLength();

    while ( i<len )
    {
        // read the first byte
        c1 = in_str[i++];
        if ( i==len )       // pad with "="
        {
            out_str += _base64_encode_chars[ c1>>2 ];
            out_str += _base64_encode_chars[ (c1&0x3)<<4 ];
            out_str += "==";
            break;
        }

        // read the second byte
        c2 = in_str[i++];
        if ( i==len )       // pad with "="
        {
            out_str += _base64_encode_chars[ c1>>2 ];
            out_str += _base64_encode_chars[ ((c1&0x3)<<4) | ((c2&0xF0)>>4) ];
            out_str += _base64_encode_chars[ (c2&0xF)<<2 ];
            out_str += "=";
            break;
        }

        // read the third byte
        c3 = in_str[i++];
        // convert into four bytes string
        out_str += _base64_encode_chars[ c1>>2 ];
        out_str += _base64_encode_chars[ ((c1&0x3)<<4) | ((c2&0xF0)>>4) ];
        out_str += _base64_encode_chars[ ((c2&0xF)<<2) | ((c3&0xC0)>>6) ];
        out_str += _base64_encode_chars[ c3&0x3F ];
    }

    return out_str;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    CString decode()
// 功能:    将Base64字符串转成ANSI字符串
// 参数:    in_str Base64字符串
// 返回值:  CString ANSI字符串
// 日期:    [6/23/2005]
//////////////////////////////////////////////////////////////////////////
CString Base64::decode(const CString in_str)
{
    CString out_str;
    char c1, c2, c3, c4;
    int i = 0;
    int len = in_str.GetLength();
 
    while ( i<len)
    {
        // read the first byte
        do {
            c1 = _base64_decode_chars[ in_str[i++] ];
        } while ( i<len && c1==-1);

        if ( c1==-1)
            break;

        // read the second byte
        do {
            c2 = _base64_decode_chars[ in_str[i++] ];
        } while ( i<len && c2==-1);

        if ( c2==-1 )
            break;

        // assamble the first byte
        out_str += char( (c1<<2) | ((c2&0x30)>>4) );

        // read the third byte
        do {
            c3 = in_str[i++];
            if ( c3==61 )       // meet with "=", break
                return out_str;
            c3 = _base64_decode_chars[ c3 ];
        } while ( i<len && c3==-1);

        if ( c3==-1 )
            break;

        // assamble the second byte
        out_str += char( ((c2&0XF)<<4) | ((c3&0x3C)>>2) );

        // read the fourth byte
        do {
            c4 = in_str[i++];
            if ( c4==61 )       // meet with "=", break
                return out_str;
            c4 = _base64_decode_chars[ c4 ];
        } while ( i<len && c4==-1 );

        if ( c4==-1 )
            break;

        // assamble the third byte
        out_str += char( ((c3&0x03)<<6) | c4 );
    }

    return out_str;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    void encode()
// 功能:    将ANSI字符串转成Base64字符串
// 参数:    pIn  ANSI字符串
//   dwInLen ANSI字符串的长度
//   pOut 放Base64字符串的内存
//   pdwOutLen Base64字符串的长度
// 返回值:  void
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
void Base64::encode(LPSTR pIn, DWORD dwInLen, LPSTR pOut, LPDWORD pdwOutLen)
{
    unsigned char c1, c2, c3;
    int i = 0, n = 0;
    int len = dwInLen;

    while ( i<len )
    {
        // read the first byte
        c1 = pIn[i++];
        if ( i==len )       // pad with "="
        {
            pOut[n++] = _base64_encode_chars[ c1>>2 ];
            pOut[n++] = _base64_encode_chars[ (c1&0x3)<<4 ];
            pOut[n++] = '=';
            pOut[n++] = '=';
           break;
        }

        // read the second byte
        c2 = pIn[i++];
        if ( i==len )       // pad with "="
        {
            pOut[n++] = _base64_encode_chars[ c1>>2 ];
            pOut[n++] = _base64_encode_chars[ ((c1&0x3)<<4) | ((c2&0xF0)>>4) ];
            pOut[n++] = _base64_encode_chars[ (c2&0xF)<<2 ];
            pOut[n++] = '=';
            break;
        }

        // read the third byte
        c3 = pIn[i++];
        // convert into four bytes string
        pOut[n++] = _base64_encode_chars[ c1>>2 ];
        pOut[n++] = _base64_encode_chars[ ((c1&0x3)<<4) | ((c2&0xF0)>>4) ];
        pOut[n++] = _base64_encode_chars[ ((c2&0xF)<<2) | ((c3&0xC0)>>6) ];
        pOut[n++] = _base64_encode_chars[ c3&0x3F ];
    }
 *pdwOutLen = n;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    void decode()
// 功能:    将Base64字符串转成ANSI字符串
// 参数:    pIn  Base64字符串
//   dwInLen Base64字符串的长度
//   pOut 放ANSI字符串的内存
//   pdwOutLen ANSI字符串的长度
// 返回值:  void
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
void Base64::decode(LPSTR pIn, DWORD dwInLen, LPSTR pOut, LPDWORD pdwOutLen)
{
    char c1, c2, c3, c4;
    int i = 0, n = 0;
    int len = dwInLen;

    while ( i<len)
    {
        // read the first byte
        do {
            c1 = _base64_decode_chars[ pIn[i++] ];
        } while ( i<len && c1==-1);

        if ( c1==-1)
            break;

        // read the second byte
        do {
            c2 = _base64_decode_chars[ pIn[i++] ];
        } while ( i<len && c2==-1);

        if ( c2==-1 )
            break;

        // assamble the first byte
        pOut[n++] = char( (c1<<2) | ((c2&0x30)>>4) );

        // read the third byte
        do {
            c3 = pIn[i++];
            if ( c3==61 )       // meet with "=", break
                goto end; //return;
            c3 = _base64_decode_chars[ c3 ];
        } while ( i<len && c3==-1);

        if ( c3==-1 )
            break;

        // assamble the second byte
        pOut[n++] = char( ((c2&0XF)<<4) | ((c3&0x3C)>>2) );

        // read the fourth byte
        do {
            c4 = pIn[i++];
            if ( c4==61 )       // meet with "=", break
                goto end; //return;
            c4 = _base64_decode_chars[ c4 ];
        } while ( i<len && c4==-1 );

        if ( c4==-1 )
            break;

        // assamble the third byte
        pOut[n++] = char( ((c3&0x03)<<6) | c4 );
    }
end:
 *pdwOutLen = n;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    BOOL encodeMemMap()
// 功能:    将ANSI格式文件转成Base64格式文件
// 参数:    fIn  ANSI格式的文件名
//   fOut Base64格式的文件名
// 返回值:  BOOL TRUE(成功) FALSE(失败)
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
BOOL Base64::encodeMemMap(LPCTSTR fIn, LPCTSTR fOut)
{
 HANDLE hIn, hOut, hInMap, hOutMap;
 LPSTR pIn, pInFile;
 LPSTR pOut, pOutFile;
 DWORD dwInLow, dwOutLow;
 DWORD dwOutLen = 0;

 hIn = CreateFile(fIn, GENERIC_READ, 0, NULL,
  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
 hInMap = CreateFileMapping(hIn, NULL, PAGE_READONLY,
  0, 0, NULL);
 pInFile = (LPSTR)MapViewOfFile(hInMap, FILE_MAP_READ, 0, 0, 0);
 
 hOut = CreateFile(fOut, GENERIC_READ|GENERIC_WRITE, 0, NULL,
  CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
 dwInLow = GetFileSize(hIn, NULL);
 dwOutLow = CalcANSItoBase64Len(dwInLow);
 hOutMap = CreateFileMapping(hOut, NULL, PAGE_READWRITE,
  0, dwOutLow, NULL);
 pOutFile = (LPSTR)MapViewOfFile(hOutMap, FILE_MAP_WRITE, 0, 0, dwOutLow);

 //转换
 pIn = pInFile;
 pOut = pOutFile;
 encode(pIn, dwInLow, pOut, &dwOutLen);

 UnmapViewOfFile(pOutFile); UnmapViewOfFile(pInFile);
 CloseHandle(hOutMap); CloseHandle(hInMap);
 CloseHandle(hOut); CloseHandle(hIn);
 return TRUE;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    BOOL decodeMemMap()
// 功能:    将Base64格式文件转成ANSI格式文件
// 参数:    fIn  Base64格式的文件名
//   fOut ANSI格式的文件名
// 返回值:  BOOL TRUE(成功) FALSE(失败)
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
BOOL Base64::decodeMemMap(LPCTSTR fIn, LPCTSTR fOut)
{
 HANDLE hIn, hOut, hInMap, hOutMap;
 LPSTR pIn, pInFile;
 LPSTR pOut, pOutFile;
 DWORD dwInLow, dwOutLow;
 DWORD dwOutLen = 0;
 TCHAR szBuf[3] = "";

 hIn = CreateFile(fIn, GENERIC_READ, 0, NULL,
  OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
 dwInLow = GetFileSize(hIn, NULL);
 if (dwInLow >= 2)
 {
  SetFilePointer(hIn, -2, NULL, FILE_END);
  DWORD result;
  ReadFile(hIn, szBuf, 2, &result, NULL);
  dwOutLow = CalcBase64toANSILen(dwInLow, szBuf);
 }
 hInMap = CreateFileMapping(hIn, NULL, PAGE_READONLY,
  0, 0, NULL);
 pInFile = (LPSTR)MapViewOfFile(hInMap, FILE_MAP_READ, 0, 0, 0);
 
 hOut = CreateFile(fOut, GENERIC_READ|GENERIC_WRITE, 0, NULL,
  CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
 hOutMap = CreateFileMapping(hOut, NULL, PAGE_READWRITE,
  0, dwOutLow, NULL);
 pOutFile = (LPSTR)MapViewOfFile(hOutMap, FILE_MAP_WRITE, 0, 0, dwOutLow);

 //转换
 pIn = pInFile;
 pOut = pOutFile;
 decode(pIn, dwInLow, pOut, &dwOutLen);

 UnmapViewOfFile(pOutFile); UnmapViewOfFile(pInFile);
 CloseHandle(hOutMap); CloseHandle(hInMap);
 CloseHandle(hOut); CloseHandle(hIn);
 return TRUE;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    BOOL encode()
// 功能:    将ANSI格式文件转成Base64格式文件
// 参数:    cstrSrc ANSI格式的文件名
//   cstrDes Base64格式的文件名
// 返回值:  BOOL TRUE(成功) FALSE(失败)
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
BOOL Base64::encode(const CString cstrSrc, const CString cstrDes)
{
 try
 {
  CFile file(cstrSrc, CFile::modeRead);
  CFile desFile(cstrDes, CFile::modeWrite | CFile::modeCreate);

  int length = file.GetLength();
  while (length>0)
  {
   int size = 4095; //必须是3的倍数,不然就被'='所烦。解码只要以四的倍数即可
   PSTR buffer=NULL;
   buffer = new TCHAR[size];
   UINT nBytesRead = file.Read(buffer, size);

   // 将Base64格式写入文件
   PSTR pszBase64 = AllocMemBase64(nBytesRead);
   DWORD dwBase64 = 0;
   encode(buffer, nBytesRead, pszBase64, &dwBase64);
   desFile.Write(pszBase64, dwBase64);
   FreeMemBase64(pszBase64);
   delete[] buffer;
  
   length -= nBytesRead;
  }
 }
 catch(CFileException *e)
 {
//   MessageBox(NULL, e->ReportError(), "error", MB_OK);
  e->Delete();
  return FALSE;
 }

 return TRUE;
}


//////////////////////////////////////////////////////////////////////////
// 函数:    BOOL decode()
// 功能:    将Base64格式文件转成ANSI格式文件
// 参数:    cstrSrc Base64格式的文件名
//   cstrDes ANSI格式的文件名
// 返回值:  BOOL TRUE(成功) FALSE(失败)
// 日期:    [6/24/2005]
//////////////////////////////////////////////////////////////////////////
BOOL Base64::decode(const CString cstrSrc, const CString cstrDes)
{
 try
 {
  CFile file(cstrSrc, CFile::modeRead);
  CFile desFile(cstrDes, CFile::modeWrite | CFile::modeCreate);

  // 读取ANSI文件放入cstrANSI
  int length = file.GetLength();
  while (length>0)
  {
   int size = 4096; //必须是4的倍数
   PSTR buffer=NULL;
   buffer = new TCHAR[size];
   UINT nBytesRead = file.Read(buffer, size);

   PSTR pszANSI = AllocMemANSI(nBytesRead);
   DWORD dwANSI = 0;
   decode(buffer, nBytesRead, pszANSI, &dwANSI);
   desFile.Write(pszANSI, dwANSI);
   FreeMemANSI(pszANSI);
   delete[] buffer;

   length -= nBytesRead;
  }
 }
 catch(CFileException *e)
 {
//   MessageBox(NULL, e->ReportError(), "error", MB_OK);
  e->Delete();
  return FALSE;
 }

 return TRUE;
}

-===================

PHP实现Base64编码解码类的详细教程 在自定义Base64编解码类时,我们需要首先定义类的基本结构,包括它的属性和方法。以下是一个简化版的Base64类的结构设计:// 将输入数据编码成Base64字符串// 将Base64字符串解码回原始数据// 内部使用的方法,处理数据分组的编码// 内部使用的方法,处理数据分组的解码// 更多辅助方法可以在这里定义,例如错误处理等。 阅读详情

相关推荐

Base64编码(VC++实现)

Base64内容传送编码(VC++实现):常用于电子邮件的数据传输中

【转】VC Base64编解码

#include #include unsigned char * base64=(unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; // 编码CString Base64Encode(CString src, int srclen){ int n, buflen, i,

奋斗 1398

TwinCAT3新手必看:5分钟搞定EtherCAT从站PDO动态配置(附电流变量添加技巧)

本文为TwinCAT3新手提供了EtherCAT从站PDO动态配置的快速入门指南。文章详细解析了Process Data Object(PDO)在实时数据交换中的核心作用,并分步演示了在TwinCAT3工程中扫描从站、动态添加与映射PDO(包括接收PDO和发送PDO)的完整操作流程。重点分享了如何灵活添加并监控如电机实际电流等关键工艺变量的高级技巧,并针对不同品牌驱动器的兼容性问题提供了实用的调试心法和解决方案,帮助工程师快速上手并优化工业自动化系统。

xgboost6farmer的博客 459

c++/mfc base64编解码 base64编码 base64解码

unsigned char * base64=(unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";   CString base64encode(CString src,int srclen) {      int n,buflen,i,j;      static un

pornographer的专栏 4425

微信小程序订阅消息实战:如何绕过长期订阅限制实现多次发送(附PHP代码)

本文针对微信小程序开发者无法获取长期订阅消息权限的痛点,提供了一套完整的实战解决方案。通过深入剖析一次性订阅与长期订阅的规则差异,结合巧妙的交互设计、稳健的PHP服务端发送引擎(含高并发处理与失败重试机制)以及授权池管理等高级策略,帮助开发者在合规前提下,构建高可用的消息推送系统,有效提升通知触达率与用户体验。

weixin_29008805的博客 632

基于 Quest 摄像头数据开发的原理介绍【Unity Meta Quest MR 开发教程】

比如想在识别到的现实物体上叠加虚拟物体,需要知道这个现实物体在 Unity 的世界坐标下的哪个位置,是带有 x,y,z 三个轴的数据的。而 WebCamTexture 捕捉到的图像只是个 2D 的平面,没有三维世界的深度信息,我们通过物体识别算法识别到的物体坐标只是在这个 2D 平面上的一个屏幕坐标,可以理解为 Quest 拍摄了一张照片,我们识别到这张照片上的某个像素点为需要识别的现实物体的中心。是不是看起来比较复杂?Quest 的相机访问功能是在安卓的。

qq_46044366的博客 2111

MFC封装的base64编码解码函数

函数本就是网上下载的,经过我修改并测试通过以后,封装成C++代码了,并且使用了MFC的数据结构,懂C或C++的朋友可以拿过去稍作修改就可以用了。 提醒:作为C函数,在进行base64编码时一定要给够缓冲区,base64是将8比特数据封装到6比特里,所以缓冲区大小应该为原数据长度 x 4 / 3 + 3,同理,解码的时候则是原数据长度 x 3 / 4 +4,为什么+3、+4?这是因为整除会抛弃余数,余数最大值分别为:2、3,+3、4,多了1个字节,正好给结尾的字符0准备。 #include "StdAfx.h

canlynetsky的博客 1364

llama.cpp部署大模型

llama.cpp如何部署大模型

Eddy的博客 989

base64加密解密

因为jsp是写在web-info下的,只能后台访问,只能request跳转,在登陆的时候因为是request跳转,所以想加密url中的参数 ps:操蛋的form表单提交登陆后刷新会导致重复提交。。。。 js // base64加密开始 var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstu...

略略略的博客 996

Python re库【正则表达式操作库】全面讲解及代码示例

以下是Pythonre库的全面讲解,包含主要功能、常用方法及代码示例。完整代码和注释附后。正则表达式(Regular Expression)是用于匹配、查找、替换字符串的工具,通过特定语法定义模式。?{n}[...][a-z]A|B\d[0-9]\D\s\S\w\Wre从字符串匹配模式,返回Match对象或None。在字符串中第一个匹配项,返回Match对象或None。返回所有匹配项的。返回所有匹配项的Match对象)。替换匹配项,返回新字符串。根据模式分割字符串,返回列表。通过。

记录点滴 1164

AI自瞄原理剖析(四)从Yolo推理坐标到屏幕坐标:基于FOV视角与焦距的坐标变换与精准瞄准

从Yolo推理框架得到的坐标到屏幕坐标的转换是一个涉及到FOV视角、焦距以及分辨率的复杂过程。通过数学公式,我们可以将推理框坐标反推为游戏内的实际坐标,并最终映射到屏幕坐标系中。利用这些信息,AI自瞄系统能够精确计算出准星从当前位置移动到敌人位置的距离,实现精准的自动瞄准。通过这种方法,AI自瞄系统能够在不同的游戏环境下灵活应对,提供高度精确的操作体验。在AI自瞄系统中,目标检测仅仅是第一步,获取到预测框的坐标后,我们还需要将这些坐标转换为实际屏幕上的精确位置。

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1341

java base64 编码 类_java版base64编码解码类

较早的java版本没有直接提供base64编码处理的类,都是通过其他类库的附加功能实现。而对于android平台,又有自己的base64支持类, 导致代码影响跨平台。所以就自己写了个base64编码处理的类,这样就可以同一套代码运行在android平台和se平台了。packagecom.hoverlees.utils;/***@authorhoverleeshttp://www.hoverlees...

weixin_36145673的博客 215

DAMMFND: Domain-Aware Multimodal Multi-view Fake News Detection

虚假新闻的泛滥不仅严重阻碍了互联网社交媒体的健康发展,还在政治、经济和社会层面造成了实际危害,凸显了自动化虚假新闻检测的重要性(Zhou 等,2015;Cui 等,2019;Zhu 等,2022a;Li 等,2024c,b,a)。现有的虚假新闻检测方法通常聚焦于特定领域的新闻,例如健康或政治领域。然而,在现实世界中,社交媒体上的新闻往往跨越多个领域,这就要求现有的虚假新闻检测方法必须考虑多域泛化(Nan 等,2021;Qi 等,2019;Zhu 等,2022b)。

qq_52053775的博客 345

base64编码和解码类

/**  * base64编码和解码类  * Base64.java  * @author vincent chen  * @since 2012 Jun 25, 2012 8:09:05 PM  */ public class Base64Coder {     // The line separator string of the operating system.     p

chong7171的专栏 616

PyTorch实战(21)——扩散模型(Diffusion Model)

扩散模型通过简单的噪声扩散过程,就能创造出高质量的超现实图像。在本节中,我们首先学习了扩散如何用于图像生成,了解了扩散模型的内部运作机制。随后基于动漫图像数据集,使用 PyTorch 和 Hugging Face 框架训练和运行自定义扩散模型,生成逼真动漫图像。

盼小辉丶的博客 3538

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

java base64 编码 类_java base64编码和解码的三种方式 | 学步园

方式一:使用commons-codec.jar/*** @param bytes* @return*/public static byte[] decode(final byte[] bytes) {return Base64.decodeBase64(bytes);}/*** 二进制数据编码为BASE64字符串** @param bytes* @return* @throws Exception...

weixin_30131185的博客 349

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

c# Base64编码解码类

c# Base64编码解码类

Debug-123 431

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

基于flash AS3.0 的BASE64编码与解码类

代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--&gt;//调用代码: import com.dynamicflash.utils.Base64; //编码和解码字符串 var source:Stri...

优秀技术文章收录 384

AS3的BASE64编码与解码类

最近任务紧,工作忙,好久没来更新我的BLOG了。今天在国外网站上淘到一个很好用的AS3的BASE64类感觉写得简洁而强大。很好,赶快放上来。调用代码:import com.dynamicflash.utils.Base64;      //编码和解码字符串      var source:Str

blacksource的专栏 4831

Base64 Encode/Decode Class C++ SourceCode - Base64编码/解码 类 C++ 源码

Base64 Encode/Decode Class C++ SourceCode - Base64编码/解码 类 C++ 源码  1、Base64.h // Base64.h: interface for the CBase64 class.////////////////////////////////////////////////////////////////////

纪飞的博客 8969

基于 flash AS3.0 的BASE64编码与解码类

版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明 http://programmer.blogbus.com/logs/36436446.html 在国外网站上淘到一个很好用的AS3的BASE64类感觉写得简洁而强大。很好,赶快放上来。 调用代码: 01 import com.dynamicflash.utils.Base64;      02 //编码和

Manketon的专栏 2450

php的Url 安全的base64编码解码类

用于 http传输的,安全的url base64编码,主要对 +,-,=字符进行了处理,以防止注入的产生

hzbigdog的专栏 1236

Java 版本的 Base64 编码解码类

J2SE 中没有标准的 Base64 编码解码类,虽然可以使用非标准的 sun.misc.BASE64Encoder 和 sun.misc.BASE64Decoder,但是用非标准的东西总感觉不好。所以自己写了一个 Base64 编码解码的类。这个类只有 2 个方法,一个 encode,一个 decode,encode 用来将 byte 数组转化为 Base64 字符串,而 decode 则将 B

走向资深架构师的旅程 1070

java常用工具类:实现base64加盐编码、解码

本文实现加盐的base64编码和解码

m0_71817461的博客 517

java base64 编码 类_java base64编码解码工具类

自己编写的java base64编码解码工具类使用起来很方便就分享出来了,以下的案例使用的base64 utf-8编码,如果想改gbk编码只需要传不同的值即可,下面来解析一下base64的使用。packagecom.baidu;importjava.io.UnsupportedEncodingException;importjava.nio.charset.Charset;importco...

weixin_39707725的博客 411
上一篇: POP3Dlg.cpp
下一篇: 简单实现强大的加密功能——CryptoAPI
iiprogram
博客等级 码龄25年 1068粉丝 1515原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址