您的位置:首页 > 运维架构 > Linux

Linux下用管道执行base64命令加密解密字符串

2016-12-29 16:42 190 查看
Linux下用管道执行base64命令加密解密字符串

直接上实例代码,用base64加密解密字符串。

test.c 文件:

#include <stdio.h>
#include <string.h>
#include <errno.h>

#define MAXL_BASE64CODE 1024

int base64_encode(const char* str, char* out)
{
int n=0;
FILE* fp=NULL;
char buf[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!";
char buf1[MAXL_BASE64CODE];
char buf2[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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: