資源簡介
OpenSSL 1.1.1 新特性: 全面支持國密SM2/SM3/SM4加密算法,最近的項目涉及到國密,前期已經完成了SM2算法,近期測試了SM4。代碼附上。vs2017親測通過。支持ECB、CBC 。采用自己打補丁的方式。
代碼片段和文件信息
#define?CRTDBG_MAP_ALLOC
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#include??
#include??
#include?
#include?
#include??
#include??
#include?jects.h>?
#include??
#include??
#include?
#include?
#include?
#define?SM2_DEFAULT_USERID?“1234567812345678“
char?*?OpensslGetLastErr()
{
ERR_load_ERR_strings();
ERR_load_crypto_strings();
unsigned?long?ulErr?=?ERR_get_error();
char?szErrMsg[1024]?=?{?0?};
char?*pTmp?=?NULL;
pTmp?=?ERR_error_string(ulErr?szErrMsg);
return?pTmp;
}
int?addpadding(char?*in?int?inLenint?paddingLen?char?*out?int?*outLen)
{
char?tmpPadding[16?+?1]?=?{?0?};
int?tmpPaddingLen?=?-1;
char?tmpOut[8192?+?16?+?1]?=?{?0?};
int??tmpOutLen?=?-1;
if?(paddingLen?%8?!=?0?||?inLen?<=?0)
{
return?-1;
}
tmpOutLen?=?0;
tmpPaddingLen?=?paddingLen?-?(inLen?%?paddingLen?==?0???0?:?inLen?%?16);
memset(tmpPadding?tmpPaddingLen?tmpPaddingLen);
memcpy(tmpOut?in?inLen);
tmpOutLen?+=?inLen;
memcpy(tmpOut?+?tmpOutLen?tmpPadding?tmpPaddingLen);
tmpOutLen?+=?tmpPaddingLen;
memcpy(out?tmpOut?tmpOutLen);
*outLen?=?tmpOutLen;
return?0;
}
int??unaddpadding(char?*in?int?inLen?char?*out?int?*outLen)
{
if?(inLen?%?8?!=?0?||?inLen?<=?0)
{
return?-1;
}
memcpy(out?in?inLen-?in[inLen?-?1]);
*outLen?=?inLen?-?in[inLen?-?1];
return?0;
}
int?sm4_encrypt(char?*keyint?keyLenchar?*in?int?inLen?char?*out?int?*outLenint?modechar?*ivint?ivLen)
{
int?nRet?=?-1;
char?tmpIn[8192?+?1]?=?{?0?};
int??tmpInLen?=?0;
char?tmpOut[8192?+?16?+?1]?=?{?0?};
int??tmpOutLen?=?0;
int??tmpLen?=?0;
EVP_CIPHER_CTX?*ctx;
if?(inLen?<=0?||?in?==?NULL?)
{
return?-1;
}
if?(?keyLen?!=?16?||?key?==?NULL)
{
return?-2;
}
nRet?=?addpadding(in?inLen?16?tmpIn?&tmpInLen);
if?(nRet?!=?0?||?tmpInLen?%?16?!=?0)
{
return?-3;
}
ctx?=?EVP_CIPHER_CTX_new();
if?(ctx?==?NULL)
{
return?-4;
}
if?(mode==0)
{
if?(ivLen?!=?16?||?iv?==?NULL)
{
return?-1;
}
nRet?=?EVP_EncryptInit_ex(ctx?EVP_sm4_cbc()?NULL?key?iv);
}
else
{
nRet?=?EVP_EncryptInit_ex(ctx?EVP_sm4_ecb()?NULL?key?NULL);
}
if?(nRet?!=?1)
{
EVP_CIPHER_CTX_free(ctx);
return?-?5;
}
EVP_CIPHER_CTX_set_padding(ctx?0);
nRet?=?EVP_EncryptUpdate(ctx?tmpOut?&tmpOutLen?tmpIn?tmpInLen);
if?(nRet?!=?1)
{
EVP_CIPHER_CTX_free(ctx);
return?-6;
}
tmpLen?+=?tmpOutLen;
nRet?=?EVP_EncryptFinal_ex(ctx?tmpOut+tmpOutLen?&tmpOutLen);
if?(nRet?!=?1)
{
EVP_CIPHER_CTX_free(ctx);
return?-7;
- 上一篇:Dalsa Camerali
nk相機采集代碼 - 下一篇:基于verilog的小數分頻
評論
共有 條評論