Base64加密解密算法的C/C++代码实现

这个Base64是从Live555的代码里面提取出来的,请大家放心使用吧。

 

Base64的加密解密的算法和原理我就不想说了。。。。, 网上有很多介绍原理的文章。

这个算法有啥好处呢?  为什么我们要用它?

 

Base64算法不是为了防止内容被人破解而使用的算法, 因为破解Base64太容易了, 就是简单的字符替换。

 

Base64还有个不好的地方,就是加密后, 长度会变成。

 

那我们为何还要使用Base64 呢 ?  因为Base64可以把乱七八糟的二进制转化为字符串,这个特性在很多地方很有用。

 

Base64.h 头文件

/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2010 Live Networks, Inc.  All rights reserved.
// Base64 encoding and decoding
// C++ header

#ifndef _BASE64_HH
#define _BASE64_HH

//#ifndef _BOOLEAN_HH
//#include "Boolean.hh"
//#endif

#ifdef __cplusplus
extern "C" {
#endif

unsigned char* base64Decode(char* in, unsigned int& resultSize, bool trimTrailingZeros = true);
    // returns a newly allocated array - of size "resultSize" - that
    // the caller is responsible for delete[]ing.

char* base64Encode(char const* orig, unsigned origLength);
    // returns a 0-terminated string that
    // the caller is responsible for delete[]ing.

#ifdef __cplusplus
}
#endif

#endif

Base64.cpp 文件

 

/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)

This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for
more details.

You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
**********/
// "liveMedia"
// Copyright (c) 1996-2010 Live Networks, Inc.  All rights reserved.
// Base64 encoding and decoding
// implementation

#include "base64.h"

#include <string.h>

static char base64DecodeTable[256];

char* strDup(char const* str)
{
	if (str == NULL) return NULL;
	size_t len = strlen(str) + 1;
	char* copy = new char[len];

	if (copy != NULL)
	{
		memcpy(copy, str, len);
	}
	return copy;
}

char* strDupSize(char const* str)
{
	if (str == NULL) return NULL;
	size_t len = strlen(str) + 1;
	char* copy = new char[len];

	return copy;
}

static void initBase64DecodeTable()
{
  int i;
  for (i = 0; i < 256; ++i) base64DecodeTable[i] = (char)0x80;
      // default value: invalid

  for (i = 'A'; i <= 'Z'; ++i) base64DecodeTable[i] = 0 + (i - 'A');
  for (i = 'a'; i <= 'z'; ++i) base64DecodeTable[i] = 26 + (i - 'a');
  for (i = '0'; i <= '9'; ++i) base64DecodeTable[i] = 52 + (i - '0');
  base64DecodeTable[(unsigned char)'+'] = 62;
  base64DecodeTable[(unsigned char)'/'] = 63;
  base64DecodeTable[(unsigned char)'='] = 0;
}

unsigned char* base64Decode(char* in, unsigned int& resultSize, bool trimTrailingZeros)
{
  static bool haveInitedBase64DecodeTable = false;
  if (!haveInitedBase64DecodeTable)
  {
    initBase64DecodeTable();
    haveInitedBase64DecodeTable = true;
  }

  unsigned char* out = (unsigned char*)strDupSize(in); // ensures we have enough space
  int k = 0;
  int const jMax = strlen(in) - 3;
     // in case "in" is not a multiple of 4 bytes (although it should be)
  for (int j = 0; j < jMax; j += 4)
  {
    char inTmp[4], outTmp[4];
    for (int i = 0; i < 4; ++i)
	{
      inTmp[i] = in[i+j];
      outTmp[i] = base64DecodeTable[(unsigned char)inTmp[i]];
      if ((outTmp[i]&0x80) != 0) outTmp[i] = 0; // pretend the input was 'A'
    }

    out[k++] = (outTmp[0]<<2) | (outTmp[1]>>4);
    out[k++] = (outTmp[1]<<4) | (outTmp[2]>>2);
    out[k++] = (outTmp[2]<<6) | outTmp[3];
  }

  if (trimTrailingZeros)
  {
    while (k > 0 && out[k-1] == '/0') --k;
  }
  resultSize = k;
  unsigned char* result = new unsigned char[resultSize];
  memmove(result, out, resultSize);
  delete[] out;

  return result;
}

