树莓派openssl实践
安装openssl源码
安装地址:openssl-3.0.0
建立两个文件夹,分别放置OpenSSL的源码和安装路径:mkdir rocopensslsrc rocopenssl
使用scp D:/树莓派/openssl-3.0.0.tar.gz root@192.168.184.124:/root/rocopenssl
将源码传输至树莓派中
解压源代码到rocopensslsrc文件夹:tar -zxvf openssl-3.0.0.tar.gz -C /root/rocopensslsrc
配置编译安装路径(/root/rocopenssl),和openEuler系统默认的不同。
cd rocopensslsrc/openssl-3.0.0
./config --prefix=/root/rocopenssl
编译(make时间稍长,耐心等待),测试、安装,其中测试步骤可选:
make
make test
make install
make了快一个小时
查看openssl
使用
openssl version
查看openssl版本
openssl help
查看openssl帮助文档:
openssl计算摘要
把besti放到besti.txt文件中,计算文件的摘要:
echo "besti" >> besti.txt
OpenSSL编程
简单测试,编写一个测试代码test_openssl.c:
#include <stdio.h>
#include <openssl/evp.h>
int main(){
OpenSSL_add_all_algorithms();
return 0;
}
使用以下指令编译:gcc -o to test_openssl.c -I /root/rocopenssl/include -L /root/rocopenssl/lib -lcrypto -lpthread
<openssl/evp.h>头文件缺失,openeuler系统传统艺能了。
sudo yum install openssl-devel
使用该指令安装相关文件:
编译成功:
执行./to;echo $?
,结果打印0.
BASE64算法
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
void tEVP_Encode()
{
EVP_ENCODE_CTX *ctx;
ctx = EVP_ENCODE_CTX_new();
unsigned char in[1024];
int inl;
char out[2048]={0};
int outl;
FILE *infp;
FILE *outfp;
infp = fopen("test.dat","rb");
if(infp == NULL)
{
printf("Open File \"Test.dat\" for Read Err.\n");
return;
}
outfp = fopen("test.txt","w");
if(outfp == NULL)
{
printf("Open File \"test.txt\" For Write Err.\n");
return;
}
EVP_EncodeInit(ctx);
printf("file\"Test.dat\" after Base64 coding:\n");
while(1)
{
inl = fread(in,1,1024,infp);
if(inl <= 0)
break;
EVP_EncodeUpdate(ctx,out,&outl,in,inl);
fwrite(out,1,outl,outfp);
printf("%s",out);
}
EVP_EncodeFinal(ctx,out,&outl);
fwrite(out,1,outl,outfp);
printf("%s",out);
fclose(infp);
fclose(outfp);
printf("file \"Test.dat\" Base64 coding is finish,save to \"test.txt\"文件.\n\n\n");
}
void tEVP_Decode()
{
EVP_ENCODE_CTX *ctx;
ctx = EVP_ENCODE_CTX_new();
char in[1024];
int inl;
unsigned char out[1024];
int outl;
FILE *infp;
FILE *outfp;
infp = fopen("test.txt","r");
if(infp == NULL)
{
printf("Open File \"Test.txt\" for Read Err.\n");
return;
}
outfp = fopen("test-1.dat","wb");
if(outfp == NULL)
{
printf("Open File \"test-1.txt\" For Write Err.\n");
return;
}
EVP_DecodeInit(ctx);
printf("start file \"Test.txt\" Base64 decoding...\n\n");
while(1)
{
inl = fread(in,1,1024,infp);
if(inl <= 0)
break;
EVP_DecodeUpdate(ctx,out,&outl,in,inl);
fwrite(out,1,outl,outfp);
}
EVP_DecodeFinal(ctx,out,&outl);
fwrite(out,1,outl,outfp);
fclose(infp);
fclose(outfp);
printf("file \"Test.txt\" Base64 decoding is finish,save as \"test-1.dat\"\n\n\n");
}
int main()
{
tEVP_Encode();
tEVP_Decode();
return 0;
}
使用gcc -o testbase64 testbase64.c -I /root/rocopenssl/include -L /root/rocopenssl/lib -lcrypto -lpthread
编译成功:
运行截图: