#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
/**********************************************
作者:Minuit
时间:2007年02月05日 星期日 20时42分33秒
文件名:base64.c
描述:C base64编码操作函数
**********************************************/
/*
A B C D E F G H I J K L M N O P Q
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
R S T U V W X Y Z a b c d e f g h
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
i j k l m n o p q r s t u v w x y
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
z 0 1 2 3 4 5 6 7 8 9 + / (pad) =
51 52 53 54 55 56 57 58 59 60 61 62 63
*/
static char base64_table[255];
char *decode(const char*,char **);
char *encode(const char*,char **);
void base64_tableinit()
{
int i,j;
bzero(base64_table,255);
for(j=0,i='A';i<='Z';i++) /*填base64编码表*/
base64_table=j++;
for(i='a';i<='z';i++)
base64_table=j++;
for(i='0';i<='9';i++)
base64_table=j++;
base64_table['+']=j++;
base64_table['/']=j++;
base64_table['=']=j;
}
char *decode(const char *cptr,char **rptr)
{
char *res;
int clen,len;
static int init=0;
if(cptr==NULL)
return NULL;
len=strlen(cptr);
if(len%4) /*编了码的字符绝对是4的倍数*/
return NULL;
if(!init)
{
init=1;
base64_tableinit();
}
clen=len/4;
if((res=malloc(len-clen))==NULL)
return NULL;
for(*rptr=res;clen--;)
{
*res=base64_table[*cptr++]<<2&0xfc; /*cptr后六位移动到最高位*/
*res++|=base64_table[*cptr]>>4; /*跟着下个字符低两位给res低两位*/
*res=base64_table[*cptr++]<<4&0xf0; /*填充res高四位其它清0*/
*res++|=base64_table[*cptr]>>2&0x0f; /*字符前六位移到低六位取低四位*/
*res=base64_table[*cptr++]<<6;
if(*cptr!='=') /*=号乎略*/
*res++|=base64_table[*cptr++];
}
return *rptr;
}
char *encode(const char *cptr,char **rptr)
{
char *res;
int i,clen,len;
len=strlen(cptr);
clen=len/3;
if(cptr==NULL||(res=malloc(clen+3*2+len))==NULL)
return NULL;
for(*rptr=res;clen--;)
{
*res++=*cptr>>2&0x3f; /*取ptr高6位放入res低6位*/
*res=*cptr++<<4&0x30; /*移动ptr最低2位到高6位然后清0其 它位*/
*res++|=*cptr>>4; /*取ptr高4位给res低4位*/
*res=(*cptr++&0x0f)<<2; /*取ptr低4位移动到高6位*/
*res++|=*cptr>>6; /*取ptr高2位给res低2位*/
*res++=*cptr++&0x3f;
}
if(i=len%3) /*处理多余字符只有两种情况多一个或者两个字符*/
{
if(i==1) /*根据base64编码补=号*/
{
*res++=*cptr>>2&0x3f;
*res++=*cptr<<4&0x30;
*res++='=';
*res++='=';
}
else
{
*res++=*cptr>>2&0x3f;
*res=*cptr++<<4&0x30;
*res++|=*cptr>>4;
*res++=(*cptr&0x0f)<<2;
*res++='=';
}
}
*res='='; /*保证最后结位为=结束原因是因为base64里有为0的编码*/
for(res=*rptr;*res!='=';res++)
*res="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[*res];
rptr[0][strlen(*rptr)-1]='/0'; /*去掉最后一个=号*/
return *rptr;
}
贡献两个函数本来想写着转成perl用的但是目前还没有学xs还无法转换成perl模块 因为在很多地方都用到这个我也遇到了,所以自己也来个造轮子 http://bbs.chinaunix.net/viewthread.php?tid=895303&extra=page%3D1&page=1 不知道效率如何^_^
新修改base64表初始化工作谢谢思一克提醒
[ 本帖最后由 lovesaka 于 2007-2-5 21:24 编辑 ]
屁屁虫 回复于:2007-02-05 02:18:38
强人啊……不顶不行!
01072541 回复于:2007-02-05 09:55:57
请问这2个函数如何调用啊 比如我只提供一个字符串
langue 回复于:2007-02-05 09:58:52
引用:原帖由 01072541 于 2007-2-5 09:55 发表 请问这2个函数如何调用啊 比如我只提供一个字符串
函数已有声明:
char *decode(const char*,char **); char *encode(const char*,char **);
--
01072541 回复于:2007-02-05 10:02:45
但是我就一个字符串啊就一个参数 这函数需要有2个参数传入啊
01072541 回复于:2007-02-05 10:03:47
比如char *p; p = ewrfsdfsd; 举个例子给我看下,好不好,谢谢了
langue 回复于:2007-02-05 10:05:26
引用:原帖由 01072541 于 2007-2-5 10:02 发表 但是我就一个字符串啊就一个参数 这函数需要有2个参数传入啊
开一个缓冲区,用来存放目标数据。大小为原数据长度的 4/3 多一些,就可以了。
--
01072541 回复于:2007-02-05 10:06:14
是不是一个输入,一个输出啊 我懂了
langue 回复于:2007-02-05 10:07:12
引用:原帖由 01072541 于 2007-2-5 10:06 发表 是不是一个输入,一个输出啊 我懂了
是的。楼主在变量的命名上有自己的风格。
--
思一克 回复于:2007-02-05 10:08:10
decode函数中是每次都填BASE表?
langue 回复于:2007-02-05 10:20:17
--
通常是把预先计算好的 tab 放到全局数组里,这个叫 pre-computation
--
01072541 回复于:2007-02-05 10:27:36
int main() { char *p,*q; p="xygyqwg"; char en[20],de[20]; printf(encode(p,&en)); printf("/n"); q=en; printf(decode(q,&de)); printf("/n"); printf("end"); } 我这样可以吗??编码好像可以,就是不能解码?不知道为什么
langue 回复于:2007-02-05 10:36:31
引用:[font="Courier New"]/* LibTomCrypt, modular cryptographic library -- Tom St Denis * * LibTomCrypt is a library that provides various cryptographic * algorithms in a highly modular and flexible manner. * * The library is free for all purposes without any express * guarantee it works. * * Tom St Denis, [email]tomstdenis@gmail.com[/email], http://libtomcrypt.com */
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <assert.h>
int base64_encode(const unsigned char *, unsigned long, unsigned char *, unsigned long *);
int base64_decode(const unsigned char *, unsigned long, unsigned char *, unsigned long *);
static const char *codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/* error codes [will be expanded in future releases] */ enum { CRYPT_OK=0, /* Result OK */ CRYPT_ERROR, /* Generic Error */ CRYPT_NOP, /* Not a failure but no operation was performed */
CRYPT_INVALID_KEYSIZE, /* Invalid key size given */ CRYPT_INVALID_ROUNDS, /* Invalid number of rounds */ CRYPT_FAIL_TESTVECTOR, /* Algorithm failed test vectors */
CRYPT_BUFFER_OVERFLOW, /* Not enough space for output */ CRYPT_INVALID_PACKET, /* Invalid input packet given */
CRYPT_INVALID_PRNGSIZE, /* Invalid number of bits for a PRNG */ CRYPT_ERROR_READPRNG, /* Could not read enough from PRNG */
CRYPT_INVALID_CIPHER, /* Invalid cipher specified */ CRYPT_INVALID_HASH, /* Invalid hash specified */ CRYPT_INVALID_PRNG, /* Invalid PRNG specified */
CRYPT_MEM, /* Out of memory */
CRYPT_PK_TYPE_MISMATCH, /* Not equivalent types of PK keys */ CRYPT_PK_NOT_PRIVATE, /* Requires a private PK key */
CRYPT_INVALID_ARG, /* Generic invalid argument */ CRYPT_FILE_NOTFOUND, /* File Not Found */
CRYPT_PK_INVALID_TYPE, /* Invalid type of PK key */ CRYPT_PK_INVALID_SYSTEM,/* Invalid PK system specified */ CRYPT_PK_DUP, /* Duplicate key already in key ring */ CRYPT_PK_NOT_FOUND, /* Key not found in keyring */ CRYPT_PK_INVALID_SIZE, /* Invalid size input for PK parameters */
CRYPT_INVALID_PRIME_SIZE,/* Invalid size of prime requested */ CRYPT_PK_INVALID_PADDING /* Invalid padding on input */ };
#define LTC_ARGCHK(x) assert(x)
/** base64 Encode a buffer (NUL terminated) @param in The input buffer to encode @param inlen The length of the input buffer @param out [out] The destination of the base64 encoded data @param outlen [in/out] The max size and resulting size @return CRYPT_OK if successful */ int base64_encode(const unsigned char *in, unsigned long inlen, unsigned char *out, unsigned long *outlen) { unsigned long i, len2, leven; unsigned char *p;
LTC_ARGCHK(in != NULL); LTC_ARGCHK(out != NULL); LTC_ARGCHK(outlen != NULL);
/* valid output size ? */ len2 = 4 * ((inlen + 2) / 3); if (*outlen < len2 + 1) { *outlen = len2 + 1; return CRYPT_BUFFER_OVERFLOW; } p = out; leven = 3*(inlen / 3); for (i = 0; i < leven; i += 3) { *p++ = codes[(in[0] >> 2) & 0x3F]; *p++ = codes[(((in[0] & 3) << 4) + (in[1] >> 4)) & 0x3F]; *p++ = codes[(((in[1] & 0xf) << 2) + (in[2] >> 6)) & 0x3F]; *p++ = codes[in[2] & 0x3F]; in += 3; } /* Pad it if necessary... */ if (i < inlen) { unsigned a = in[0]; unsigned b = (i+1 < inlen) ? in[1] : 0;
*p++ = codes[(a >> 2) & 0x3F]; *p++ = codes[(((a & 3) << 4) + (b >> 4)) & 0x3F]; *p++ = (i+1 < inlen) ? codes[(((b & 0xf) << 2)) & 0x3F] : '='; *p++ = '='; }
/* append a NULL byte */ *p = '/0';
/* return ok */ *outlen = p - out; return CRYPT_OK; }
static const unsigned char map[256] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 62, 255, 255, 255, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 255, 255, 255, 254, 255, 255, 255, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 255, 255, 255, 255, 255, 255, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 };
/** base64 decode a block of memory @param in The base64 data to decode @param inlen The length of the base64 data @param out [out] The destination of the binary decoded data @param outlen [in/out] The max size and resulting size of the decoded data @return CRYPT_OK if successful */ int base64_decode(const unsigned char *in, unsigned long inlen, unsigned char *out, unsigned long *outlen) { unsigned long t, x, y, z; unsigned char c; int g;
LTC_ARGCHK(in != NULL); LTC_ARGCHK(out != NULL); LTC_ARGCHK(outlen != NULL);
g = 3; for (x = y = z = t = 0; x < inlen; x++) { c = map[in[x]&0xFF]; if (c == 255) continue; /* the final = symbols are read and used to trim the remaining bytes */ if (c == 254) { c = 0; /* prevent g < 0 which would potentially allow an overflow later */ if (--g < 0) { return CRYPT_INVALID_PACKET; } } else if (g != 3) { /* we only allow = to be at the end */ return CRYPT_INVALID_PACKET; }
t = (t<<6)|c;
if (++y == 4) { if (z + g > *outlen) { return CRYPT_BUFFER_OVERFLOW; } out[z++] = (unsigned char)((t>>16)&255); if (g > 1) out[z++] = (unsigned char)((t>>8)&255); if (g > 2) out[z++] = (unsigned char)(t&255); y = t = 0; } } if (y != 0) { return CRYPT_INVALID_PACKET; } *outlen = z; return CRYPT_OK; }[/font]
不过上面的代码也有问题,比如数据长度什么的还是用 size_t 类型比较好。
--
[ 本帖最后由 langue 于 2007-2-5 10:39 编辑 ]
熊猫烧香 回复于:2007-02-05 10:49:02
echo "blablabla"| openssl base64 -e(-d) 不行么?:mrgreen:
langue 回复于:2007-02-05 10:50:53
--
openssl enc -a -(e|d) 也可以。
--
熊猫烧香 回复于:2007-02-05 10:51:41
我记的没错的话perl里面也应该有相应的模块吧,不用自己动手编的。
lovesaka 回复于:2007-02-05 18:30:33
引用:原帖由 思一克 于 2007-2-5 10:08 发表 decode函数中是每次都填BASE表?
呵呵那肯定是要填的不然手功输入那么多字符太不现实了,而且这字符大多数都分开的搞不好掉一两个那就很麻烦 开始写的时候也用的是全局变量,结果中间掉了三个字符RST最后结果老是不对劲调试了半个多少时后来数编码表才发现少了几个字符 引用: 回复01072541 (飞冰) 但是我就一个字符串啊就一个参数 这函数需要有2个参数传入啊 int main() { char *p,*q; p="xygyqwg"; char en[20],de[20]; printf(encode(p,&en)); printf("/n"); q=en; printf(decode(q,&de)); printf("/n"); printf("end"); }
呵呵为了更加方便你只需定义一个指针把指针的地址传给函数的第二个参数就行了 它会为你分配解码后存放字符串的内存 你应该这样写
int main()
{
char *p="xygyqwg";
char *en,*de;
printf("[%s]=[%s]/n",p,encode(p,&en));
printf("[%s]=[%s]/n",en,decode(en,&de));
/*在后面用完后释放内存就行了*/
}
结果应该是这样的
minuit@SuSe:~> ./a.out
[xygyqwg]=[eHlneXF3Zw==]
[eHlneXF3Zw==]=[xygyqwg]
minuit@SuSe:~>
我想这样子会更好用些. 最后多谢版主加精^_^
lovesaka 回复于:2007-02-05 21:27:01
引用:原帖由 思一克 于 2007-2-5 10:08 发表 decode函数中是每次都填BASE表?
你的意思应该是这样子吧 看来开始把你的意思想错了^_^
|