openssl的安装
在使用c语言库调用openssl的时候要先安装,因为安装的时候才会将库放到系统中供程序调用.
1
2
3
|
/usr/local/bin
/usr/local/lib
/usr/local/include
|
把这个安装好后会将与openssl相关的头文件放到/usr/local/include中,这样在编写程序的时候调用才能成功.
demo
代码:
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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/aes.h>
#define AESKEY "df98b715d5c6ed2b25817b6f255411a1" //HEX密钥
#define AESIV "2841ae97419c2973296a0d4bdfe19a4f" //HEX初始向量
//将文本形式的HEX串进行转换
unsigned char* str2hex(char *str)
{
unsigned char *ret = NULL;
int str_len = strlen(str);
int i = 0;
// assert((str_len%2) == 0);
ret = (char *)malloc(str_len/2);
for (i =0;i < str_len; i = i+2 )
{
sscanf(str+i,"%2hhx",&ret[i/2]);
}
return ret;
}
int main()
{
AES_KEY encryptkey;
AES_KEY decryptkey;
unsigned char *key;
unsigned char *stdiv;
key = str2hex(AESKEY);
stdiv = str2hex(AESIV);
AES_set_encrypt_key(key,128,&encryptkey);
AES_set_decrypt_key(key,128,&decryptkey);
unsigned char plain_text [32];
memcpy(plain_text, "AES encrypt in openssl demo", 27);
memset(plain_text + 27, 0, 5);
//需要将加密区块长度填充为16字节整数倍,此处使用zero-padding,即末尾全用0填充
printf("plain_text: ");
for(int i = 0; i < 32; i++)
{
printf("%02X ", plain_text[i]);
}
printf("\n" );
unsigned char encrypted_text [32];
memset(encrypted_text, 0, 32);
unsigned char tmpiv[16];
memcpy(tmpiv, stdiv, 16);
AES_cbc_encrypt(plain_text, encrypted_text, 32, &encryptkey, tmpiv, AES_ENCRYPT);
//初始向量这个参数每次使用都会将其改变,有兴趣的话可以把调用前后这个地址下的内容打印出来。所以如果要多次加密且每次使用固定的初始向量,可以先用tmpiv接收
printf("encrypted_text: " );
for(int i = 0; i < 32; i++)
{
printf("%02X ", encrypted_text[i]);
}
printf("\n" );
unsigned char decrypted_text [32];
memset(decrypted_text, 0, 32);
memcpy(tmpiv, stdiv, 16);
AES_cbc_encrypt(encrypted_text, decrypted_text, 32, &decryptkey, tmpiv, AES_DECRYPT);
printf("decrypted_text: " );
for(int i = 0; i < 32; i++)
{
printf("%02X ", decrypted_text[i]);
}
printf("\n" );
return 0;
}
|
编译时出现如下类似错误:
1
2
3
4
5
6
|
aes.c:(.text.startup+0x24d):对‘RAND_pseudo_bytes’未定义的引用
aes.c:(.text.startup+0x25f):对‘RAND_pseudo_bytes’未定义的引用
aes.c:(.text.startup+0x362):对‘AES_set_encrypt_key’未定义的引用
aes.c:(.text.startup+0x388):对‘AES_cbc_encrypt’未定义的引用
aes.c:(.text.startup+0x468):对‘AES_set_decrypt_key’未定义的引用
aes.c:(.text.startup+0x486):对‘AES_cbc_encrypt’未定义的引用
|
链接库需要手动指定,编译例子为:
1
|
gcc main.c -lssl -lcrypto -ldl -o main
|
编译完成后运行时出现如下错误:
1
|
openssl: error while loading shared libraries: libcrypto.so.3: cannot open shared object file: No such file or directory
|
需要在/etc/ld.so.conf.d/libc.conf 文件中添加 /usr/local/lib64, 因为在安装的时候一些动态库都放入了这个文件夹中,但它并不在可搜索的库列表中. 添加完该命令后还要更新一下: /sbin/ldconfig -v 才能生效
命令总结:
1
2
|
/etc/ld.so.conf.d/libc.conf #在这个文中添加: /usr/local/lib64
/sbin/ldconfig -v # 更新搜索列表
|