des对称算法
源代码如下:
#include <string.h>
#include <openssl/evp.h>
void show_hex(
unsigned char * s,
int len)
{
for(
int i=
0; i<len; i++)
{
printf(
"x",s[i]);
if(
19 == i %
20)
printf(
"\n");
}
printf(
"\n\n");
}
int main()
{
int ret,which=
1;
EVP_CIPHER_CTX ctx;
const EVP_CIPHER *cipher;
unsigned char key[
24],iv[
8],in[
100],out[
108],de[
100];
int i,len,inl,outl,total=
0;
for(i=
0;i<
24;i++)
{
memset(&key[i],i,
1);
}
for(i=
0;i<
8;i++)
{
memset(&iv[i],i,
1);
}
for(i=
0;i<
100;i++)
{
memset(&in[i],i+
1,
1);
}
EVP_CIPHER_CTX_init(&ctx);
printf(
"please select :\n");
printf(
"1: EVP_des_ede3_ofb\n");
printf(
"2: EVP_des_ede3_cbc\n");
scanf(
"%d",&which);
if(which==
1)
cipher=EVP_des_ede3_ofb();
else
cipher=EVP_des_ede3_cbc();
printf(
"原文:\n");
show_hex(in,
100);
ret=EVP_EncryptInit_ex(&ctx,cipher,NULL,key,iv);
if(ret!=
1)
{
printf(
"EVP_EncryptInit_ex err1!\n");
return -
1;
}
inl=
50;
len=
0;
EVP_EncryptUpdate(&ctx,out+len,&outl,in,inl);
len+=outl;
EVP_EncryptUpdate(&ctx,out+len,&outl,in+
50,inl);
len+=outl;
EVP_EncryptFinal_ex(&ctx,out+len,&outl);
len+=outl;
printf(
"加密结果长度: %d\n",len);
printf(
"加密结果:\n");
show_hex(out, len);
EVP_CIPHER_CTX_cleanup(&ctx);
EVP_CIPHER_CTX_init(&ctx);
ret=EVP_DecryptInit_ex(&ctx,cipher,NULL,key,iv);
if(ret!=
1)
{
printf(
"EVP_DecryptInit_ex err1!\n");
return -
1;
}
total=
0;
EVP_DecryptUpdate(&ctx,de+total,&outl,out,
44);
total+=outl;
EVP_DecryptUpdate(&ctx,de+total,&outl,out+
44,len-
44);
total+=outl;
ret=EVP_DecryptFinal_ex(&ctx,de+total,&outl);
total+=outl;
printf(
"解密结果长度: %d\n",total);
printf(
"解密结果:\n");
show_hex(de, total);
if(ret!=
1)
{
EVP_CIPHER_CTX_cleanup(&ctx);
printf(
"EVP_DecryptFinal_ex err\n");
return -
1;
}
if((total!=
100) || (
memcmp(de,in,
100)))
{
printf(
"err!\n");
return -
1;
}
EVP_CIPHER_CTX_cleanup(&ctx);
printf(
"test ok!\n");
return 0;
}
编译提示:
需要包含OpenSSL include 头文件目录需要引入OpenSSL 库(libeay32.lib)。
运行结果:
注意事项
在运行EVP_des_ede3_cbc 算法时,运行结束时,会出现错误: Run-Time Check Failure #2 - Stack around the variable 'de' was corrupted. 修复办法: ref: http://www.cnblogs.com/flysnail/archive/2011/09/21/2184114.html
配置属性->c/c++->代码生成->基本运行时检查 为 默认值 就不会报该异常.
转载请注明原文地址: https://ju.6miu.com/read-600327.html