Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 Аватар для Viels
0 / 0 / 1
Регистрация: 07.05.2016
Сообщений: 41

OPENSSL ошибка "digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:crypto\evp\ev"

16.09.2018, 21:34. Показов 20643. Ответов 0
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый вечер!

Использую Openssl v 1.1.0, используя пример с сайта: https://wiki.openssl.org/index... Decryption

Написал программку шифрования, странная ошибка, причем возникает она не всегда.

"digital envelope routines:EVP_DecryptFinal_ex:wrong final block length:crypto\evp\ev"

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// AES_EVP.cpp: реализация CAES_EVP
 
#pragma comment(lib, "IPHLPAPI.lib")
#include <winsock2.h>
#include <iphlpapi.h>
#include <algorithm> 
#include <sstream>
#include <iomanip>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <array>
#include <tchar.h>
#define _WIN32_DCOM
#include <comdef.h>
#include <Wbemidl.h>
#include <chrono>
#include <ctime>
#include <fstream>
#include <stdio.h>  /* defines FILENAME_MAX */
#include <direct.h>
#include <string.h>
#include <iostream>
#include "base64.h"
#include <atlconv.h>
#include <atlbase.h>
#include <atlconv.h>
#include <assert.h> 
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/applink.c>
// CAES_EVP
 
#define GetCurrentDir _getcwd
#define INFO_BUFFER_SIZE 32767
#pragma comment(lib, "wbemuuid.lib")
using namespace std;
 
#define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x))
#define FREE(x) HeapFree(GetProcessHeap(), 0, (x))
 
template<typename T>
 
static std::string HexToString(T uval)
{
    std::stringstream ss;
    ss << std::setw(sizeof(uval) * 2) << std::setfill('0') << std::hex << +uval;
    std::string strToConvert = ss.str();
    std::transform(strToConvert.begin(), strToConvert.end(), strToConvert.begin(), ::toupper);
    return strToConvert;
}
 
std::wstring GetMac()
{
    std::wstring result;
    unsigned int i = 0;
    DWORD dwRetVal = 0;
    ULONG flags = GAA_FLAG_INCLUDE_PREFIX;
    ULONG family = AF_INET;
    PIP_ADAPTER_ADDRESSES pAddresses = NULL;
    ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
    pAddresses = (IP_ADAPTER_ADDRESSES *)MALLOC(outBufLen);
 
    if (GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen) == ERROR_BUFFER_OVERFLOW)
    {
        FREE(pAddresses);
        pAddresses = (IP_ADAPTER_ADDRESSES *)MALLOC(outBufLen);
    }
 
    if (pAddresses == NULL)
        return L"";
 
    dwRetVal = GetAdaptersAddresses(family, flags, NULL, pAddresses, &outBufLen);
    if (dwRetVal == NO_ERROR)
    {
        if (pAddresses->PhysicalAddressLength != 0)
        {
            std::string str;
            for (i = 0; i < pAddresses->PhysicalAddressLength; i++)
            {
                if (i == (pAddresses->PhysicalAddressLength - 1))
                    str += HexToString((unsigned char)pAddresses->PhysicalAddress[i]);
                else
                    str += HexToString((unsigned char)pAddresses->PhysicalAddress[i]) + ":";
            }
            result = std::wstring(str.begin(), str.end());
        }
    }
    FREE(pAddresses);
    return result;
}
 
