Linux环境下使用openssl库的base64进行加解密

openssl库中的加密工具可以对数据进行简单的加解密,代码如下所示:

 1 #include <stdio.h>
 2 #include <string.h>
 3 #include <unistd.h>
 4 
 5 #include <openssl/pem.h>
 6 #include <openssl/bio.h>
 7 #include <openssl/evp.h>
 8 
 9 int base64_encode(char *in_str, int in_len, char *out_str)
10 {
11     BIO *b64, *bio;
12     BUF_MEM *bptr = NULL;
13     size_t size = 0;
14 
15     if (in_str == NULL || out_str == NULL)
16         return -1;
17 
18     b64 = BIO_new(BIO_f_base64());
19     bio = BIO_new(BIO_s_mem());
20     bio = BIO_push(b64, bio);
21 
22     BIO_write(bio, in_str, in_len);
23     BIO_flush(bio);
24 
25     BIO_get_mem_ptr(bio, &bptr);
26     memcpy(out_str, bptr->data, bptr->length);
27     out_str[bptr->length] = '\0';
28     size = bptr->length;
29 
30     BIO_free_all(bio);
31     return size;
32 }
33 
34 int base64_decode(char *in_str, int in_len, char *out_str)
35 {
36     BIO *b64, *bio;
37     BUF_MEM *bptr = NULL;
38     int counts;
39     int size = 0;
40 
41     if (in_str == NULL || out_str == NULL)
42         return -1;
43 
44     b64 = BIO_new(BIO_f_base64());
45     BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
46 
47     bio = BIO_new_mem_buf(in_str, in_len);
48     bio = BIO_push(b64, bio);
49 
50     size = BIO_read(bio, out_str, in_len);
51     out_str[size] = '\0';
52 
53     BIO_free_all(bio);
54     return size;
55 }

验证方式:

echo “str” | openssl base64

使用linux下的openssl命令行进行验证。

转载于:https://www.cnblogs.com/hancq/p/5535869.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值