2017-01-28 14 views
1

Я пытаюсь использовать openssl с проектом visual studio c.EVP_get_cipherbyname и «undefined struct/union evp_cipher_st» в OpenSSL 1.1.0

Я составил OpenSSL с помощью Visual Studio NMake команды затем установил все к предопределенной папке (C: \ OpenSSL) с помощью:

nmake install 

Структура папки выглядит следующим образом:

  • bin

  • include/openssl

  • lib

Внутри включают/OpenSSL есть .h файлы заголовков.

В моем Visual Studio 2012, я создал пустой общий проект гр ++ и включен C: \ OpenSSL \ включает

[Project properties -> C/C++ -> General -> Additional Include Directories] 

Я также добавил Lib каталога и .lib файлов.

Но когда я скомпилировать код, я получаю

left of 'key_len' specifies undefined struct/union 'evp_cipher_st' 

Внутри моего кода у меня есть эти строки

const EVP_CIPHER *cipher = EVP_get_cipherbyname("aes-256-cbc"); 
//some other code 
return cipher->key_len; 

Заглянув в ossl_typ.h файл для evp_cipher_st определения, он объявлен как

typedef struct evp_cipher_st EVP_CIPHER; 

и нет определения для структурного тела!

Копировав больше в исходное дерево, evp_cipher_st определяется в crypto \ include \ internal \ evp_int.h, который не включен в папку include папки установки openssl.

Я также попытался включить crypto \ include \ internal \ evp_int.h из коробки, но это приводит к большему количеству проблем.

Любая идея, как исправить это?

UPDATE:

Вот полная функция и мое главное в том числе все включает в себя:

#include <winsock2.h> 
#include <Ws2tcpip.h> 
#include <mswsock.h> 
#include <windows.h> 
#include <minwindef.h> 
#include <malloc.h> 
typedef unsigned char uint8_t; 
typedef unsigned short uint16_t; 
typedef unsigned int uint32_t; 
typedef int socklen_t; 
#include "wingetopt.h" 
#include <Wincrypt.h> 
#include <iphlpapi.h> 
#include "Shlwapi.h" 
#include <Bcrypt.h> 

#define inline __inline 
#define STATUS_SUCCESS 0 

#pragma comment(lib, "iphlpapi.lib") 
#pragma comment(lib, "Ws2_32.lib") 
#pragma comment(lib, "Shlwapi.lib") 

#include <sys/stat.h> 
#include <sys/types.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <errno.h> 
#include <stdarg.h> 
#include <fcntl.h> 
#include <time.h> 

int generate_aes_key(const unsigned char *input_key, uint16_t input_key_size, 
      unsigned char *output_key, uint16_t *outputkey_size) { 

     const EVP_MD *dgst = NULL; 
     unsigned char iv[EVP_MAX_IV_LENGTH]; 
     const EVP_CIPHER *cipher = EVP_get_cipherbyname("aes-256-cbc"); 

     if(!cipher) { 

      return -1; 
     } 

     dgst = EVP_get_digestbyname("sha256"); 

     if(!dgst) { 

      fprintf(stderr, "no such digest\n"); 
      return -2; 
     } 

     if(!EVP_BytesToKey(cipher, dgst, NULL, input_key, input_key_size, 1, output_key, iv)) { 

      return -3; 
     } 

     *outputkey_size = (uint16_t)cipher->key_len; 

     return 0; 
} 

int main(int argc, char *argv[]) { 

    char secret[] = "MIIFBTCCAu2gAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwTjELMAkGA1UEBhMCR0Ix"; 

    unsigned char shared_secret[500]; 
    uint16_t aes_keylen = 0; 

    //bunch of codes 

    if(generate_aes_key((unsigned char *)secret, strlen(secret), shared_secret, &aes_keylen) < 0) { 

     fprintf(stderr, "Could not get initial shared secret\n"); 
     return 0; 
    } 

    //other codes 
} 

Openssl версия:

OpenSSL_1_1_0-pre6-1266-g487d3a726

Выше версии является последним именем тега из мерзавца , Я думаю, что он самый свежий до сих пор.Последний коммит версию и дату выглядит следующим образом:

