欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c++如何实现Base64算法

程序员文章站 2022-12-06 14:11:56
base64用途1.用于对soho级路由器(网关设备)管理员帐户密码的加密2.流媒体网站对于播放的流媒体文件的路径的加密3.迅雷等下载软件对下载链接地址的加密base64算法base64编码要求把3个...

base64用途

1.用于对soho级路由器(网关设备)管理员帐户密码的加密

2.流媒体网站对于播放的流媒体文件的路径的加密

3.迅雷等下载软件对下载链接地址的加密

base64算法

base64编码要求把3个8位字节(3*8=24)转化为4个6位的字节(4*6=24),之后在6位的前面补两个0,形成8位一个字节的形式。

c++如何实现Base64算法

c++如何实现Base64算法

base64类

函数:

unsigned int creatematchingencodingbuffer (unsigned int p_inputbytecount, char** p_ppencodingbuffer);

创建匹配于编码的缓存空间。参数:1输入字节数,2进行编码需要的缓存空间;返回值:缓存空间大小。

unsigned int creatematchingdecodingbuffer (char* p_pinputbufferstring, char** p_ppdecodingbuffer);

创建匹配于解码的缓存空间。参数:1解码对象缓存,2进行解码需要的缓存空间;返回值:缓存空间大小。

void encodebuffer (char* p_pinputbuffer, unsigned int p_inputbufferlength, char* p_poutputbufferstring);

进行编码。参数:1明文,2明文长度,3密文输出。

unsigned int decodebuffer (char* p_pinputbufferstring, char* p_poutputbuffer);

进行解码。参数:1密文,2明文;返回值:明文长度

c++实现:

头文件:

view code 

/************************************************
*            *
* cbase64.h          *
* base 64 de- and encoding class    *
*            *
* ============================================ *
*            *
* this class was written on 28.05.2003    *
* by jan raddatz [jan-raddatz@web.de]    *
*            *
* ============================================ *
*            *
* copyright (c) by jan raddatz      *
* this class was published @ codeguru.com  *
* 28.05.2003          *
*            *
************************************************/

#pragma once

#include <afx.h>
#include <stdlib.h>
#include <math.h>
#include <memory.h>
const static unsigned int max_line_length = 76;

const static char base64_alphabet [64] = 
{
  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', //  0 -  9
  'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', // 10 - 19
  'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', // 20 - 29
  'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', // 30 - 39
  'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', // 40 - 49
  'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', // 50 - 59
  '8', '9', '+', '/'         // 60 - 63
};

const static char base64_dealphabet [128] = 
{
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //  0 -  9
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10 - 19
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 - 29
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 30 - 39
  0, 0, 0, 62, 0, 0, 0, 63, 52, 53, // 40 - 49
  54, 55, 56, 57, 58, 59, 60, 61, 0, 0, // 50 - 59
  0, 61, 0, 0, 0, 0, 1, 2, 3, 4, // 60 - 69
  5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 70 - 79
  15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 80 - 89
  25, 0, 0, 0, 0, 0, 0, 26, 27, 28, // 90 - 99
  29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // 100 - 109
  39, 40, 41, 42, 43, 44, 45, 46, 47, 48, // 110 - 119
  49, 50, 51, 0, 0, 0, 0, 0    // 120 - 127
};

enum
{
  unable_to_open_input_file,
  unable_to_open_output_file,
  unable_to_create_outputbuffer
};

class cbase64
{
public:
  cbase64 ();

  unsigned int calculaterecquiredencodeoutputbuffersize (unsigned int p_inputbytecount);
  unsigned int calculaterecquireddecodeoutputbuffersize (char* p_pinputbufferstring);

  void encodebytetriple (char* p_pinputbuffer, unsigned int inputcharacters, char* p_poutputbuffer);
  unsigned int decodebytequartet (char* p_pinputbuffer, char* p_poutputbuffer);

