實驗步驟:html
一,下載並安裝gcc,openssl,(OpenSSL 是一個安全套接字層密碼庫,囊括主要的密碼算法、經常使用的密鑰和證書封裝管理功能及SSL協議,並提供豐富的應用程序供測試或其它目的使用。 )算法
yum -y install gccubuntu
wget https://www.openssl.org/source/openssl-1.0.2h.tar.gzcentos
解壓openssl安全
tar zxf openssl-1.0.2h.tar.gz app
二,把openssl移動到 /usr/local目錄下測試
mv openssl /usr/localspa
三,在/usr/local、openssl目錄下建立一個文件 enc_dec.c用來存儲算法程序htm
四,把所須要的規則寫到makefile文件中blog
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("\n");
}
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:\n");
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:\n");
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:\n");
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.