487d3a726a1970e84853434561d88cb4ac212d15

Author: EasySec Date: Tue Jan 17 17:21:55 2017 +0100

И, наконец, вот Visual Studio 2012 компиляции выход:

Build started 1/28/2017 8:23:02 PM. 
1>Project "C:\CODE\mycode.vcxproj" on node 2 (Build target(s)). 
1>ClCompile: 
    C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\CL.exe /c /I"c:\openssl\include" /ZI /nologo /W3 /WX- /Od /Oy- /D _MBCS /Gm /EHsc /RTC1 /MDd /GS /fp:precise /Zc:wchar_t /Zc:forScope /Fo"Debug\\" /Fd"Debug\vc110.pdb" /Gd /TC /analyze- /errorReport:prompt src\main.c ... 

    wingetopt.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    crypto.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
1>c:\CODE\src\crypto.c(517): error C2037: left of 'key_len' specifies undefined struct/union 'evp_cipher_st' 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    client.c 
1>c:\openssl\include\openssl\lhash.h(198): warning C4090: 'function' : different 'const' qualifiers 
    Generating Code... 
1>Done Building Project "C:\CODE\mycode.vcxproj" (Build target(s)) -- FAILED. 

Build FAILED. 

Time Elapsed 00:00:08.55 
+0

Вы должны включить ['evp.h'] (https://github.com/openssl/openssl/blob/master/include/openssl/evp.h). Вы это делаете? В противном случае предоставьте [Минимальный, полный и проверенный пример] (https://stackoverflow.com/help/mcve). Фактически, нам нужно увидеть полный 'main' с функциями, которые вы вызываете. Возможно, нам понадобится команда компиляции, поэтому вы также должны ее предоставить. Наконец, укажите версию OpenSSL, которую вы используете. – jww

+0

Я включил evp.h тоже, но ничего не сделал. Хорошо, я уточню вопрос с дополнительной информацией, спасибо – madz

+0

Это выглядит хорошо из вашей команды компиляции: 'I 'c: \ openssl \ include". В вашей программе нет 'evp.h'. Вы должны включить ''. – jww

ответ

1

Вы можете получить длину ключа с помощью:

*outputkey_size = EVP_CIPHER_key_length(cipher); 

Ввод кода в конец вашего кода:

printf("Key-size: %d\n", aes_keylen); 
printf("Key: "); for (int i = 0; i<aes_keylen; ++i) { printf("%02x", shared_secret[i]); } printf("\n"); 

Он печатает правильный вывод, который находится рядом:

Key-size: 32 
Key: 51ae3ac4721439302cc5f90313f440bd9ca714c9a80b2213d034c87c00a700a0 

я не уверен, если key_len была доступна в предыдущих версиях, но в openssl-1.10 release notes вы можете прочитать:

  • Most libcrypto and libssl public structures were made opaque, including: BIGNUM and associated types, EC_KEY and EC_KEY_METHOD, DH and DH_METHOD, DSA and DSA_METHOD, RSA and RSA_METHOD, BIO and BIO_METHOD, EVP_MD_CTX, EVP_MD, EVP_CIPHER_CTX, EVP_CIPHER, EVP_PKEY and associated types, HMAC_CTX, X509, X509_CRL, X509_OBJECT, X509_STORE_CTX, X509_STORE, X509_LOOKUP, X509_LOOKUP_METHOD
  • libssl internal structures made opaque

что означает, что приложениям больше не разрешено заглядывать в переменные структур. Это причина, по которой _key_len (и другие) отображается неопределенно.

+0

Спасибо @jgorosdev решение работает хорошо. Похоже, что эта структура стала непрозрачным типом для более новых версий opensl. – madz

+0

@pendrive. Похоже, вы столкнулись с [Ошибка: «неверное использование неполного типа« RSA {aka struct rsa_st} »в OpenSSL 1.1.0] (http: /stackoverflow.com/q/40549318) и [Visual Studio и ошибка C2027: использование неопределенного типа «rsa_st»] (http://stackoverflow.com/q/41348281) – jww