Linux下用管道执行base64命令加密解密字符串。
直接上实例代码,用base64加密解密字符串。
test.c 文件:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define MAXL_BASE64CODE1024
int base64_encode(const char* str, char* out)
{
int n=0;
FILE* fp=NULL;
charbuf[256];
sprintf(buf, "echo %s | base64", str);
if(NULL == (fp=popen(buf,"r")))
{
fprintf(stderr, "execute command failed: %s", strerror(errno));
return -1;
}
if(NULL == fgets(out, MAXL_BASE64CODE, fp))
{
pclose(fp);
return -1;
}
n = strlen(out);
if('\n' == out[n-1])
out[n-1] = 0; // 去掉base64命令输出的换行符
pclose(fp);
return 0;
}
int base64_decode(const char* str, char* out)
{
int n=0;
FILE* fp=NULL;
char buf[256];
sprintf(buf, "echo %s | base64 -d", str);
if(NULL == (fp=popen(buf, "r")))
{
fprintf(stderr, "execute command failed: %s", strerror(errno));
return -1;
}
if(NULL == fgets(out, MAXL_BASE64CODE, fp))
{
pclose(fp);
return -1;
}
n = strlen(out);
if('\n' == out[n-1])
out[n-1] = 0; // 去掉base64命令输出的换行符
pclose(fp);
return 0;
}
int main()
{
char* str="Hello World!";
charbuf1[MAXL_BASE64CODE];
charbuf2[MAXL_BASE64CODE];
printf("%s\n", str);
base64_encode(str, buf1); // 加密
printf("%s\n", buf1);
base64_decode(buf1, buf2); // 解密
printf("%s\n", buf2);
return 0;
}
执行结果:
$ ./test
Hello World!
SGVsbG8gV29ybGQhCg==
Hello World!