  void encodebuffer (char* p_pinputbuffer, unsigned int p_inputbufferlength, char*p_poutputbufferstring);
  unsigned int decodebuffer (char* p_pinputbufferstring, char* p_poutputbuffer);

  unsigned int creatematchingencodingbuffer (unsigned int p_inputbytecount, char** p_ppencodingbuffer);
  unsigned int creatematchingdecodingbuffer (char* p_pinputbufferstring, char** p_ppdecodingbuffer);

  unsigned int encodefile (char* p_psourcefilename, char* p_pencodedfilename);
  unsigned int decodefile (char* p_psourcefilename, char* p_pdecodedfilename);
};

cpp文件:

view code 

/************************************************
*            *
* cbase64.cpp          *
* base 64 de- and encoding class    *
*            *
* ============================================ *
*            *
* this class was written on 28.05.2003    *
* by jan raddatz [jan-raddatz@web.de]    *
*            *
* ============================================ *
*            *
* copyright (c) by jan raddatz      *
* this class was published @ codeguru.com  *
* 28.05.2003          *
*            *
************************************************/
#include "stdafx.h"
#include "cbase64.h"


cbase64::cbase64 ()
{
}

unsigned int cbase64::calculaterecquiredencodeoutputbuffersize (unsigned int p_inputbytecount)
{
  div_t result = div (p_inputbytecount, 3);

  unsigned int recquiredbytes = 0;
  if (result.rem == 0)
  {
    // number of encoded characters
    recquiredbytes = result.quot * 4;

    // crlf -> "\r\n" each 76 characters
    result = div (recquiredbytes, 76);
    recquiredbytes += result.quot * 2;

    // terminating null for the encoded string
    recquiredbytes += 1;

    return recquiredbytes;
  }
  else
  {
    // number of encoded characters
    recquiredbytes = result.quot * 4 + 4;

    // crlf -> "\r\n" each 76 characters
    result = div (recquiredbytes, 76);
    recquiredbytes += result.quot * 2;

    // terminating null for the encoded string
    recquiredbytes += 1;

    return recquiredbytes;
  }
}

unsigned int cbase64::calculaterecquireddecodeoutputbuffersize (char* p_pinputbufferstring)
{
  unsigned int bufferlength = strlen (p_pinputbufferstring);

  div_t result = div (bufferlength, 4);

  if (p_pinputbufferstring [bufferlength - 1] != '=')
  {
    return result.quot * 3;
  }
  else
  {
    if (p_pinputbufferstring [bufferlength - 2] == '=')
    {
      return result.quot * 3 - 2;
    }
    else
    {
      return result.quot * 3 - 1;
    }
  }
}

void cbase64::encodebytetriple (char* p_pinputbuffer, unsigned int inputcharacters, char* p_poutputbuffer)
{
  unsigned int mask = 0xfc000000;
  unsigned int buffer = 0;


  char* temp = (char*) &buffer;
  temp [3] = p_pinputbuffer [0];
  if (inputcharacters > 1)
    temp [2] = p_pinputbuffer [1];
  if (inputcharacters > 2)
    temp [1] = p_pinputbuffer [2];

  switch (inputcharacters)
  {
  case 3:
    {
      p_poutputbuffer [0] = base64_alphabet [(buffer & mask) >> 26];
      buffer = buffer << 6;
      p_poutputbuffer [1] = base64_alphabet [(buffer & mask) >> 26];
      buffer = buffer << 6;
      p_poutputbuffer [2] = base64_alphabet [(buffer & mask) >> 26];
      buffer = buffer << 6;
      p_poutputbuffer [3] = base64_alphabet [(buffer & mask) >> 26];
      break;
    }
  case 2:
    {
      p_poutputbuffer [0] = base64_alphabet [(buffer & mask) >> 26];
      buffer = buffer << 6;
      p_poutputbuffer [1] = base64_alphabet [(buffer & mask) >> 26];
      buffer = buffer << 6;
      p_poutputbuffer [2] = base64_alphabet [(buffer & mask) >> 26];
      p_poutputbuffer [3] = '=';
      break;
    }
  case 1:
    {
      p_poutputbuffer [0] = base64_alphabet [(buffer & mask) >> 26];
      buffer = buffer << 6;
      p_poutputbuffer [1] = base64_alphabet [(buffer & mask) >> 26];
      p_poutputbuffer [2] = '=';
      p_poutputbuffer [3] = '=';
      break;
    }
  }
}

