std::string EncryptByOpenSSL(const std::string& str, const EVP_CIPHER* evp,
const unsigned char* key, const unsigned char* iv, bool bEncrypt)
{
std::string strCipher1;
{
BIO* bio = BIO_new(BIO_f_cipher());
BIO* mio = BIO_new(BIO_s_mem());
do
{
if (NULL == bio || NULL == mio)
{
break;
}
const EVP_CIPHER* _evp = evp ? evp : EVP_aes_256_cbc();
const unsigned char* _key = key ? key : (const unsigned char*)"00001111";
const unsigned char* _iv = iv ? iv : (const unsigned char*)"00001111";
BIO_set_cipher(bio, _evp, _key, _iv, bEncrypt ? 1 : 0);
bio = BIO_push(bio, mio);
BIO_write(bio, str.c_str(), str.size());
BIO_flush(bio);
{
BUF_MEM* ptr = NULL;
BIO_get_mem_ptr(mio, &ptr);
if (ptr)
{
strCipher1.append(ptr->data, ptr->length);
}
}
} while (0);
if (bio)
{
BIO_free(bio);
}
if (mio)
{
BIO_free(mio);
}
}
return strCipher1;
}
void Test_Encrypt()
{
int index = 0;
auto _test = [&](const EVP_CIPHER* evp)
{
printf("============================ %d =========================\n", index++);
char* key = NULL;
char* iv = NULL;
std::string str = "1111111 1111111 1111111 1111111 1111111 1111111\n\n";
std::cout << "明文:" << str << std::endl;
std::string strTmp = EncryptByOpenSSL(str, evp, (unsigned char*)key, (unsigned char*)iv, true);
std::cout << "密文:" << std::endl;
for (int ii = 0; ii < strTmp.size(); ++ii)
{
printf("%02x ", (unsigned char)strTmp[ii]);
if (ii % 8 == 7)
{
printf("\n");
}
}
printf("\n");
std::string strTmp1 = EncryptByOpenSSL(strTmp, evp, (unsigned char*)key, (unsigned char*)iv, false);
std::cout << "解密之后的明文:" << strTmp1 << std::endl;
std::cout << "=====================================================" << std::endl << std::endl;
};
_test(EVP_des_ecb());
_test(EVP_des_ede());
_test(EVP_des_ede3());
_test(EVP_des_ede_ecb());
_test(EVP_des_ede3_ecb());
_test(EVP_des_cfb64());
_test(EVP_des_cfb1());
_test(EVP_des_cfb8());
_test(EVP_des_ede_cfb64());
_test(EVP_des_ede3_cfb64());
_test(EVP_des_ede3_cfb1());
_test(EVP_des_ede3_cfb8());
_test(EVP_des_ofb());
_test(EVP_des_ede_ofb());
_test(EVP_des_ede3_ofb());
_test(EVP_des_cbc());
_test(EVP_des_ede_cbc());
_test(EVP_des_ede3_cbc());
_test(EVP_desx_cbc());
_test(EVP_camellia_256_cfb128());
_test(EVP_seed_ofb());
_test(EVP_rc2_40_cbc());
_test(EVP_aes_256_cbc());
_test(EVP_aes_192_ofb());
_test(EVP_aes_192_ofb());
_test(EVP_seed_ofb());
_test(EVP_cast5_cfb64());
_test(EVP_aes_128_cbc_hmac_sha256());
_test(EVP_aes_192_ccm());
_test(EVP_bf_ofb());
_test(EVP_idea_ofb());
}