c++如何实现Base64算法

Base64用途

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

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

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

Base64算法

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

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算法的资料请关注我们其它相关文章!

(0)

相关推荐

  • c++base64编解码使用示例

    复制代码 代码如下: #include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>static const char b64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";static const char reverse_table[128

  • Base64 编码介绍、Base64编码转换原理与算法

    Base64编码,是我们程序开发中经常使用到的编码方法.它是一种基于用64个可打印字符来表示二进制数据的表示方法.它通常用作存储.传输一些二进制数据编码方法!也是MIME(多用途互联网邮件扩展,主要用作电子邮件标准)中一种可打印字符表示二进制数据的常见编码方法!它其实只是定义用可打印字符传输内容一种方法,并不会产生新的字符集!有时候,我们学习转换的思路后,我们其实也可以结合自己的实际需要,构造一些自己接口定义编码方式.好了,我们一起看看,它的转换思路吧! Base64实现转换原理 它是用64个可

  • python3 常见解密加密算法实例分析【base64、MD5等】

    本文实例讲述了python3 常见解密加密算法.分享给大家供大家参考,具体如下: 一.使用base64 Base64编码,64指A-Z.a-z.0-9.+和/这64个字符,还有"="号不属于编码字符,而是填充字符. 优点:方法简单 缺点:不保险,别人拿到密文可以自己解密出明文 编码原理:将3个字节转换成4个字节((3 X 8)=24=(4X6)),先读入3个字节,每读一个字节,左移8位,再右移四次,每次6位,这样就有4个字节了. 解码原理:将4个字节转换成3个字节,先读入4个6位(用或

  • Java Base64算法实际应用之邮件发送实例分析

    本文实例讲述了Java Base64算法实际应用之邮件发送.分享给大家供大家参考,具体如下: 一 利用telnet和Base64来实现收发邮件 二 Base64在线编码和解码 http://tools.jb51.net/transcoding/base64 三 Java代码实现 四 运行效果 PS:这里再推荐几款加密解密相关在线工具供大家参考使用: 线编码转换工具(utf-8/utf-32/Punycode/Base64): http://tools.jb51.net/transcoding/d

  • Java实现的Base64加密算法示例

    本文实例讲述了Java实现的Base64加密算法.分享给大家供大家参考,具体如下: 一 算法实现 1.JDK 2.Commonc Codec 3.Bouncy Castle 二 代码 package com.imooc.security.base64; import java.io.IOException; import org.apache.commons.codec.binary.Base64; import sun.misc.BASE64Decoder; import sun.misc.B

  • JavaScript BASE64算法实现(完美解决中文乱码)

    JavaScript 的 BASE64 算法 var BASE64={ enKey: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', deKey: new Array( -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -

  • java实现Base64加密解密算法

    Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045-RFC2049,上面有MIME的详细规范.Base64编码可用于在HTTP环境下传递较长的标识信息.例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数.在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式.

  • Android数据加密之Base64编码算法的简单实现

    前面学习总结了平时开发中遇见的各种数据加密方式,最终都会对加密后的二进制数据进行Base64编码,起到一种二次加密的效果,其实呢Base64从严格意义上来说的话不是一种加密算法,而是一种编码算法,为何要使用Base64编码呢?它解决了什么问题?这也是本文探讨的东西? 什么Base64算法? Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,Base64并不是安全领域的加密算法,其实Base64只能算是一个编码算法,对数据内容进行编码来适合传输.标准Base64编码解码无需额外信

  • Android编程加密算法小结(AES、Base64、RAS加密算法)

    本文实例总结了Android编程加密算法.分享给大家供大家参考,具体如下: android常用加密算法之Base64加密算法: package com.long; /** * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in

  • JS实现的3des+base64加密解密算法完整示例

    本文实例讲述了JS实现的3des+base64加密解密算法.分享给大家供大家参考,具体如下: 1. index.html: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>www.jb51.net BASE64编码</title> <meta http-equiv="Content-Type" content="text/html; c

随机推荐