openssl程式設計
測試代碼
#include <stdio.h>
#include <openssl/evp.h>
int main(){
OpenSSL_add_all_algorithms();
return 0;
}
編譯時出現錯誤:

原因:你嘗試編譯的程式使用OpenSSL,但是需要和OpenSSL連結的檔案(庫和頭檔案)在你Linux平台上缺少。
解決方法:安裝OpenSSL開發包
sudo dnf install openssl-devel
再次嘗試編譯,成功。
base64算法
測試代碼:
#include <stdio.h>
#include <string.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
//Base64編碼
void tEVP_Encode()
{
EVP_ENCODE_CTX *ctx;
ctx = EVP_ENCODE_CTX_new(); //EVP編碼結構體
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);//Base64編碼初始化
printf("檔案\"Test.dat\" Base64編碼後為:\n");
//循環讀取原文,并調用EVP_EncodeUpdate計算Base64編碼
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("對檔案\"Test.dat\" Base64編碼完成,儲存到\"test.txt\"檔案.\n\n\n");
}
//Base64解碼
void tEVP_Decode()
{
EVP_ENCODE_CTX *ctx;
ctx = EVP_ENCODE_CTX_new(); //EVP編碼結構體
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);//Base64解碼初始化
printf("開始對檔案\"Test.txt\" Base64解碼...\n\n");
//循環讀取原文,并調用EVP_DecodeUpdate進行Base64解碼
while(1)
{
inl = fread(in,1,1024,infp);
if(inl <= 0)
break;
EVP_DecodeUpdate(ctx,out,&outl,in,inl);//Base64解碼
fwrite(out,1,outl,outfp);//輸出到檔案
}
EVP_DecodeFinal(ctx,out,&outl);//完成解碼,輸出最後的資料。
fwrite(out,1,outl,outfp);
fclose(infp);
fclose(outfp);
printf("對檔案\"Test.txt\" Base64解碼完成,儲存為\"test-1.dat\"\n\n\n");
}
int main()
{
tEVP_Encode();
tEVP_Decode();
return 0;
}
編譯結果如下:編譯不支援gbk,是以删除掉将源碼編碼成gbk即可
通過echo指令寫二進制檔案,參考如下