std::string getFirstHddSerialNumber() {
    //get a handle to the first physical drive
    HANDLE h = CreateFileW(L"\\\\.\\PhysicalDrive0", 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
    if (h == INVALID_HANDLE_VALUE) return{};
    //an std::unique_ptr is used to perform cleanup automatically when returning (i.e. to avoid code duplication)
    std::unique_ptr<std::remove_pointer<HANDLE>::type, void(*)(HANDLE)> hDevice{ h, [](HANDLE handle) {CloseHandle(handle); } };
    //initialize a STORAGE_PROPERTY_QUERY data structure (to be used as input to DeviceIoControl)
    STORAGE_PROPERTY_QUERY storagePropertyQuery{};
    storagePropertyQuery.PropertyId = StorageDeviceProperty;
    storagePropertyQuery.QueryType = PropertyStandardQuery;
    //initialize a STORAGE_DESCRIPTOR_HEADER data structure (to be used as output from DeviceIoControl)
    STORAGE_DESCRIPTOR_HEADER storageDescriptorHeader{};
    //the next call to DeviceIoControl retrieves necessary size (in order to allocate a suitable buffer)
    //call DeviceIoControl and return an empty std::string on failure
    DWORD dwBytesReturned = 0;
    if (!DeviceIoControl(hDevice.get(), IOCTL_STORAGE_QUERY_PROPERTY, &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
        &storageDescriptorHeader, sizeof(STORAGE_DESCRIPTOR_HEADER), &dwBytesReturned, NULL))
        return{};
    //allocate a suitable buffer
    const DWORD dwOutBufferSize = storageDescriptorHeader.Size;
    std::unique_ptr<BYTE[]> pOutBuffer{ new BYTE[dwOutBufferSize]{} };
    //call DeviceIoControl with the allocated buffer
    if (!DeviceIoControl(hDevice.get(), IOCTL_STORAGE_QUERY_PROPERTY, &storagePropertyQuery, sizeof(STORAGE_PROPERTY_QUERY),
        pOutBuffer.get(), dwOutBufferSize, &dwBytesReturned, NULL))
        return{};
    //read and return the serial number out of the output buffer
    STORAGE_DEVICE_DESCRIPTOR* pDeviceDescriptor = reinterpret_cast<STORAGE_DEVICE_DESCRIPTOR*>(pOutBuffer.get());
    const DWORD dwSerialNumberOffset = pDeviceDescriptor->SerialNumberOffset;
    if (dwSerialNumberOffset == 0) return{};
    const char* serialNumber = reinterpret_cast<const char*>(pOutBuffer.get() + dwSerialNumberOffset);
    return serialNumber;
}
 
void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}
 
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
    unsigned char *iv, unsigned char *ciphertext)
{
    EVP_CIPHER_CTX *ctx;
 
    int len;
 
    int ciphertext_len;
 
    /* Create and initialise the context */
    if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
 
    /* Initialise the encryption operation. IMPORTANT - ensure you use a key
    * and IV size appropriate for your cipher
    * In this example we are using 256 bit AES (i.e. a 256 bit key). The
    * IV size for *most* modes is the same as the block size. For AES this
    * is 128 bits */
    if (1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();
 
    /* Provide the message to be encrypted, and obtain the encrypted output.
    * EVP_EncryptUpdate can be called multiple times if necessary
    */
    if (1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
        handleErrors();
    ciphertext_len = len;
 
    /* Finalise the encryption. Further ciphertext bytes may be written at
    * this stage.
    */
    if (1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
    ciphertext_len += len;
 
    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);
 
    return ciphertext_len;
}
 
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
    unsigned char *iv, unsigned char *plaintext)
{
    EVP_CIPHER_CTX *ctx;
 
    int len;
 
    int plaintext_len;
 
    /* Create and initialise the context */
    if (!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
 
    /* Initialise the decryption operation. IMPORTANT - ensure you use a key
    * and IV size appropriate for your cipher
    * In this example we are using 256 bit AES (i.e. a 256 bit key). The
    * IV size for *most* modes is the same as the block size. For AES this
    * is 128 bits */
    if (1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();
 
    /* Provide the message to be decrypted, and obtain the plaintext output.
    * EVP_DecryptUpdate can be called multiple times if necessary
    */
    if (1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
        handleErrors();
    plaintext_len = len;
 
    /* Finalise the decryption. Further plaintext bytes may be written at
    * this stage.
    */
    if (1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
    plaintext_len += len;
 
    /* Clean up */
    EVP_CIPHER_CTX_free(ctx);
 
    return plaintext_len;
}
 
char* getchar_from_bstr(BSTR in) {
    int leng = wcslen(in);
    char * string = new char[leng + 1];
    int last = WideCharToMultiByte(CP_ACP, 0, in, leng, string, leng, 0, 0);
    string[last] = 0;
    return string;
}
 
string bstr_to_str(BSTR source) {
    //source = L"lol2inside";
    _bstr_t wrapped_bstr = _bstr_t(source);
    int length = wrapped_bstr.length();
    char* char_array = new char[length];
    strcpy_s(char_array, length + 1, wrapped_bstr);
    return char_array;
}
 
unsigned char* bstr_char(BSTR in) {
    int bstrLen = SysStringLen(in) + 1;
    int len = WideCharToMultiByte(CP_ACP, 0, in, bstrLen, NULL, 0,
        NULL, NULL);
    unsigned char * pBuffer = new unsigned char[len];
    WideCharToMultiByte(CP_ACP, 0, in, bstrLen, LPSTR(pBuffer), len,
        NULL, NULL);
    return pBuffer;
}
 
unsigned char* bstr_char_2(BSTR in) {
    int leng = wcslen(in);
    char * string = new char[leng + 1];
    int last = WideCharToMultiByte(CP_ACP, 0, in, leng, string, leng, 0, 0);
    string[last] = 0;
    return (unsigned char*)string;
}
 
BSTR char_bstr(unsigned char* in) {
    char * ansistr = (char *)in;
    int a = lstrlenA(ansistr);
    BSTR unicodestr = SysAllocStringLen(NULL, a);
    ::MultiByteToWideChar(CP_ACP, 0, ansistr, a, unicodestr, a);
    return unicodestr;
}
 
BSTR ENCRYPT(BSTR in, BSTR key) {
    unsigned char * pBuffer = bstr_char(in);
 
    unsigned char * key_v = bstr_char(key);
 
    unsigned char *key_ = (unsigned char*)"857759686370038057";
 
    char *temp = (char *)malloc(strlen((char*)key_v) + strlen((char*)key_) + 1);
    strcpy(temp, (char*)key_);
    strcat(temp, (char*)key_v);
 
    unsigned char *iv = (unsigned char*)"2371904392800624";//(unsigned char*)"199618872547325";
 
    unsigned char ciphertext[5000];
 
    int ciphertext_len;
 
    ciphertext_len = encrypt(pBuffer, strlen((char *)pBuffer), (unsigned char*)temp, iv, ciphertext);
 
    ciphertext[ciphertext_len] = '\0';
 
    std::string encoded = base64_encode(ciphertext, strlen((char *)ciphertext));
 
    ULONG ulSize = strlen((char*)reinterpret_cast<const unsigned char*>(encoded.c_str())) + sizeof(char);
    char* pszReturn = NULL;
 
    pszReturn = (char*)::CoTaskMemAlloc(ulSize);
    strcpy(pszReturn, (char*)(char*)reinterpret_cast<const unsigned char*>(encoded.c_str()));
    BSTR out = SysAllocString(CA2W(pszReturn));
 
    pBuffer = NULL;
    key_v = NULL;
    key_ = NULL;
    temp = NULL;
    iv = NULL;
    return out;
}
 
BSTR DECRYPT(BSTR in, BSTR key) {
    unsigned char * pBuffer = bstr_char(in);
 
    unsigned char * key_v = bstr_char(key);
 
    unsigned char *key_ = (unsigned char*)"857759686370038057";
 
    char *temp = (char *)malloc(strlen((char*)key_v) + strlen((char*)key_) + 1);
    strcpy(temp, (char*)key_);
    strcat(temp, (char*)key_v);
 
    unsigned char *iv = (unsigned char*)"2371904392800624";// (unsigned char*)"199618872547325";;
    unsigned char decryptedtext[5000];
 
    int decryptedtext_len;
 
    std::string sName(reinterpret_cast<char*>(pBuffer));
    std::string decoded = base64_decode(sName);
 
    /* _DECRYPT_AES_ the ciphertext */
    decryptedtext_len = decrypt((unsigned char*)reinterpret_cast<const unsigned char*>(decoded.c_str()),
        strlen((char *)(char*)reinterpret_cast<const unsigned char*>(decoded.c_str())), (unsigned char*)temp, iv,
        decryptedtext);
 
    /* Add a NULL terminator. We are expecting printable text */
    decryptedtext[decryptedtext_len] = '\0';
 
    ULONG ulSize = strlen((char*)decryptedtext) + sizeof(char);
    char* pszReturn = NULL;
 
    pszReturn = (char*)::CoTaskMemAlloc(ulSize);
 
    strcpy(pszReturn, (char*)decryptedtext);
 
    BSTR out = SysAllocString(CA2W(pszReturn));
 
    pBuffer = NULL;
    key_v = NULL;
    key_ = NULL;
    temp = NULL;
    iv = NULL;
    return out;
}
 
BSTR GET_PARAM_()
{
    // TODO: добавьте код реализации
    time_t rawtime;
    struct tm * timeinfo;
    char buffer[15];
 
    time(&rawtime);
    timeinfo = localtime(&rawtime);
 
    strftime(buffer, sizeof(buffer), "%d%m%Y%H%M%S", timeinfo);
    BSTR GET_TIME = SysAllocString(CA2W(buffer));
    return GET_TIME;
}
 
 
void main()
{
    for (int i = 0; i < 100; i++) {
        BSTR KEY = GET_PARAM_();
        BSTR ENCR = ENCRYPT(SysAllocString(L"new string"), KEY);
        BSTR decr = DECRYPT(ENCR, KEY);
        wcout << ENCR << endl;
        wcout << decr << endl;
        cout << "----------------------------------" << endl;
    }
    system("pause");
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
16.09.2018, 21:34
Ответы с готовыми решениями:

React_js ошибка error:0308010C:digital envelope routines::unsupported
как сделать чтобы реакт заработал? в консоли браузера такая ошыбка - crbug/1173575, non-JS module files deprecated. работаю в vs code...

Error: digital envelope routines
Здравствуйте, в react не особо разбираюсь но пытаюсь понять Буду признателен если подскажете с чем это может быть связано все проблемы...

Crypto: Given final block not properly padded
Нужна помощь. Пытаюсь разобраться в шифровании. К сожалению неудачно. Постоянно отлавливаю ошибку javax.crypto.BadPaddingException:...

0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
16.09.2018, 21:34
Помогаю со студенческими работами здесь

Aiogram.utils.exceptions.BadRequest: Wrong remote file identifier specified: wrong string length
How can this problem be solved and what is it? I have already tried all the options, checked all the variables, checked the entire database...

libcrypto OpenSSL использование EVP API
В инете полно информации, и примеров с кодирование информации и раскодированием в одной программе, причем там почти всегда информацию...

Ошибка! something is wrong with the solve block used to define this function
подскажите в чем проблема?не понимаю... кроме f,пожалуйста,не использовать другие переменные

Delphi XE8 idIMAP4 gmail и ошибка error connecting with ssl error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version nu
В чем может быть ошибка? ССЛ библиотек уже кучу перебрал Вроде по коду все норм: var msgcnt, i: integer; ss: string; begin ...

Unhandled exception. Interop+Crypto+OpenSslCryptographicException: error:2006D002:BIO routines:BIO_new_file:system lib
Всем доброго времени суток! Развертываю серверную часть на Linux получаю при запуске приложения исключение Unhandled exception....


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
1
Ответ Создать тему
Новые блоги и статьи
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Access
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут. В век Веб все очень привыкли к дизайну Single-Page-Application . Быстренько разберем подход "на фреймах". Мы делаем одну. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru