1.编译Openssl源代码,⽣成.so库(笔者使⽤环境为Ubuntu 18.04 amd64 桌⾯版,android_ndk_r19c 64位版): 下载Openssl源代码,进⼊源码环境然后运⾏配置脚本,设置编译参数,开始编译:
export ANDROID_NDK=/home/gj/android-ndk-r19c
export PATH=/home/gj/android-ndk-r19c/toolchains/llvm/prebuilt/linux-x86_64/bin:$PATH ./Configure android-arm shared make SHLIB_EXT=.so -j8
⽣成的.so保存⼀下。如果想⽣成其他ABI架构的so,可以clean后再配置、编译:
make clean
./Configure android-arm64 shared make SHLIB_EXT=.so -j8
2.新建Android项⽬(注意要选中Native C++这个。笔者使⽤环境为Android Studio 4.0,JDK1.8,gradle 6.1.1,gradle plugin 4.0.0),复制openssl源代码⽬录下所有头⽂件(include⽬录),以及上⼀步⽣成的所有.so到Android项⽬中。
项⽬地址:
native-lib.cpp⽰例展⽰了如何使⽤openssl库进⾏RSA加解密、⽣成签名并验证签名。
代码太多,就不⼀⼀列出来内容了,可以clone代码查看内容,只列⼀下build.gradle和CMakeLists.txt主要内容:build.gradle:
android { ......
defaultConfig { ......
externalNativeBuild { cmake {
cppFlags \"-std=c++11 -frtti -fexceptions\" arguments '-DANDROID_STL=c++_shared' } ndk {
stl = \"c++_shared\"
abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a' } } } ......
sourceSets { main {
jniLibs.srcDirs = ['${PROJECT_SOURCE_DIR}/libs'] } }
packagingOptions { pickFirst '**/*.so' }
externalNativeBuild { cmake {
path \"src/main/cpp/CMakeLists.txt\" version \"3.10.2\" } }
}
CMakeLists.txt:
# For more information about using CMake with Android Studio, read the# documentation: https://d.android.com/studio/projects/add-native-code.htmlcmake_minimum_required(VERSION 3.4.1)
set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=gnu++11\")################################################################ import openssl library files BEGINinclude_directories(include)
set(SSL_LIB_NAME ssl)
add_library(${SSL_LIB_NAME} SHARED IMPORTED)
set_target_properties(${SSL_LIB_NAME} PROPERTIES IMPORTED_LOCATION ${PROJECT_SOURCE_DIR}/libs/${ANDROID_ABI}/lib${SSL_LIB_NAME}.so)
set(CRYPTO_LIB_NAME crypto)
add_library(${CRYPTO_LIB_NAME} SHARED IMPORTED)
set_target_properties(${CRYPTO_LIB_NAME} PROPERTIES IMPORTED_LOCATION ${PROJECT_SOURCE_DIR}/libs/${ANDROID_ABI}/lib${CRYPTO_LIB_NAME}.so)# import openssl library files END
###############################################################find_library(log-lib log)add_library(native-lib SHARED native-lib.cpp native-lib.h b64/b64.cpp b64/b64.h
b64/test_b64.cpp b64/test_b64.h rsa/rsa.cpp rsa/rsa.h
rsa/test_rsa.cpp rsa/test_rsa.h common.h)target_link_libraries( native-lib ssl crypto ${log-lib})
因篇幅问题不能全部显示,请点此查看更多更全内容