unsigned int cbase64::decodebytequartet (char* p_pinputbuffer, char* p_poutputbuffer)
{
  unsigned int buffer = 0;

  if (p_pinputbuffer[3] == '=')
  {
    if (p_pinputbuffer[2] == '=')
    {
      buffer = (buffer | base64_dealphabet [p_pinputbuffer[0]]) << 6;
      buffer = (buffer | base64_dealphabet [p_pinputbuffer[1]]) << 6;
      buffer = buffer << 14;

      char* temp = (char*) &buffer;
      p_poutputbuffer [0] = temp [3];

      return 1;
    }
    else
    {
      buffer = (buffer | base64_dealphabet [p_pinputbuffer[0]]) << 6;
      buffer = (buffer | base64_dealphabet [p_pinputbuffer[1]]) << 6;
      buffer = (buffer | base64_dealphabet [p_pinputbuffer[2]]) << 6;
      buffer = buffer << 8;

      char* temp = (char*) &buffer;
      p_poutputbuffer [0] = temp [3];
      p_poutputbuffer [1] = temp [2];

      return 2;
    }
  }
  else
  {
    buffer = (buffer | base64_dealphabet [p_pinputbuffer[0]]) << 6;
    buffer = (buffer | base64_dealphabet [p_pinputbuffer[1]]) << 6;
    buffer = (buffer | base64_dealphabet [p_pinputbuffer[2]]) << 6;
    buffer = (buffer | base64_dealphabet [p_pinputbuffer[3]]) << 6; 
    buffer = buffer << 2;

    char* temp = (char*) &buffer;
    p_poutputbuffer [0] = temp [3];
    p_poutputbuffer [1] = temp [2];
    p_poutputbuffer [2] = temp [1];

    return 3;
  }

  return -1;
}

void cbase64::encodebuffer(char* p_pinputbuffer, unsigned int p_inputbufferlength, char* p_poutputbufferstring)
{
  unsigned int finishedbytequartetsperline = 0;
  unsigned int inputbufferindex = 0;
  unsigned int outputbufferindex = 0;

  memset (p_poutputbufferstring, 0, calculaterecquiredencodeoutputbuffersize (p_inputbufferlength));

  while (inputbufferindex < p_inputbufferlength)
  {
    if (p_inputbufferlength - inputbufferindex <= 2)
    {
      finishedbytequartetsperline ++;
      encodebytetriple (p_pinputbuffer + inputbufferindex, p_inputbufferlength - inputbufferindex, p_poutputbufferstring + outputbufferindex);
      break;
    }
    else
    {
      finishedbytequartetsperline++;
      encodebytetriple (p_pinputbuffer + inputbufferindex, 3, p_poutputbufferstring + outputbufferindex);
      inputbufferindex += 3;
      outputbufferindex += 4;
    }

    if (finishedbytequartetsperline == 19)
    {
      p_poutputbufferstring [outputbufferindex ] = '\r';
      p_poutputbufferstring [outputbufferindex+1] = '\n';
      p_poutputbufferstring += 2;
      finishedbytequartetsperline = 0;
    }
  }
}

