实验步骤:
一,下载并安装gcc,openssl,(OpenSSL 是一个安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。 )
yum -y install gcc
wget https://www.openssl.org/source/openssl-1.0.2h.tar.gz
解压openssl
tar zxf openssl-1.0.2h.tar.gz
二,把openssl移动到 /usr/local目录下
mv openssl /usr/local
三,在/usr/local、openssl目录下创建一个文件 enc_dec.c用来存储算法程序
四,把所需要的规则写到makefile文件中
LIB=-L/usr/local/lib -lcrypto
all:${OBJ}
cc ${OBJ}-o app.exe ${LIB}
${OBJ}:enc_dec.c
cc -c enc_dec.c -o ${OBJ}
.PHONY:clean
clean:
rm ${OBJ}
~
五,编译算法程序: cc enc_dec.c -o app.exe -L/usr/local/lib -lcrypto没有报错,然后用make检验也没有报错。
六,执行./app.exe文件
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <openssl/aes.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
void HexCode(unsigned char* data, int len)
{
int i = 0;
for(; i < len; i++)
printf("%02x", (unsigned int)data[i]);
printf(" ");
}
int main()
{
const int len = 3;
char userkey[AES_BLOCK_SIZE];
unsigned char *data = malloc(AES_BLOCK_SIZE*len);
unsigned char *cipher = malloc(AES_BLOCK_SIZE*len);
unsigned char *plain = malloc(AES_BLOCK_SIZE*len);
int i;
AES_KEY key;
memset((void*)userkey, 0, AES_BLOCK_SIZE);
memset((void*)data, 0, AES_BLOCK_SIZE*len);
memset((void*)cipher, 0, AES_BLOCK_SIZE*len);
memset((void*)plain, 0, AES_BLOCK_SIZE*len);
strcpy(userkey, "userkey");
strcpy(data, "original text");
printf("original text: ");
HexCode(data, AES_BLOCK_SIZE*len);
AES_set_encrypt_key(userkey, 128, &key);
for(i = 0; i < len; i++)
AES_ecb_encrypt(data+i*AES_BLOCK_SIZE, cipher+i*AES_BLOCK_SIZE, &key, AES_ENCRYPT);
printf("cipher: ");
HexCode(cipher, AES_BLOCK_SIZE*len);
AES_set_decrypt_key(userkey, 128, &key);
for(i = 0; i < len; i++)
AES_ecb_encrypt(cipher+i*AES_BLOCK_SIZE, plain+i*AES_BLOCK_SIZE, &key, AES_DECRYPT);
printf("plain: ");
HexCode(plain, AES_BLOCK_SIZE*len);
free(data);
free(cipher);
free(plain);
return 0;
}
实现结果:
疑难小结:一开始输入 cc enc_dec.c -o app.exe -L/usr/local/lib -lcrypto的时候出现如下错误
原因是:需要和OpenSSL链接的文件(库和头文件)在你Linux平台上缺少
解决办法:centos用命令$ sudo yum install openssl-devel
ubuntu用$ sudo apt-get install libssl-dev.