static const char base64Char[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

char* base64Encode(char const* origSigned, unsigned origLength)
{
  unsigned char const* orig = (unsigned char const*)origSigned; // in case any input bytes have the MSB set
  if (orig == NULL) return NULL;

  unsigned const numOrig24BitValues = origLength/3;
  bool havePadding = origLength > numOrig24BitValues*3;
  bool havePadding2 = origLength == numOrig24BitValues*3 + 2;
  unsigned const numResultBytes = 4*(numOrig24BitValues + havePadding);
  char* result = new char[numResultBytes+1]; // allow for trailing '/0'

  // Map each full group of 3 input bytes into 4 output base-64 characters:
  unsigned i;
  for (i = 0; i < numOrig24BitValues; ++i)
  {
    result[4*i+0] = base64Char[(orig[3*i]>>2)&0x3F];
    result[4*i+1] = base64Char[(((orig[3*i]&0x3)<<4) | (orig[3*i+1]>>4))&0x3F];
    result[4*i+2] = base64Char[((orig[3*i+1]<<2) | (orig[3*i+2]>>6))&0x3F];
    result[4*i+3] = base64Char[orig[3*i+2]&0x3F];
  }

  // Now, take padding into account.  (Note: i == numOrig24BitValues)
  if (havePadding)
  {
    result[4*i+0] = base64Char[(orig[3*i]>>2)&0x3F];
    if (havePadding2)
	{
      result[4*i+1] = base64Char[(((orig[3*i]&0x3)<<4) | (orig[3*i+1]>>4))&0x3F];
      result[4*i+2] = base64Char[(orig[3*i+1]<<2)&0x3F];
    }
	else
	{
      result[4*i+1] = base64Char[((orig[3*i]&0x3)<<4)&0x3F];
      result[4*i+2] = '=';
    }
    result[4*i+3] = '=';
  }

  result[numResultBytes] = '/0';
  return result;
}
时间: 2024-10-24 10:04:11

Base64加密解密算法的C/C++代码实现的相关文章

java实现Base64加密解密算法_java

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

一组PHP可逆加密解密算法实例代码

 这篇文章主要介绍了一组PHP可逆加密解密算法实例代码,有需要的朋友可以参考一下 对于大部分密码加密,我们可以采用md5.sha1等方法.可以有效防止数据泄露,但是这些方法仅适用于无需还原的数据加密.   对于需要还原的信息,则需要采用可逆的加密解密算法.   下面一组PHP函数是实现此加密解密的方法:   加密算法如下: 代码如下: function encrypt($data, $key) {  $key = md5($key);     $x  = 0;     $len = strlen

一组PHP可逆加密解密算法实例代码_php实例

对于大部分密码加密,我们可以采用md5.sha1等方法.可以有效防止数据泄露,但是这些方法仅适用于无需还原的数据加密. 对于需要还原的信息,则需要采用可逆的加密解密算法. 下面一组PHP函数是实现此加密解密的方法: 加密算法如下: 复制代码 代码如下: function encrypt($data, $key){ $key = md5($key);    $x  = 0;    $len = strlen($data);    $l  = strlen($key);    for ($i = 0

详解.NET下的加密解密算法(2) 对称加密

本博文列出了.NET下常用的对称加密算法,并将它们制作成小DEMO,希望能对大家有所帮助. 公共代码 static byte[] CreateKey(int num) { byte[] result = new byte[num]; Random rand = new Random(); for (int i = 0; i < num; i++) { result[i] = (Byte)rand.Next(1, 256); } return result; } DES /// <summary

详解.NET下的加密解密算法(3) 非对称加密

本博文列出了.NET下常用的非对称加密算法,并将它们制作成小DEMO,希望能对大家有所帮助. RSA static string EnRSA(string data,string publickey) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(publickey); cipherbytes = rsa.Encrypt(Encoding

PHP实现加密解密算法

PHP实现加密解密的算法,如下代码: <?php    class Mcrypt    {        /**        * 解密        *         * @param string $encryptedText 已加密字符串        * @param string $key  密钥        * @return string        */        public static function _decrypt($encryptedText,$key =

C#加密解密算法

加密|解密|算法 /*************************字符串加密算法***********************/public string EncryptString(string str)  {   char[] Base64Code=new char[]{'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

Relaxlife.net可加密/解密中文/英文的Asp代码

加密|解密|中文  Relaxlife.net可加密/解密中文/英文的Asp代码供大家下载,这可是机密,可用在代码加密 可加密/解密中文/英文的Asp代码供大家下载,这可是机密,可用在代码加密 Function.asp <% Rem ================================================================= Rem = 函数文件:Function.asp Rem = 测试文件:TestEncrypt.asp,Encryptpass.asp

php使用base64加密解密图片示例分享

 这篇文章主要介绍了php使用base64加密解密图片的示例,大家参考使用吧    代码如下: <?php   //文件名:base64.php $data="/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9P DkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2MBERISGBUYLxoaL2NCOEJjY2NjY2NjY2NjY2 NjY2NjY2NjY