Tesla4o
@Tesla4o
Без пользы жизнь - безвременная смерть... В. Гете

Почему при каждом выполнении программы постоянно разыне результаты шифрования DES3?

Есть пример кода для шифрования методом DES3 библиотекой OpenSSL, при каждом выполнении разные результаты.
Например один раз правильно зашифровал и расшифровал то второй раз может совсем не правильно расшифровать.
Не могу понять где ошибка, вот пример

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/pem.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include <openssl/pkcs12.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/md5.h>
#include <openssl/rc4.h>
#include <openssl/ct.h>
#include <openssl/aes.h>
#include <iostream>
#include <vector>
#include <boost/algorithm/hex.hpp>

#include <openssl/des.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define F_SIZE 4096

std::vector<std::string> explode_s(std::string d, std::string s) {
    std::vector<std::string> a = {};
    int pos = s.find(d);
    while (pos != std::string::npos) {
        a.push_back(s.substr(0, pos));
        s = s.substr(pos + d.length());
        pos = s.find(d);
    }
    a.push_back(s);
    return a;
}

struct CBlocks {
public:
    DES_key_schedule SchKey1;
    DES_key_schedule SchKey2;
    DES_key_schedule SchKey3;
    bool flag = true;

    CBlocks() {
    }

    CBlocks(DES_cblock &k1, DES_cblock &k2,
            DES_cblock &k3) {
        if (-2 == (DES_set_key_checked(&k1, &SchKey1) ||
                DES_set_key_checked(&k2, &SchKey2)
                || DES_set_key_checked(&k3, &SchKey3))) {
            throw std::invalid_argument(" Weak keys ...");
        }
    }
};

CBlocks getKeys(const std::string &key) {
    auto keys = explode_s(";", key);
    if (keys.size() < 3) {
        throw std::invalid_argument("size of keys has to be equal 3");
    }

    DES_cblock Key1;
    DES_cblock Key2;
    DES_cblock Key3;
    strncpy((char*) Key1, keys[0].c_str(), keys[0].size());
    strncpy((char*) Key2, keys[1].c_str(), keys[1].size());
    strncpy((char*) Key3, keys[2].c_str(), keys[2].size());

    return CBlocks(Key1, Key2, Key3);
}

std::string encrypt(std::string const& text, CBlocks keys) {
    DES_cblock iv = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0D };
    DES_set_odd_parity(&iv);

    char stg[F_SIZE] = "";
    strcpy(stg, text.c_str());

    int l = (text.size() << 1);

    char* cipher(new char[F_SIZE]);
    memset(cipher,0, F_SIZE);

    DES_ede3_cbc_encrypt((const unsigned char*)stg,
                          (unsigned char*)cipher,
                           text.length(), &keys.SchKey1, &keys.SchKey2, &keys.SchKey3,
                                   &iv, DES_ENCRYPT);

    std::string cip(cipher);

    //std::string h_cip = boost::algorithm::hex(cip);
    return cip;
}

std::string decrypt(std::string const& text, CBlocks keys) {
    std::string ucip = text; //boost::algorithm::unhex(text);
    DES_cblock iv = { 0x00, 0x01, 0x01, 0x02, 0x03, 0x05, 0x08, 0x0D };
    DES_set_odd_parity(&iv);

    char stg[F_SIZE] = "";
    strcpy(stg, ucip.c_str());

    char* cipher(new char[F_SIZE]);

    memset(cipher,0, F_SIZE);

    DES_ede3_cbc_encrypt((const unsigned char*)stg,
                          (unsigned char*)cipher,
                           ucip.size(), &keys.SchKey1, &keys.SchKey2, &keys.SchKey3,
                                      &iv,DES_DECRYPT);

    return std::string(cipher);
}

int main() {

        std::string text = "Dein draccar liegt auf dem Boden\n" \
                           "Das Herz brennt in Flammen\n" \
                           "Und kühles Wasser im Meer\n" \
                           "Nur die Seele kennt keine Trauer\n" \
                           "Der Tag wird kommen, die Stunde kommt\n" \
                           "Der Tod wartet auf jeden von uns\n";

    CBlocks keys = getKeys("12;123;32;23;12;23;53;34");

    auto s = encrypt(text, keys);
    //std::cout << s << std::endl;
    s = decrypt(s, keys);
    std::cout << "OUT: " << s << std::endl;

    std::cout << std::boolalpha << (text == s) << std::endl;
    return 0x00;
}


UPD: Поменял пример кода, первый был не тот
  • Вопрос задан
  • 98 просмотров
Пригласить эксперта
Ответы на вопрос 1
jcmvbkbc
@jcmvbkbc
"I'm here to consult you" © Dogbert
при каждом выполнении разные результаты.
CBlocks getKeys(const std::string &key) {
    auto keys = explode_s(";", key);
    if (keys.size() < 3) {
        throw std::invalid_argument("size of keys has to be equal 3");
    }

    DES_cblock Key1;
    DES_cblock Key2;
    DES_cblock Key3;
    strncpy((char*) Key1, keys[0].c_str(), keys[0].size());
    strncpy((char*) Key2, keys[1].c_str(), keys[1].size());
    strncpy((char*) Key3, keys[2].c_str(), keys[2].size());

    return CBlocks(Key1, Key2, Key3);
}

так а чего удивительного, если ты неизвестно куда свои ключи в этой функции копируешь?
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы