base64加密 C code

2016-2-20 海滨 程序就是一个世界

base64.h

#ifndef _BASE64_H
#define _BASE64_H

char* base64_encode(const char*);
#endif

base64.c

#define _CRT_SECURE_NO_WARNINGS
#include "base64.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

static char base64_index[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char* base64_encode(char* c)
{
	//临时字符串
	char* tmpc = NULL;
	char* tmpcc = NULL;
	//返回字符串
	char* ret = NULL;
	char* tret = NULL;
	unsigned int i = 0;
	unsigned int tlen3 = 0;
	//计算所需要申请的字符的长度
	unsigned int tlen = ceil(strlen(c) / 3.0) * 3;
	//计算分为多少组
	tlen3 = tlen / 3;
	//申请临时字符串所需内存 以及结果字符串所占内存
	tmpc = (char*)malloc(sizeof(char)*(tlen + 1));
	ret = (char*)malloc(sizeof(char)*(tlen3 * 4 + 1));
	tmpcc = tmpc;
	tret = ret;
	ret[sizeof(char)*(tlen3 * 4 + 1) - 1] = '\0';
	//拷贝字符串
	strcpy(tmpcc, c);
	//将指针移动到\0
	while (*tmpcc != '\0')
	{
		//记住当前位置
		i++;
		//移动指针
		tmpcc++;
	}
	for (; i < tlen +1; i++)
	{
		tmpc[i] = '\0';
	}
	//读取所构造字符串
	for (i = 0; i < tlen3; i++)
	{
		for (int j = 0; j < 3; j++)
		{
			switch (j)
			{
			case 0:
				if ((tmpc[i * 3 + j] >> 2) == 0 && tmpc[i * 3 + j] == 0) {
					*ret = '=';
				}
				else
				{
					*ret = base64_index[tmpc[i * 3 + j] >> 2];
					
				}
				ret++;
				break;
			case 1:
				//第二个字符
				char tmpchar = ((tmpc[i * 3 + j - 1] & 0x03) << 4) | ((tmpc[i * 3 + j] >> 4) & 0x0F);
				if (tmpchar == 0 && tmpc[i * 3 + j] == 0)
				{
					*ret = '=';
				}
				else
				{
					*ret = base64_index[tmpchar];
				}
				ret++;
				//第三个字符
				tmpchar = (((tmpc[i * 3 + j] & 0x0F) << 2) | (tmpc[i * 3 + j + 1]  >> 6));
				if (tmpchar == 0 && tmpc[i * 3 + j] == 0)
				{
					*ret = '=';
				}
				else
				{
					*ret = base64_index[tmpchar];
				};
				ret++;

				break;
			case 2:
				if ((tmpc[i * 3 + j] & 0x3F) == 0 && tmpc[i * 3 + j] == 0)
				{
					*ret = '=';
					
				}
				else
				{
					*ret = base64_index[tmpc[i * 3 + j] & 0x3F];
				}
				ret++;
				break;
			default:
				break;
			}
		}
	}

	free(tmpc);

	
	return tret;
}

main.c

#include<stdio.h>
#include "base64.h"

int main()
{
	char* c = "sdfdrfdrg";
	char* c_base64en = base64_encode(c);
	printf("%s", c_base64en);
	free(c_base64en);
	getchar();
	return 0;
}


标签: base64encode

发表评论:


Powered by 海滨Blog
sitemap