服务器 频道

MIME邮件中之Base64编解码

  【IT168 服务器学院】Base64是MIME邮件中常用的编码方式之一。它的主要思想是将输入的字符串或数据编码成只含有{''A''-''Z'', ''a''-''z'', ''0''-''9'', ''+'', ''/''}这64个可打印字符的串,故称为“Base64”。

  Base64编码的方法是,将输入数据流每次取6 bit,用此6 bit的值(0-63)作为索引去查表,输出相应字符。这样,每3个字节将编码为4个字符(3×8 → 4×6);不满4个字符的以''=''填充。

  const char EnBase64Tab[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

  int EncodeBase64(const unsigned char* pSrc, char* pDst, int nSrcLen, int nMaxLineLen)
  {
  unsigned char c1, c2, c3; // 输入缓冲区读出3个字节
  int nDstLen = 0; // 输出的字符计数
  int nLineLen = 0; // 输出的行长度计数
  int nDiv = nSrcLen / 3; // 输入数据长度除以3得到的倍数
  int nMod = nSrcLen % 3; // 输入数据长度除以3得到的余数

  // 每次取3个字节,编码成4个字符
  for (int i = 0; i < nDiv; i ++)
  {
  // 取3个字节
  c1 = *pSrc++;
  c2 = *pSrc++;
  c3 = *pSrc++;

  // 编码成4个字符
  *pDst++ = EnBase64Tab[c1 >> 2];
  *pDst++ = EnBase64Tab[((c1 << 4) | (c2 >> 4)) & 0x3f];
  *pDst++ = EnBase64Tab[((c2 << 2) | (c3 >> 6)) & 0x3f];
  *pDst++ = EnBase64Tab[c3 & 0x3f];
  nLineLen += 4;
  nDstLen += 4;

  // 输出换行?
  if (nLineLen > nMaxLineLen - 4)
  {
  *pDst++ = '' '';
  *pDst++ = '' '';
  nLineLen = 0;
  nDstLen += 2;
  }
  }

  // 编码余下的字节
  if (nMod == 1)
  {
  c1 = *pSrc++;
  *pDst++ = EnBase64Tab[(c1 & 0xfc) >> 2];
  *pDst++ = EnBase64Tab[((c1 & 0x03) << 4)];
  *pDst++ = ''='';
  *pDst++ = ''='';
  nLineLen += 4;
  nDstLen += 4;
  }
  else if (nMod == 2)
  {
  c1 = *pSrc++;
  c2 = *pSrc++;
  *pDst++ = EnBase64Tab[(c1 & 0xfc) >> 2];
  *pDst++ = EnBase64Tab[((c1 & 0x03) << 4) | ((c2 & 0xf0) >> 4)];
  *pDst++ = EnBase64Tab[((c2 & 0x0f) << 2)];
  *pDst++ = ''='';
  nDstLen += 4;
  }

  // 输出加个结束符
  *pDst = ''
  

0
相关文章