des-ecb模式 Key 必须是 64位
加密文字不足8位少1位补0x01 2位补 0x02 0x02 3位补 0x03 0x03 0x03
以上是标准ecb padding #5
String __stdcall EnDesECB(String strWM,String strKEY)
{
unsigned char pad;
unsigned char *data;
unsigned char tmp[8]="";
unsigned char in[EVP_MAX_KEY_LENGTH]="";
if(!strWM.IsEmpty())
data = strWM.c_str(); /* 明文 */
else
data = "11111111";
String strResult = "";
int data_len ,data_rest,len,key_len;
unsigned char *src = NULL; /* 补齐后的明文 */
// 分析补齐明文所需空间及补齐填充数据 */
data_len = strlen((const char*)data);
data_rest = data_len % 8;
if (data_rest != 0 )
pad = 8 - data_rest;
else
pad = 0;
len = data_len + (8 - data_rest);
src = (unsigned char*) malloc(len);
if (NULL != src )
{
int count;
int i;
/* 构造补齐后的加密内容 */
memset(src, 0, len);
memcpy(src, data, data_len);
memset(src + data_len, pad, 8 - data_rest);
// 初始化秘钥
DES_key_schedule ks = InitKey(strKEY.c_str());
/* 循环加密/解密,每8字节一次 */
count = len / 8;
for (i = 0; i < count; i++)
{
//memset(tmp, 0, ;
//memset(in , 0, ;
//memset(out, 0, ;
memcpy(tmp, src + 8 * i, 8);
/* 加密 */
DES_ecb_encrypt((const_DES_cblock*)tmp, (DES_cblock*)(in + 8 * i), &ks, DES_ENCRYPT);
}
}
for (int i = 0; i < (int)strlen(in); i++)
{
strResult += IntToHex(in[i],2);
}
if (NULL != src)
{
free(src);
src = NULL;
}
return strResult;
}
String __stdcall DeDesECB(String strMW,String strKEY)
{
unsigned char WM[EVP_MAX_KEY_LENGTH]="";
unsigned char out[EVP_MAX_KEY_LENGTH]="";
int mw_len,len;
String strResult="";
DES_key_schedule ks = InitKey(strKEY.c_str());
HexToBin(strMW.c_str(),WM,strMW.Length());
len = strlen(WM);
if (len)
{
int count;
int i;
// 循环解密,每8字节一次
count = len / 8 ;
for (i = 0; i < count; i++)
{ // 解密
DES_ecb_encrypt((const_DES_cblock*)(WM + 8 * i), (DES_cblock*)(out + 8 * i), &ks, DES_DECRYPT);
}
}
for (unsigned int i =0; i < strlen(out); i++)
{
if (int(out[i]) < 8 )
out[i] = 0;
}
strResult = String().sprintf(out);
return strResult;
}
DES_key_schedule InitKey(String strKey)
{
unsigned char *k; /* 原始密钥 */
unsigned char key[EVP_MAX_KEY_LENGTH]; /* 补齐后的密钥 */
unsigned char block_key[8]="";
unsigned char tmpkey[8]="11111111";
DES_key_schedule ks;
if (strKey.IsEmpty() || strKey.Length() < 8)
{
//后加随机生成
k = tmpkey;
}
else
{
k = strKey.c_str();
}
/* 构造补齐后的密钥 */
int key_len = strlen((const char*)k);
memcpy(key, k, key_len);
memset(key + key_len, 0x00, EVP_MAX_KEY_LENGTH - key_len);
/* 密钥置换 */
memset(block_key, 0, sizeof(block_key));
memcpy(block_key, key + 0, 8);
DES_set_key_unchecked((const_DES_cblock*)block_key, &ks);
return ks;
}