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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include "f2c/fglExt.h"
char* base64_decode(const char* str);
char* base64_encode(const char* str);
int base64Encode(int);
int base64Decode(int);
char* base64_decode(const char* str){
unsigned char imap[79]={62,0,0,0,63,52,53,54,55,56,57,58,59,60,61,0,0,0,0,0,0,0,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,0,0,0,0,0,0,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};
int rest_count =0;
int buf_idx=0;
int len = strlen(str);
int flen = len;
int i;
while(str[flen-1]=='=')
flen--;
int buflen = flen*6/8+1;
unsigned char* buf = (unsigned char*) malloc(buflen);
memset(buf,'\\0',buflen);
for(i=0;i<flen;i++){
unsigned char c=imap[str[i]-43];
int mcount = rest_count ==0?-2:6-rest_count;
unsigned char c0 = (mcount>0?c>>mcount:c<<-mcount);
buf[buf_idx] = buf[buf_idx] | c0;
rest_count= mcount <0 ? -mcount : 8-mcount;
if(mcount>=0)
buf[++buf_idx]=c<<rest_count;
}
return buf;
}
char* base64_encode(const char* str){
char map[65]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int len =strlen(str);
int buflen = len * 8 / 6 + 4;//缺位补齐1 俩等号2 最后0-1位
unsigned char* buf = (unsigned char*)malloc(buflen);
memset(buf,'\\0',buflen);
char a [4];
int i;
int rest_count = 0;
int index = 0;
int buf_idx =0 ;
unsigned char last = 0;
for( i=0;i<len;i++){
unsigned char c = str[i];
a[index]= (last<<(6-rest_count))&63;
int get_count = 6-rest_count;
a[index] = a[index] | ( c >>(8-get_count));
a[index]=map[a[index]];
rest_count = 8-get_count;
last = c;
index = index==2?0:index+1;
if(index==0){
a[3]=map[c&63];
memcpy(buf+buf_idx,a,4);
buf_idx+=4;
rest_count=0;
last = 0;
}
}
if(index!=0){
a[index]= last<<(6-rest_count) & 63;
a[index]=map[a[index]];
memcpy(buf+buf_idx,a,index+1);
buf[buf_idx+index+1]='=';
buf[buf_idx+index+2]= rest_count ==2 ? '=':0;
}
return buf;
}
int base64Encode(int in_num){
const int sz = 5000;
char src[sz];
char *ret;
int *p;
assert(in_num==1);
// 取参数
popvchar(src,sz);
if (*src == '\\0') {
pushvchar("", 0);
return 1;
}
ret = base64_encode(src);
pushvchar(ret, strlen(ret));
return 1;
}
int base64Decode(int in_num){
const int sz = 5000;
char src[sz];
char *ret;
int *p;
assert(in_num == 1);
// 取参数
popvchar(src,sz);
if (*src == '\\0') {
pushvchar("", 0);
return 1;
}
ret = base64_decode(src);
pushvchar(ret, strlen(ret));
return 1;
}
|