Android下使用Openssl库
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项目中。
项目地址:https://github.com/areful/NdkUseOpenssl
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.html cmake_minimum_required(VERSION 3.4.1) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11") ############################################################### # import openssl library files BEGIN include_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})