openssldescbc算法c++版
#include <iostream>
#include <string>
#include <vector>
#include <openssl/des.h>
#include "cryptotest.h"
using namespace std; //STL庫
static unsigned char cbc_iv[8] = {'0', '1', 'A', 'B', 'a', 'b', '9', '8'};
//初始化IV向量
string DES_Encrypt(const string cleartext, const string key, CRYPTO_MODE mode)
{
string strCipherText;
switch (mode) {
case GENERAL:
case CBC: //選擇CBC模式
{
DES_cblock keyEncrypt, ivec;
memset(keyEncrypt, 0, 8);
if (key.length() <= 8)
memcpy(keyEncrypt, key.c_str(), key.length());
else
memcpy(keyEncrypt, key.c_str(), 8);
DES_key_schedule keySchedule; //密鑰表
DES_set_key_unchecked(&keyEncrypt, &keySchedule); //設置密鑰,且不檢測密鑰奇偶性
memcpy(ivec, cbc_iv, sizeof(cbc_iv));
int iLength = cleartext.length() % 8 ? (cleartext.length() / 8 + 1) * 8 : cleartext.length();
unsigned char* tmp = new unsigned char[iLength + 16];
memset(tmp, 0, iLength);
DES_ncbc_encrypt((const unsigned char*)cleartext.c_str(), tmp, cleartext.length()+1, &keySchedule, &ivec, DES_ENCRYPT); //加密
strCipherText = (char*)tmp;
delete [] tmp;
}
break;
}