openssl rc5 ecb模式

ECB(Electronic Code Book)/電碼本模式
原理非常簡單數據按照8個字節一段進行加密或解密得到一段8個字節的密文或者明文,最後一段不足8個字節,按照需求補足8個字節進行計算,之後按照順序將計算所得的數據連在一起即可,各段數據之間互不影響
特點是 簡單 有利於並行計算 容易被***

用到兩個函數
void RC532setkey(RC532KEY key, int len, const unsigned char data, int rounds);
根據密鑰計算密鑰組 連同 輪次round 填充到key中 後面的加密解密都須要用的這個key
data:密鑰 len:密鑰長度 0到2040位 rounds:輪次 可選 8/12/16

void RC532ecbencrypt(const unsigned char in, unsigned char out, RC532KEY key, int enc);
in:輸入 out:輸出 key:RC532setkey中初始化好的 enc: 可選 RC5ENCRYPT(加密)/RC5DECRYPT(解密)
注意這個函數每次只能處理8字節的數據 加/解密時源數據順序傳入


#include <openssl/rc5.h>
#include <stdio.h>
#include <string>
#include <string.h>

int main()
{
    RC5_32_KEY  rckey;
    unsigned char pwd[20] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x10, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0xe1, 0xe2, 0xe3, 0xe4 };

    RC5_32_set_key(&rckey, 20, pwd, RC5_8_ROUNDS);

    std::string in = "accidfdsa測試dfd";
    std::string strout = "";
    std::string strjie = "";

    char tempin[8];
    char tempout[8];
    // 加密
    for(size_t i = 0; i < in.size(); i += 8)
    {
        if(i + 8 <= in.size())
            memcpy(tempin, in.c_str()+i, 8);
        else
        {
            memset(tempin, 0, 8);
            memcpy(tempin, in.c_str()+i, in.size()-i);
        }

        RC5_32_ecb_encrypt((const unsigned char*)(tempin), (unsigned char*)tempout, &rckey, RC5_ENCRYPT);
        strout.append(tempout, 8);
    }

    // 解密
    for(size_t i = 0; i < strout.size(); i += 8)
    {
        if(i + 8 <= strout.size())
            memcpy(tempin, strout.c_str()+i, 8);
        else
        {
            memset(tempin, 0, 8);
            memcpy(tempin, strout.c_str()+i, strout.size() - i);
        }   

        RC5_32_ecb_encrypt((const unsigned char*)(tempin), (unsigned char*)tempout, &rckey, RC5_DECRYPT);

        if(strjie.size() + 8 > in.size())
            strjie.append(tempout, in.size() - strjie.size());
        else
            strjie.append(tempout, 8);
    }

    printf("-- %s", strjie.c_str());                                                                                                                                                                                                                                          
    return 0;
}

g++ -g -o main main.cpp -I/usr/include/openssl -lssl -lcrypto -L/usr/lib64

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章