/*3des加密 cbc pkcs5padding pkcs7padding 跟 pkcs5padding结构是一样的,8位iv以当前日期代替yymmdd 使用openssl库
@param 待加密明文
@param 加密密钥24位
return 加密后的密文*/
std::string CGetData::tdes_cbc_pkcs5_encrypt(const std::string &clearText, const std::string &key)
{
DES_cblock Key1, Key2, Key3;
memcpy(Key1, key.c_str(), 8);
memcpy(Key2, key.c_str() + 8, 8);
memcpy(Key3, key.c_str() + 16, 8);
DES_key_schedule SchKey1, SchKey2, SchKey3;
//用于得到当前日期作为iv 格式为 yyyymmdd
time_t now = time(0);
tm *ltm = localtime(&now);
std::string year = std::to_string(1900 + ltm->tm_year);
std::string month = std::to_string(1 + ltm->tm_mon);
if (month.size() == 1)
{
month.insert(month.begin(), '0');
}
std::string day = std::to_string(ltm->tm_mday);
if (day.size() == 1)
{
day.insert(day.begin(), '0');
}
std::string yearmonthday = year + month + day;
static unsigned char cbc_iv[8];
memcpy(cbc_iv, yearmonthday.data(), yearmonthday.size());
//初始化IV向量
std::string strCipherText;
DES_cblock keyEncrypt, ivec;
DES_set_key_unchecked(&Key1, &SchKey1); //设置密钥,且不检测密钥奇偶性
DES_set_key_unchecked(&Key2, &SchKey2);
DES_set_key_unchecked(&Key3, &SchKey3);
memcpy(ivec, cbc_iv, sizeof(cbc_iv));
// 循环加密,每8字节一次
const_DES_cblock inputText;
DES_cblock outputText;
std::vector<unsigned char> vecCiphertext;
unsigned char tmp[8];
for (int i = 0; i < clearText.size() / 8; i++)
{
memcpy(inputText, clearText.c_str() + i * 8, 8);
DES_ede3_cbc_encrypt(inputText, outputText, 8, &SchKey1, &SchKey2, &SchKey3, &ivec, DES_ENCRYPT);
memcpy(tmp, outputText, 8);
for (int j = 0; j < 8; j++)
vecCiphertext.push_back(tmp[j]);
}
if (clearText.size() % 8 != 0)
{
int tmp1 = clearText.size() / 8 * 8;
int tmp2 = clearText.size() - tmp1;
memset(inputText, (8 - tmp2), 8);
memcpy(inputText, clearText.c_str() + tmp1, tmp2);
}
else
{
memset(inputText, 8, 8);
}
// 加密函数
DES_ede3_cbc_encrypt(inputText, outputText, 8, &SchKey1, &SchKey2, &SchKey3, &ivec, DES_ENCRYPT);
memcpy(tmp, outputText, 8);
for (int j = 0; j < 8; j++)
vecCiphertext.push_back(tmp[j]);
strCipherText.clear();
strCipherText.assign(vecCiphertext.begin(), vecCiphertext.end());
//std::to_string(1);
printf("%s", strCipherText);
return strCipherText;
}
/*base64加密函数,加密结果每64位加个\n 使用openssl库
@param 待加密字符串
return 返回加密后的字符串*/
std::string CGetData::base64_encodestring(const std::string &text)
{
EVP_ENCODE_CTX ectx;
int size = text.size() * 2;
size = size > 64 ? size : 64;
unsigned char* out = (unsigned char*)malloc(size);
int outlen = 0;
int tlen = 0;
printf("text.size = %d\n", text.size());
EVP_EncodeInit(&ectx);
EVP_EncodeUpdate(&ectx, out, &outlen, (const unsigned char*)text.c_str(), text.size());
tlen += outlen;
EVP_EncodeFinal(&ectx, out + tlen, &outlen);
tlen += outlen;
std::string str((char*)out, tlen);
free(out);
return str;
}