- StringCat
- Compiling OpenSSL on Windows (mingw32)
- Quick editing of the PATH environment variable
- Requirements
- Dynamic link libraries
- Static libraries
- StringCat
- Compiling OpenSSL on Windows (msvc)
- Troubleshooting
- Quick editing of the PATH environment variable
- Requirements
- Fast track of our recipes
- Compile msvc32 for static libraries
- Compile msvc32 for dynamic libraries
- Compile msvc64 for static libraries
- Compile msvc64 for dynamic libraries
- Компилируем библиотеку OpenSSL 1.1.0 для платформ Win32 и Win64
- Готовим всё необходимое для компиляции OpenSSL
- Компилируем OpenSSL
StringCat
7 December, 2015 (published) 7 December, 2015 (last modified) |
Compiling OpenSSL on Windows (mingw32)
The present post is a recipe for building static and dynamic OpenSSL libraries for all versions of OpenSSL on the Windows platform, viz. mingw using the gnu c++ compiler. In another posts we treat the msvc (Microsoft Visual Studio C++ compiler) toolchain. Any mingw toolchain could be used for the present purpose. However, there are quite a number of mingw distributions around that differ in a not well-documented way. As in our company we build multi-platform (Windows, Mac and Linux) applications using the Qt IDE we will use the mingw distribution (version 492-32bit) that comes with the open source Qt package (version 5.5.1 at present). Our goal is to have in the end the following 2 static libraries:
The following 2 import libraries
And the following 2 dynamic libraries:
Quick editing of the PATH environment variable
You will have to run several applications from the command line to compile OpenSSL. For your convenience it is advisable to have the location of these applications in your PATH environment. In earlier days one had to restart Windows to have a change in the SYSTEM environment to become active. This awkward situation has changed now. We use the free gui utility Rapid Environment Editor with which you can edit the SYSTEM and USER environment variables in such a way that these changes become immediately active if you open a *new* instance of explorer or a *new* instance of the MS-DOS terminal window (cmd.exe). Sometimes Windows caches the environment variables in such a way that a new change will not become active. This unwanted situation could occur for instance after installing a new program that adds its own file location to the PATH environment. To force to refresh the cache just edit the PATH variable and save and then undo the previous edit and save again. Now the most actual PATH will be known to all applications that need the environment for their execution.
Requirements
All the following requirements are essential. Do not go to a next requirement if you have not fulfilled the previous requirement.
- perl
You will need the perl program. Open an MS-DOS command window and run
If you get something like:
you do not have perl installed. We advise to use the free ActiveState perl distribution. Then running the previous command should give something like:
You are OK now.
Mingw32
I assume you have somewhere a mingw distribution whose gcc compiler you want to use. Open an MS-DOS cmd window at the file location of this gcc compiler of the mingw32 distribution and run
The last line of the response should be something like
Open another MS-DOS window at root c:\ and run again
If the response is exactly the same as you had before you have the right mingw toolchain and it is also in your PATH. If you get another response you have to add the mingw location to your PATH and/or you have to remove from your PATH the location containing other gcc compilers.
GNU make
You will need the GNU make utility and it must be in your PATH. On a Windows development computer there are usually a number of programs called «make», and worse some of them are in your PATH. Open a MS-DOS window at root location and run
The response should be something like
Any other response, like a Microsoft «make» is wrong. Get these other «make»‘s out of the PATH (possibly only temporarily). If you still do not get the GNU response you will have to install GNU make. Download it from the internet (it is shipped with MSYS).
tar
The OpenSSL source comes as a compressed (gz) archive (tar) which in the Linux world is called a tarball. The OpenSSL archive (may) contain file links. Although Windows supports some form of file links their implementation is not compatible with Linux-type links. As a result the popular zip/unzip Windows utilities can produce incomplete uncompressed archives if there are file links in the archive. For this purpose we strongly advise to use the GNU «tar» utility to untar the tarball. The tar utility ships with the above mentioned MSYS distribution. So open an MS-DOS terminal at root and run
The response should be something like:
Dynamic link libraries
We will now compile for the case of generating dynamic link libraries.
- Download the required OpenSSL version. It is a compressed file (tarball tar.gz. ) Untar the tarball with tar. Open a MS-DOS terminal window at the location of the tarball and run
where vv is the OpenSSL version (like 1.0.2e). Neglect the warnings about file links. Check that the tarball is indeed decompressed in its own new directory.
Open an MS-DOS cmd window at the root location of the OpenSSL source distribution. That directory should have a file called «Configure». Run
it should do some stuff ( a minute or so) and should end with something like
Run in the same terminal
The terminal window should start compiling and after some time (10 minutes in our case) it should end with no errors.
Static libraries
If you want to generate static libraries the procedure is almost identical to the one described for the case of dynamic libraries. Just replace
You now can collect the two static libraries and the include branch.
StringCat
9 December, 2015 (published) 9 December, 2015 (last modified) |
Compiling OpenSSL on Windows (msvc)
The present post is a recipe for building the static and dynamic OpenSSL libraries for all versions of OpenSSL on the Windows platform, viz. msvc32 and msvc64. We are using the Microsoft Visual Studio 2013 C++ compiler. In another posts we treat the mingw (Minimal GNU for Windows) toolchain. Our goal is to have in the end the following libraries (each for 32bit and 64bit that all have 32 in their name even then 64bit versions):
And the import, export, debug files *.exp, *.lib, and*.pdb with «*» equal to «libeay32» or «ssleay32» that are possibly useful when linking dynamically.
Troubleshooting
We start with common errors that are to be avoided.
- do not use «make clean» to correct for a faulty build. Delete the whole branch and replace by a fresh decompressed OpenSSL tarball.
- only open terminal windows through the msvc compiler shortcuts and not just a «cmd.exe» terminal.
- internet fora are full of reports of failed OpenSSL compilations. One such a source of errors is the use of the assembler. Our recipes work but they do not necessarily produce the smallest and/o the fastest binaries. We use explicitly use the nasm assembly compiler for 32bit.
- the OpenSSL tarballs may contain file links that are often corrupted by windows decompress utilities. Note that the final «include/openssl» dir should contain only real header files and not file links.
Quick editing of the PATH environment variable
You will have to run several applications from the command line to compile OpenSSL. For your convenience it is advisable to have the location of these applications in your PATH environment. In earlier days one had to restart Windows to have a change in the SYSTEM environment to become active. This awkward situation has changed now. We use the free gui utility Rapid Environment Editor with which you can edit the SYSTEM and USER environment variables in such a way that these changes become immediately active if you open a *new* instance of explorer or a *new* instance of the MS-DOS terminal window (cmd.exe). Sometimes Windows caches the environment variables in such a way that a new change will not become active. This unwanted situation could occur for instance after installing a new program that adds its own file location to the PATH environment. To force to refresh the cache just edit the PATH variable and save and then undo the previous edit and save again. Now the most actual PATH will be known to all applications that need the environment for their execution.
Requirements
All the following requirements are essential. Do not go to a next requirement if you have not fulfilled the previous requirement.
- perl
You will need the perl program. Open an MS-DOS command window and run
If you get something like:
you do not have perl installed. We advise to use the free ActiveState perl distribution. Then running the previous command should give something like:
You are OK now.
I assume you have this compiler, msvc from now on, installed (community edition is free). We use the 2013 version. The msvc compiler needs quite a number of environment variables set for it to run properly. For this to work on the command line you will have to open a command line terminal window using the shortcuts that come with the installation of the msvc compiler.
OpenSSL allows for using an assembler to produce speed-optimized binaries. We will use the nasm compiler for 32bit compilation and use the OpenSSL default for 64bit. So download the nasm compiler. Get its binary in your PATH and check with a command window it is visible to all applications. Run
with expected response like
The response should be something like:
where ov is the OpenSSL version (like 1.0.2e). Neglect the warnings about file links. Check that the tarball is indeed decompressed in its own new directory. We usually copy this source tree to the directories
openssl-version/msvc32/noshared
openssl-version/msvc32/shared
openssl-version/msvc64/noshared
openssl-version/msvc64/shared
Fast track of our recipes
If you do not want to know about the explanations, just enter in a suitable MS-DOS command window the blue commands to be found below.
Compile msvc32 for static libraries
Open a msvc32 command window (so not just a cmd.exe window) and navigate to the OpenSSL source code. The root dir should contain a file called «Configure». Run
The final response should be
Run in the same command window
You should get no error responses. Continue in the same window with running
You will see the compiling process going on (for about 10 minutes). Your libraries will be at the root of the source tree.
Compile msvc32 for dynamic libraries
Do the same as for static libraries but replace «nt.mak» by «ntdll.mak»:
Compile msvc64 for static libraries
Open a msvc64 command window (so not just a cmd.exe window) and navigate to the OpenSSL source code. The root dir should contain a file called «Configure». Run
The final response should be
Run in the same command window
You should get no error responses. Continue in the same window with running
You will see the compiling process going on (for about 10 minutes). Your libraries will be at the root of the source tree.
Compile msvc64 for dynamic libraries
Do the same as for static libraries for msvc64 but replace «nt.mak» by «ntdll.mak»:
You will see the compiling process going on (for about 10 minutes). The generated libraries will be in the out32dll subdirectory.
Компилируем библиотеку OpenSSL 1.1.0 для платформ Win32 и Win64
Автор: Alex. Опубликовано в Программирование 29 Апрель 2017 . просмотров: 11858
OpenSSL – это криптографическая библиотека, предназначенная для использования в приложениях, которым нужно безопасное взаимодействие в компьютерных сетях, например, с целью защиты передаваемой информации от прослушивания или для установления личности участника на другом конце. Найти скомпилированную библиотеку конечно можно, но не нужно. Разработчики OpenSSL советуют компилировать библиотеку самостоятельно, чтобы учесть все необходимые для вашего случая детали, такие как особенности архитектуры и платформы. В этой статье мы рассмотрим, как скомпилировать библиотеку OpenSSL версии 1.1.0 и выше для платформ Win32 и Win64.
Готовим всё необходимое для компиляции OpenSSL
Первое, что нужно сделать – это скачать и установить необходимые приложения:
-
- Perl. Рекомендуется использовать ActiveState Perl, который вы можете найти на официальном сайте здесь.
- Netwide Assembler (NASM). Этот ассемблер является обязательным, если вы планируете использовать модули на ассемблере. Скачать дистрибутив этого ассемблера вы можете с официального сайта здесь. После установки обязательно пропишите путь к файлу nasm.exe в переменную среды PATH.
- Компилятор C. OpenSSL тестируется только с компилятором Visual C++, поэтому лучше использовать именно его. Этот компилятор у вас уже установлен, если у вас установлена какая либо версия Microsoft Visual Studio. Если студия у вас не установлена, и вы не собираетесь её устанавливать, вы можете установить Visual C++ 2015 Build Tools (если при установке вы уберёте все галочки, то будет установлен только компилятор).
После этого скачайте исходники библиотеки OpenSSL с официального сайта отсюда. Если вы хотите иметь сразу две версии OpenSSL для отладки, то вам нужно будет скомпилировать OpenSSL два раза в разные папки. В этом случае создайте две папки: одну для платформы Win32, вторую для платформы Win64, например, C:\openssl-src-32 и C:\openssl-src-64, и распакуйте исходники два раза в обе эти папки.
Всё дальнейшее нужно будет делать из командной строки Visual Studio. Командную строку запускайте сразу для нужной целевой архитектуры процессора x86 или x64. Как в вашей операционной системе найти ярлык/пункт меню для запуска командной строки можете почитать здесь. Например, если у вас Windows 7 и установлена студия 2012, то для запуска командной строки для целевой архитектуры процессора x86 нужный пункт меню будет находиться по пути «Пуск -> Все программы -> Microsoft Visual Studio 2018 -> Visual Studio Tools -> Командная строка VS2012 x86 Native Tools». А если вы установили только инструменты Visual C++ 2015 Build Tools, то для Windows 7 и целевой архитектуры x86 пункт меню будет «Пуск -> Все программы -> Visual C++ Build Tools -> Windows Desktop Commands Prompt -> Visual C++ 2015 x86 Native Build Tools Command Prompt».
Компиляция библиотеки по умолчанию происходит в папку приложений «C:\Program Files\OpenSSL» или «C:\Program Files (86)\OpenSSL» (в зависимости от текущей архитектуры Windows), поэтому командную строку Visual Studio нужно запускать с правами администратора. Для этого по ярлыку/пункту меню нужно щёлкнуть правой кнопкой мышки и выбрать «Запуск от имени администратора».
Компилируем OpenSSL
-
- Откройте командную строку Visual Studio (как это сделать, см. выше).
- Перейдите в папку с нужными исходниками. Для этого выполните команду «cd ПУТЬ». Например, для перехода в папку C:\openssl-src-32 команда будет выглядеть так:
А для перехода в папку C:\openssl-src-64 так:
-
- Сконфигурируйте make-файл для конкретной целевой платформы и целевой папки. Для платформы Win32 и целевой папки «C:\Program Files\OpenSSL» или «C:\Program Files (x86)» выполните команду:
Для компиляции для Win32 в вашу конкретную папку, например, «C:\Build-OpenSSL-VC-32»:
Для компиляции для Win32 с символьной отладочной информацией в вашу папку, например, «C:\Build-OpenSSL-VC-32-dbg»:
Для платформы Win64:
Для компиляции для Win64 в вашу конкретную папку, например, «C:\Build-OpenSSL-VC-64»:
Для компиляции для Win64 с символьной отладочной информацией в вашу папку, например, «C:\Build-OpenSSL-VC-64-dbg»:
Если вы решили не использовать модули на ассемблере, то допишите ещё параметр «no-asm». Например:
Узнать назначение ещё большего количества параметров, можно почитав текстовый файл INSTALL, который находится в папке с исходниками.
-
- Чтобы получить библиотеку OpenSSL с полной отладочной информацией, после шага 3, откройте файл makefile в любом текстовом редакторе, найдите в тексте флажки «/Zi» и замените их на «/Z7». Таких замен у вас должно получиться три. Подробности об этих флажках см. здесь.
На самом деле я не обнаружил разницы между компиляцией с добавлением отладочных символов и без неё. У меня всё время получается вариант для отладки: создаются OBJ и PDB-файлы. Видимо при создании файла makefile где-то закралась ошибка, которую в будущих версиях исправят.
-
- Скомпилируйте OpenSSL. Для этого последовательно выполните следующие три команды:
Здесь команда «nmake» компилирует весь проект, команда «nmake test» проводит тестирование, при успешном проведении которого должны появится сообщения «All tests successful» и «Result: PASS», а команда «nmake install» копирует необходимые файлы в папки назначения.
После выполнения последней команды в целевой папке (это папка «C:\Program Files\OpenSSL», «C:\Program Files (x86)\OpenSSL» или папка, которую вы задали параметром —prefix) появятся готовые файлы библиотеки OpenSSL. Можно их использовать.
Как видите, ничего особенно сложного в компиляции OpenSSL нет. Однако особо ленивые могут скачать уже готовые дистрибутивы, содержащие скомпилированные файлы библиотеки, с сайта Shining Light Productions, или более старые версии библиотеки отсюда.