C语言编程:编写一个函数base64加密

Python011

C语言编程:编写一个函数base64加密,第1张

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

const char *chlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

int encode_string(char* str, unsigned int length, char* stat) {

char s[103]

int i,j

unsigned temp

if(length <= 0) return 1

if(length > 100) return 2

str[length] = '\0'

strcpy(s,str)

while(strlen(s) % 3) strcat(s,"=")

for(i = 0,j = 0 s[i] i += 3,j += 4) {

temp = s[i]

temp = (temp << 8) + s[i + 1]

temp = (temp << 8) + s[i + 2]

stat[j + 3] = chlist[temp & 0X3F]

temp >>= 6

stat[j + 2] = chlist[temp & 0X3F]

temp >>= 6

stat[j + 1] = chlist[temp & 0X3F]

temp >>= 6

stat[j + 0] = chlist[temp & 0X3F]

}

stat[j] = '\0'

return 0

}

int Index(char ch) {

int i

for(i = 0 chlist[i] ++i) {

if(chlist[i] == ch)

return i

}

return -1

}

void decode_string(char *s, char *t) {

unsigned temp

int i,j,k,len = strlen(s)

if(len % 4) {

printf("无效数据。\n")

exit(2)

}

for(i = 0,j = 0 i <= len i += 4,j += 3) {

temp = 0

for(k = 0 k < 4 ++k)

temp = (temp << 6) + Index(s[i + k])

for(k = 2 k >= 0 --k) {

t[j + k] = temp & 0XFF

temp >>= 8

}

}

t[j + k] = '\0'

}

int main() {

char s[100] = "1a2a3s4dff5fj6u7M8B9P0O1U2"

char t[150],u[100]

printf("s = %s\n",s)

encode_string(s,strlen(s),t)

printf("t = %s\n",t)

decode_string(t,u)

printf("u = %s\n",u)

return 0

}

叶剑飞

*

*

*

* 使用说明:

* 命令行参数说明:若有“-d”参数,则为base64解码,否则为base64编码。

* 若有“-o”参数,后接文件名,则输出到标准输出文件。

* 输入来自标准输入stdin,输出为标准输出stdout。可重定向输入输出流。

*

*base64编码:输入任意二进制流,读取到文件读完了为止(键盘输入则遇到文件结尾符为止)。

*输出纯文本的base64编码。

*

*base64解码:输入纯文本的base64编码,读取到文件读完了为止(键盘输入则遇到文件结尾符为止)。

*输出原来的二进制流。

*

*/