unsigned int cbase64::decodebuffer (char* p_pinputbufferstring, char* p_poutputbuffer)
{
  unsigned int inputbufferindex = 0;
  unsigned int outputbufferindex = 0;
  unsigned int inputbufferlength = strlen (p_pinputbufferstring);

  char bytequartet [4];

  while (inputbufferindex < inputbufferlength)
  {
    for (int i = 0; i < 4; i++)
    {
      bytequartet [i] = p_pinputbufferstring [inputbufferindex];

      // ignore all characters except the ones in base64_alphabet
      if ((bytequartet [i] >= 48 && bytequartet [i] <= 57) ||
        (bytequartet [i] >= 65 && bytequartet [i] <= 90) ||
        (bytequartet [i] >= 97 && bytequartet [i] <= 122) ||
        bytequartet [i] == '+' || bytequartet [i] == '/' || bytequartet [i] == '=')
      {
      }
      else
      {
        // invalid character
        i--;
      }

      inputbufferindex++;
    }

    outputbufferindex += decodebytequartet (bytequartet, p_poutputbuffer + outputbufferindex);
  }

  // outputbufferindex gives us the next position of the next decoded character
  // inside our output buffer and thus represents the number of decoded characters
  // in our buffer.
  return outputbufferindex;
}

unsigned int cbase64::creatematchingencodingbuffer (unsigned int p_inputbytecount, char** p_ppencodingbuffer)
{
  unsigned int size = calculaterecquiredencodeoutputbuffersize (p_inputbytecount);
  (*p_ppencodingbuffer) = (char*) malloc (size);
  memset (*p_ppencodingbuffer, 0, size);
  return size;
}

unsigned int cbase64::creatematchingdecodingbuffer (char* p_pinputbufferstring, char** p_ppdecodingbuffer)
{
  unsigned int size = calculaterecquireddecodeoutputbuffersize (p_pinputbufferstring);
  (*p_ppdecodingbuffer) = (char*) malloc (size+1);
  memset (*p_ppdecodingbuffer, 0, size+1);
  return size+1;
}

unsigned int cbase64::encodefile (char* p_psourcefilename, char* p_pencodedfilename)
{
  cfile inputfile;
  cfile outputfile;

  if (!inputfile.open (p_psourcefilename, cfile::moderead))
    return unable_to_open_input_file;

  if (!outputfile.open (p_pencodedfilename, cfile::modecreate|cfile::modewrite))
    return unable_to_open_output_file;

  char inputbuffer [19 * 3];
  char* poutputbuffer;
  creatematchingencodingbuffer (sizeof (inputbuffer), &poutputbuffer);

  if (poutputbuffer == 0)
    return unable_to_create_outputbuffer;

  unsigned int readbytes = 0;
  while ((readbytes = inputfile.read (inputbuffer, sizeof (inputbuffer))) != 0)
  {
    encodebuffer (inputbuffer, readbytes, poutputbuffer);
    outputfile.write (poutputbuffer, strlen (poutputbuffer));
  }

  outputfile.flush ();
  outputfile.close ();
  inputfile.close ();

  return 0;
}

unsigned int cbase64::decodefile (char* p_psourcefilename, char* p_pdecodedfilename)
{
  cstdiofile  inputfile;
  cfile    outputfile;

  if (!inputfile.open (p_psourcefilename, cfile::moderead))
    return unable_to_open_input_file;

  if (!outputfile.open (p_pdecodedfilename, cfile::modecreate|cfile::modewrite))
    return unable_to_open_output_file;

  cstring inputbuffer;
  char  outputbuffer[64];

  unsigned int readbytes = 0;
  while ((readbytes = inputfile.readstring (inputbuffer)) != 0)
  {
    inputbuffer.remove ('\r');
    inputbuffer.remove ('\n');
    unsigned int decodedbytes = decodebuffer ((lptstr) (lpctstr) inputbuffer, outputbuffer);
    outputfile.write (&outputbuffer [0], decodedbytes);
  }

  outputfile.flush ();
  outputfile.close ();
  inputfile.close ();

  return 0;
}

以上就是c++如何实现base64算法的详细内容,更多关于c++ base64算法的资料请关注其它相关文章!

相关标签: c++ base64 算法