1. 程式人生 > >Android下的編譯OpenSSL

Android下的編譯OpenSSL

1. 概述


OpenSSL可以編譯成ARM下面的二進位制程式碼(動態庫或者靜態庫),方便APP使用,APP在使用的時候,需要使用JNI來進行呼叫。

官方WIKI有寫如何為Android編譯OpenSSL,地址是:https://wiki.openssl.org/index.php/Android
因此也是參考這篇文章實現的。

編譯不太複雜,基本步驟如下:

  1. 下載NDK
  2. 下載OpenSSL原始碼和設定環境變數所需要的setenv-android.sh
  3. 配置編譯引數
  4. 編譯

2. 準備工作

2.1 環境


CentOS

2.2 安裝Linux版本的NDK


編譯Openssl需要使用NDK,先下載NDK:

wget https://dl.google.com/android/repository/android-ndk-r14b-linux-x86_64.zip
unzip android-ndk-r14b-linux-x86_64.zip

注意:NDK版本太新編譯OpenSSL可能會出錯

2.3 準備openssl原始碼和setenv-android.sh


wget https://www.openssl.org/source/openssl-1.1.1.tar.gz
wget https://wiki.openssl.org/images/7/70/Setenv-android.sh

注意:需要將OpenSSL和setenv-android.sh下載到同一個目錄,其中setenv-android.sh是Setenv-android.sh而且指令碼需要用gedit儲存成Unix/Linux格式(不然指令碼會報錯),需要改名為setenv-android.sh

3. 配置環境

修改以下引數:具體引數可以參看你下載的NDK資訊

_ANDROID_EABI="arm-linux-androideabi-4.8"
修改為GCC 4.9
_ANDROID_EABI="arm-linux-androideabi-4.9"

4. 開始編譯


  • 設定環境變數

我們需要通過環境變數來指定NDK所在的位置,按照之前的安裝位置,我們只需要執行:

export ANDROID_NDK_ROOT=你的NDK路徑
export ANDROID_NDK=你的NDK路徑(openssl-1.1.1需要)
source ./setenv-android.sh

If you receive a meesage "Error: FIPS_SIG does not specify incore module, please edit this script, then its safe to ignore it(這個錯誤可以忽略,我們不用編譯FIPS版本OpenSSL). setenv-android.sh is used to build both the FIPS Capable OpenSSL library and the non-FIPS version of the library. FIPS_SIG is not needed in this configuration.

  • 建立輸出目錄
mkdir output
  • 配置和編譯
[[email protected] openssl-1.1.1]$ ./config no-shared no-comp no-hw no-engine --openssldir=/home/scott/AndroidStudioProjects/openssl-1.1.1/output/$ANDROID_API --prefix=/home/scott/AndroidStudioProjects/openssl-1.1.1/output/$ANDROID_API
Operating system: armv7-whatever-android
Configuring OpenSSL version 1.1.1 (0x1010100fL) for android-armeabi
Using os-specific seed configuration
Creating configdata.pm
Creating Makefile

**********************************************************************
***                                                                ***
***   If you want to report a building issue, please include the   ***
***   output from this command:                                    ***
***                                                                ***
***     perl configdata.pm --dump                                  ***
***                                                                ***
**********************************************************************

這裡需要注意的是,no-shared表示不編譯動態庫,這樣編譯出來的openssl命令,不依賴動態庫,同時也沒有so產生。更多的編譯引數,詳見原始碼目錄下的:INSTALL(該檔案沒有後綴)

 

  • 安裝
make install

執行完上面的命令,openssl的標頭檔案、庫檔案、文件以及命令就被複制在:./output 目錄裡了。

目錄主要結構是:

bin 存放openssl命令
include 標頭檔案
lib 庫檔案
share 文件一類的

自己編譯各個版本庫,比較麻煩,網上有已經編譯好的庫:https://github.com/leenjewel/openssl_for_ios_and_android