openssldescbc算法c++版

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;  
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章