tar -xzf openssl-3.1.0.tar.gz # Replace with your version
cd openssl-3.1.0
Create a Build Script (e.g., build_openssl_android.sh):
This script will iterate through different Android ABIs and build OpenSSL for each.
bash
#!/bin/bash
# --- CONFIGURATION ---
OPENSSL_VERSION="openssl-3.1.0" # Make sure this matches your downloaded version
ANDROID_NDK_HOME="${HOME}/Android/Sdk/ndk/25.1.8751421" # !!! IMPORTANT: Set your NDK path here !!!
ANDROID_API_LEVEL="21" # Minimum Android API level your app supports (e.g., 21 for Lollipop, 24 for Nougat)
OUTPUT_DIR="./openssl_android_prebuilt" # Where to put the compiled libs and headers
# --- DO NOT MODIFY BELOW THIS LINE ---
if [ ! -d "$ANDROID_NDK_HOME" ]; then
echo "Error: Android NDK not found at $ANDROID_NDK_HOME"
echo "Please update ANDROID_NDK_HOME in the script."
exit 1
fi
echo "Building OpenSSL $OPENSSL_VERSION for Android NDK at $ANDROID_NDK_HOME"
echo "Output will be in: $OUTPUT_DIR"
# Clean previous build artifacts
rm -rf "$OUTPUT_DIR"
mkdir -p "$OUTPUT_DIR/include"
mkdir -p "$OUTPUT_DIR/libs"
# Copy headers
cp -R "${OPENSSL_VERSION}/include/openssl" "${OUTPUT_DIR}/include/"
# Define architectures
declare -A ABIS
ABIS["armeabi-v7a"]="android-arm"
ABIS["arm64-v8a"]="android-arm64"
ABIS["x86"]="android-x86"
ABIS["x86_64"]="android-x86_64"
for ABI in "${!ABIS[@]}"; do
ANDROID_TARGET="${ABIS[$ABI]}"
INSTALL_DIR="${OUTPUT_DIR}/libs/$ABI"
mkdir -p "$INSTALL_DIR"
echo "----------------------------------------------------"
echo "Building for ABI: $ABI ($ANDROID_TARGET)"
echo "----------------------------------------------------"
# Set up NDK paths for this ABI
if [[ "$ANDROID_TARGET" == "android-arm" ]]; then
TOOLCHAIN_NAME="arm-linux-androideabi"
elif [[ "$ANDROID_TARGET" == "android-arm64" ]]; then
TOOLCHAIN_NAME="aarch64-linux-android"
elif [[ "$ANDROID_TARGET" == "android-x86" ]]; then
TOOLCHAIN_NAME="i686-linux-android"
elif [[ "$ANDROID_TARGET" == "android-x86_64" ]]; then
TOOLCHAIN_NAME="x86_64-linux-android"
else
echo "Unknown Android target: $ANDROID_TARGET"
exit 1
fi
TOOLCHAIN="${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/$(uname -s | tr '[:upper:]' '[:lower:]')-x86_64"
export PATH="${TOOLCHAIN}/bin:$PATH"
export CXX="clang++"
export CC="clang"
export AR="${TOOLCHAIN_NAME}-ar"
export RANLIB="${TOOLCHAIN_NAME}-ranlib"
# Clean OpenSSL source tree
make clean > /dev/null 2>&1
# Configure OpenSSL
# no-ssl2 no-ssl3 no-comp: Reduce size, disable old/unsecure protocols, disable compression.
# --prefix: OpenSSL install directory.
# --openssldir: Location for OpenSSL config files (not really used on Android).
./Configure "$ANDROID_TARGET" \
no-ssl2 no-ssl3 no-comp no-shared \
-D__ANDROID_API__=$ANDROID_API_LEVEL
# Build OpenSSL
make -j$(nproc) || { echo "Build failed for $ABI"; exit 1; }
# Copy static libraries (.a) to the output directory
# We'll use static libraries in CMake for simpler integration,
# but you can also build shared libraries by removing `no-shared` above.
cp libcrypto.a "${INSTALL_DIR}/libcrypto.a"
cp libssl.a "${INSTALL_DIR}/libssl.a"
echo "Finished building for ABI: $ABI"
echo "Libraries copied to: ${INSTALL_DIR}"
done
echo "----------------------------------------------------"
echo "OpenSSL build completed for all ABIs."
echo "Headers are in: ${OUTPUT_DIR}/include"
echo "Libraries are in: ${OUTPUT_DIR}/libs/<abi>/"
echo "----------------------------------------------------"
This will create the openssl_android_prebuilt directory containing include and libs for each ABI.
Self-correction/Important Note: The no-shared flag builds static libraries (.a). This is often simpler for Android integration because you don't have to manage .so files for OpenSSL at runtime (they get linked directly into your app's main .so file). If you do need shared libraries, remove no-shared from the Configure line, and copy libcrypto.so and libssl.so instead of .a files.
Part 2: Integrating Compiled OpenSSL into Your Android Studio Project
Create a New Android Studio Project with C++ Support:
Start a new project.
Choose "Native C++" template (or add C++ support to an existing project: File -> New -> New Module -> Android Native Library).
Copy OpenSSL Prebuilt Libraries:
Create a directory, e.g., app/openssl_prebuilt in your Android Studio project.
Copy the openssl_android_prebuilt directory (from Part 1, step 2) into this app/openssl_prebuilt location.
So you'll have app/openssl_prebuilt/include and app/openssl_prebuilt/libs/armeabi-v7a/libcrypto.a, etc.
Configure CMakeLists.txt:
This is the core of integrating your prebuilt OpenSSL libraries.
Open your app/src/main/CMakeLists.txt (or where your native C++ code is built).
cmake
Part 3: Using OpenSSL Functions in C++
Now you can use OpenSSL functions in your native-lib.cpp file.
Example: Generating an SHA256 Hash
cpp
#include <jni.h>
#include <string>
#include <android/log.h>
// OpenSSL headers
#include <openssl/evp.h> // For EVP_Digest functions
#include <openssl/err.h> // For error handling
#define LOG_TAG "NativeLib"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_TAG, LOG_TAG, __VA_ARGS__)
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_your_app_package_MainActivity_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
// Initialize OpenSSL's error reporting.
// Call this once at the start of your app's native code.
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms(); // Not strictly needed for SHA, but good for general use.
std::string hello = "Hello from C++ with OpenSSL!";
const char* input_data = "This is a test string to hash.";
unsigned char md_value[EVP_MAX_MD_SIZE]; // Array to store the hash result
unsigned int md_len; // Length of the hash result
EVP_MD_CTX* md_ctx; // Message Digest Context
md_ctx = EVP_MD_CTX_new();
if (md_ctx == NULL) {
LOGE("EVP_MD_CTX_new failed");
ERR_print_errors_fp(stderr); // Log OpenSSL errors to stderr (visible in logcat)
return env->NewStringUTF("Error hashing!");
}
// Initialize the context for SHA256
if (1 != EVP_DigestInit_ex(md_ctx, EVP_sha256(), NULL)) {
LOGE("EVP_DigestInit_ex failed");
ERR_print_errors_fp(stderr);
EVP_MD_CTX_free(md_ctx);
return env->NewStringUTF("Error hashing!");
}
// Update the hash with input data
if (1 != EVP_DigestUpdate(md_ctx, input_data, strlen(input_data))) {
LOGE("EVP_DigestUpdate failed");
ERR_print_errors_fp(stderr);
EVP_MD_CTX_free(md_ctx);
return env->NewStringUTF("Error hashing!");
}
// Finalize the hash computation
if (1 != EVP_DigestFinal_ex(md_ctx, md_value, &md_len)) {
LOGE("EVP_DigestFinal_ex failed");
ERR_print_errors_fp(stderr);
EVP_MD_CTX_free(md_ctx);
return env->NewStringUTF("Error hashing!");
}
// Free the context
EVP_MD_CTX_free(md_ctx);
// Convert hash to a hex string for display
char hex_hash[EVP_MAX_MD_SIZE * 2 + 1];
for (unsigned int i = 0; i < md_len; i++) {
sprintf(&hex_hash[i * 2], "%02x", md_value[i]);
}
hex_hash[md_len * 2] = '\0'; // Null-terminate the string
LOGD("SHA256 Hash: %s", hex_hash);
// Clean up OpenSSL's error reporting system (optional, good for app exit)
// EVP_cleanup(); // Deprecated in OpenSSL 1.1.0 and later
// ERR_free_strings(); // Not strictly necessary if you only call it once
return env->NewStringUTF(hex_hash);
}
Part 4: JNI Wrapper (Java/Kotlin)
In your MainActivity.java (or Kotlin equivalent):
java
package com.example.your_app_package; // Make sure this matches your actual package name
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.your_app_package.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}
private ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
TextView tv = binding.sampleText;
// Call the C++ function
String hashResult = stringFromJNI();
tv.setText(hashResult);
}
/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native String stringFromJNI();
}
Important Considerations:
OpenSSL Version: Always use a recent, supported version of OpenSSL. Older versions might have known vulnerabilities.
Licensing: OpenSSL is released under the Apache 2.0 license. Ensure your usage complies with its terms.
Security:
Keep OpenSSL updated: Regularly update your prebuilt libraries when new OpenSSL versions are released, especially for security fixes.
Use secure random numbers: If you're generating keys or salts, use RAND_bytes() or similar OpenSSL functions, which are cryptographically secure. Don't use rand().
Error Handling: Always check the return values of OpenSSL functions and use ERR_print_errors_fp() or ERR_get_error() to diagnose issues.
Memory Management: OpenSSL objects often have dedicated _free() functions (e.g., EVP_MD_CTX_free()). Make sure you call them to prevent memory leaks.
Alternatives:
BoringSSL: Google's fork of OpenSSL. It's what Android itself uses internally for many cryptographic operations. It's often harder to integrate directly as a separate library due to its tight integration with Android's build system, but if you're doing very deep system-level work, it might be relevant.
Conscrypt: A Java Security Provider that implements many crypto algorithms. On modern Android versions, Conscrypt uses BoringSSL under the hood, effectively giving you high-performance native crypto via Java APIs. This is often the recommended approach if you don't have a compelling reason to drop to C++ directly.
JCE (Java Cryptography Extension): The standard Java API for cryptography. While often slower than native implementations for very large data, it's platform-independent and much easier to use from Java/Kotlin.
When to use C++ with OpenSSL directly?
You have existing C/C++ code that heavily relies on OpenSSL and migrating it to Java/Kotlin is not feasible.
You need very specific, low-level control over cryptographic operations that are not easily exposed via higher-level Java APIs.
You are trying to optimize for extreme performance in very specific scenarios where the JCE/Conscrypt overhead is a bottleneck (rare for most apps).
For most common cryptographic needs (hashing, symmetric encryption, basic TLS client connections), using the Java/Kotlin APIs provided by Android (which often leverage native implementations internally) is simpler and generally preferred.
# For your native library
cmake_minimum_required(VERSION 3.22.1) # Or your NDK's required CMake version
# Set up where to find OpenSSL prebuilt libraries
set(OPENSSL_PREBUILT_DIR ${CMAKE_SOURCE_DIR}/../openssl_prebuilt) # Relative path from CMakeLists.txt to openssl_prebuilt
# Add OpenSSL include directories
include_directories(${OPENSSL_PREBUILT_DIR}/include)
# --- Define and link OpenSSL libraries for each ABI ---
# We define them as IMPORTED STATIC libraries, then link against them.
# This assumes you built static libraries (.a) in Part 1 with `no-shared`.
# Common definitions
add_library(crypto STATIC IMPORTED)
add_library(ssl STATIC IMPORTED)
# Set properties for each ABI
if (ANDROID_ABI STREQUAL "armeabi-v7a")
set_target_properties(crypto PROPERTIES IMPORTED_LOCATION ${OPENSSL_PREBUILT_DIR}/libs/armeabi-v7a/libcrypto.a)
set_target_properties(ssl PROPERTIES IMPORTED_LOCATION ${OPENSSL_PREBUILT_DIR}/libs/armeabi-v7a/libssl.a)
elseif (ANDROID_ABI STREQUAL "arm64-v8a")
set_target_properties(crypto PROPERTIES IMPORTED_LOCATION ${OPENSSL_PREBUILT_DIR}/libs/arm64-v8a/libcrypto.a)
set_target_properties(ssl PROPERTIES IMPORTED_LOCATION ${OPENSSL_PREBUILT_DIR}/libs/arm64-v8a/libssl.a)
elseif (ANDROID_ABI STREQUAL "x86")
set_target_properties(crypto PROPERTIES IMPORTED_LOCATION ${OPENSSL_PREBUILT_DIR}/libs/x86/libcrypto.a)
set_target_properties(ssl PROPERTIES IMPORTED_LOCATION ${OPENSSL_PREBUILT_DIR}/libs/x86/libssl.a)
elseif (ANDROID_ABI STREQUAL "x86_64")
set_target_properties(crypto PROPERTIES IMPORTED_LOCATION ${OPENSSL_PREBUILT_DIR}/libs/x86_64/libcrypto.a)
set_target_properties(ssl PROPERTIES IMPORTED_LOCATION ${OPENSSL_PREBUILT_DIR}/libs/x86_64/libssl.a)
endif()
# Your native application library
add_library( # Sets the name of the library.
native-lib
SHARED
src/main/cpp/native-lib.cpp ) # Your source file
# Search for other native libraries.
find_library( # Sets the name of the path variable.
log-lib
log )
# Link your native library against OpenSSL and other Android system libraries
target_link_libraries( # Specifies the target library for which to add libraries.
native-lib
crypto # Link to OpenSSL crypto library
ssl # Link to OpenSSL ssl library
${log-lib} ) # Link to the Android 'log' library