Интегрировать Crypto ++ в Android с помощью Android.mk? - PullRequest
0 голосов
/ 09 апреля 2019

Я хочу интегрировать модуль cryptopp в мое приложение для Android. Я пытался, но не смог добиться успеха, а также не нашел ни одного прямого документа или примера для Android.

Структура проекта: http://prntscr.com/n9g0k9

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId ""
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        ndk {
            moduleName "cryptopp"
        }
    }

    sourceSets.main {
        jni.srcDirs = [] // This prevents the auto generation of Android.mk
        jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
    }


    task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
        def ndkDir = android.ndkDirectory
        commandLine "$ndkDir/ndk-build",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                '-j', Runtime.runtime.availableProcessors(),
                'all',
                'NDK_DEBUG=1'
    }

    task cleanNative(type: Exec, description: 'Clean JNI object files') {
        def ndkDir = android.ndkDirectory
        commandLine "$ndkDir/ndk-build",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                'clean'
    }

    clean.dependsOn 'cleanNative'

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn buildNative
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    /*externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
        }
    }*/
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'

    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

Android.mk

## Android.mk - Android build file for Crypto++. Written and placed in
##              public domain by Jeffrey Walton. Based on Android.mk
##              by Alex Afanasyev (GitHub @cawka),
##              https://github.com/weidai11/cryptopp/pull/3
##
##              The Android make uses GNU Make and is documented at
##              https://developer.android.com/ndk/guides/android_mk
##              The CPU Features library is documented at
##              https://developer.android.com/ndk/guides/cpu-features
##
##              You can create the list of files below with:
##
##                  $ make sources | fold -w74 -s
##

## TODO - We use this line below in the .mk file:
##            LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/..
## The open question is, should we be exporting the path as:
##            LOCAL_EXPORT_C_INCLUDES := $(CRYPTOPP_PATH)

ifeq ($(NDK_LOG),1)
    $(info Crypto++: TARGET_ARCH: $(TARGET_ARCH))
    $(info Crypto++: TARGET_PLATFORM: $(TARGET_PLATFORM))
endif

LOCAL_PATH := $(call my-dir)

#####################################################################
# Adjust CRYPTOPP_PATH to suit your taste, like ../cryptopp-7.1/.
# If CRYPTOPP_PATH is empty then it means the library files and the
# Android files are side-by-side in the same directory. If
# CRYPTOPP_PATH is not empty then must include the trailing slash.
# The trailing slash is needed because CRYPTOPP_PATH is prepended
# to each source file listed in CRYPTOPP_SRC_FILES.

# CRYPTOPP_PATH ?= ../cryptopp/
CRYPTOPP_PATH ?=

ifeq ($(NDK_LOG),1)
  ifeq ($CRYPTOPP_PATH),)
    $(info Crypto++: CRYPTOPP_PATH is empty)
  else
    $(info Crypto++: CRYPTOPP_PATH is $(CRYPTOPP_PATH))
  endif
endif

#####################################################################
# Library source files

CRYPTOPP_SRC_FILES := \
    cryptlib.cpp cpu.cpp integer.cpp 3way.cpp adler32.cpp algebra.cpp login_connection.cpp \
    algparam.cpp arc4.cpp aria_simd.cpp aria.cpp ariatab.cpp asn.cpp \
    authenc.cpp base32.cpp base64.cpp basecode.cpp bfinit.cpp \
    blake2.cpp blowfish.cpp blumshub.cpp camellia.cpp cast.cpp casts.cpp \
    cbcmac.cpp ccm.cpp chacha_simd.cpp chacha.cpp cham_simd.cpp cham.cpp \
    channels.cpp cmac.cpp crc_simd.cpp crc.cpp default.cpp des.cpp dessp.cpp \
    dh.cpp dh2.cpp dll.cpp dsa.cpp eax.cpp ec2n.cpp eccrypto.cpp ecp.cpp \
    elgamal.cpp emsa2.cpp eprecomp.cpp esign.cpp files.cpp filters.cpp \
    fips140.cpp fipstest.cpp gcm_simd.cpp gcm.cpp gf256.cpp gf2_32.cpp \
    gf2n.cpp gfpcrypt.cpp gost.cpp gzip.cpp hc128.cpp hc256.cpp hex.cpp \
    hight.cpp hmac.cpp hrtimer.cpp ida.cpp idea.cpp iterhash.cpp kalyna.cpp \
    kalynatab.cpp keccak.cpp lea_simd.cpp lea.cpp luc.cpp mars.cpp \
    marss.cpp md2.cpp md4.cpp md5.cpp misc.cpp modes.cpp mqueue.cpp mqv.cpp \
    nbtheory.cpp neon_simd.cpp oaep.cpp osrng.cpp padlkrng.cpp panama.cpp \
    pkcspad.cpp poly1305.cpp polynomi.cpp ppc_simd.cpp pssr.cpp pubkey.cpp \
    queue.cpp rabbit.cpp rabin.cpp randpool.cpp rc2.cpp rc5.cpp rc6.cpp \
    rdrand.cpp rdtables.cpp rijndael_simd.cpp rijndael.cpp ripemd.cpp rng.cpp \
    rsa.cpp rw.cpp safer.cpp salsa.cpp scrypt.cpp seal.cpp seed.cpp \
    serpent.cpp sha_simd.cpp sha.cpp sha3.cpp shacal2_simd.cpp shacal2.cpp \
    shark.cpp sharkbox.cpp simeck_simd.cpp simeck.cpp simon.cpp \
    simon128_simd.cpp simon64_simd.cpp skipjack.cpp sm3.cpp sm4_simd.cpp \
    sm4.cpp sosemanuk.cpp speck.cpp speck128_simd.cpp speck64_simd.cpp \
    square.cpp squaretb.cpp sse_simd.cpp strciphr.cpp tea.cpp tftables.cpp \
    threefish.cpp tiger.cpp tigertab.cpp ttmac.cpp tweetnacl.cpp twofish.cpp \
    vmac.cpp wake.cpp whrlpool.cpp xtr.cpp xtrcrypt.cpp zdeflate.cpp \
    zinflate.cpp zlib.cpp

#####################################################################
# Test source files

# Remove adhoc.cpp from this list

CRYPTOPP_TEST_FILES := \
    test.cpp bench1.cpp bench2.cpp bench3.cpp datatest.cpp \
    dlltest.cpp fipsalgt.cpp validat0.cpp validat1.cpp validat2.cpp \
    validat3.cpp validat4.cpp validat5.cpp validat6.cpp validat7.cpp \
    validat8.cpp validat9.cpp validat10.cpp regtest1.cpp regtest2.cpp \
    regtest3.cpp regtest4.cpp

#####################################################################
# ARM A-32 source file

ifeq ($(TARGET_ARCH),arm)
    CRYPTOPP_SRC_FILES += aes_armv4.S
    LOCAL_ARM_MODE := arm
    LOCAL_FILTER_ASM :=
endif

#####################################################################
# Shared object

include $(CLEAR_VARS)
LOCAL_MODULE := cryptopp_shared
LOCAL_SRC_FILES := $(addprefix $(CRYPTOPP_PATH),$(CRYPTOPP_SRC_FILES))
LOCAL_CPPFLAGS := -Wall
LOCAL_CPP_FEATURES := rtti exceptions
LOCAL_LDFLAGS := -Wl,--exclude-libs,ALL -Wl,--as-needed

LOCAL_EXPORT_CFLAGS := $(LOCAL_CFLAGS)
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/..

LOCAL_STATIC_LIBRARIES := cpufeatures

include $(BUILD_SHARED_LIBRARY)

#####################################################################
# Static library

include $(CLEAR_VARS)
LOCAL_MODULE := cryptopp_static
LOCAL_SRC_FILES := $(addprefix $(CRYPTOPP_PATH),$(CRYPTOPP_SRC_FILES))
LOCAL_CPPFLAGS := -Wall
LOCAL_CPP_FEATURES := rtti exceptions

LOCAL_EXPORT_CFLAGS := $(LOCAL_CFLAGS)
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/..

LOCAL_STATIC_LIBRARIES := cpufeatures

include $(BUILD_STATIC_LIBRARY)

#####################################################################
# Test program

include $(CLEAR_VARS)
LOCAL_MODULE := cryptest.exe
LOCAL_SRC_FILES := $(addprefix $(CRYPTOPP_PATH),$(CRYPTOPP_TEST_FILES))
LOCAL_CPPFLAGS := -Wall
LOCAL_CPP_FEATURES := rtti exceptions
LOCAL_LDFLAGS := -Wl,--as-needed

LOCAL_STATIC_LIBRARIES := cryptopp_static
include $(BUILD_EXECUTABLE)

#####################################################################
# Android cpuFeatures library

$(call import-module,android/cpufeatures)

Application.mk

## Application.mk - Android build file for Crypto++. Written and placed
##            in public domain by Jeffrey Walton. Based on
##            Application.mk by Alex Afanasyev (GitHub @cawka),
##            https://github.com/weidai11/cryptopp/pull/3
##
##            The Android make uses GNU Make and is documented at
##            https://developer.android.com/ndk/guides/android_mk
##
##            For a list of Android Platforms and API levels see
##            https://developer.android.com/ndk/guides/stable_apis
##            Android 4.3 is android-18, and Android 5 is android-21.
##
##            Android recommends c++_shared for NDK version 16.0 and
##            above. Android will be removing other runtime libraries
##            as early as NDK version 18. Also see
##            https://developer.android.com/ndk/guides/cpp-support.

APP_ABI := all
APP_PLATFORM := android-21

# APP_STL := gnustl_shared
APP_STL := c++_shared

CRYPTOPP_ROOT := $(call my-dir)
NDK_PROJECT_PATH := $(CRYPTOPP_ROOT)
APP_BUILD_SCRIPT := $(CRYPTOPP_ROOT)/Android.mk

GREP ?= grep
NDK_r16_OR_LATER := $(shell $(GREP) -i -c -E "Pkg.Revision = (1[6-9]|[2-9][0-9]\.)" "$$ANDROID_NDK_ROOT/source.properties")
ifneq ($(NDK_r16_OR_LATER),0)
  ifneq ($(APP_STL),c++_shared)
    $(info Crypto++: NDK r16 or later. Use c++_shared instead of $(APP_STL))
  endif
endif

ifeq ($(NDK_LOG),1)
    $(info Crypto++: ANDROID_NDK_ROOT is $(ANDROID_NDK_ROOT))
    $(info Crypto++: NDK_PROJECT_PATH is $(NDK_PROJECT_PATH))
    $(info Crypto++: APP_BUILD_SCRIPT is $(APP_BUILD_SCRIPT))
endif

ifeq ($(MAKECMDGOALS),debug) # template for conditional rules
   C_SOURCE_FILES += uart.c
endif

И ниже команда, которую я выполняю в терминале

:cryptopp user$ ndk-build V=1 NDK_PROJECT_PATH="$PWD" NDK_APPLICATION_MK="$PWD/Application.mk"

1 Ответ

0 голосов
/ 11 апреля 2019

Я хочу интегрировать модуль cryptopp в мое приложение для Android. Я пытался, но не смог добиться успеха, а также не нашел ни одного прямого документа или примера для Android.

Документы, которые вы ищете, находятся на вики Crypto ++ на Настройка Android (командная строка) и Android.mk (командная строка) . В первой статье вики рассказывается, как настроить машину для сборки Android. Или, может быть, более правильно, как Crypto ++ настраивает машину для сборки Android для тестирования. Во второй статье вики рассказывается, как собирать с помощью Android.mk и Application.mk, если у вас есть машина для сборки Android.

Когда я выполняю сборку, используя статьи в вики, я вижу:

cryptopp$ ndk-build NDK_PROJECT_PATH="$PWD" NDK_APPLICATION_MK="$PWD/Application.mk"
[arm64-v8a] Compile++      : cryptest.exe <= test.cpp
[arm64-v8a] Compile++      : cryptest.exe <= bench1.cpp
[arm64-v8a] Compile++      : cryptest.exe <= bench2.cpp
[arm64-v8a] Compile++      : cryptest.exe <= bench3.cpp
[arm64-v8a] Compile++      : cryptest.exe <= datatest.cpp
[arm64-v8a] Compile++      : cryptest.exe <= dlltest.cpp
[arm64-v8a] Compile++      : cryptest.exe <= fipsalgt.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat0.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat1.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat2.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat3.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat4.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat5.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat6.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat7.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat8.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat9.cpp
[arm64-v8a] Compile++      : cryptest.exe <= validat10.cpp
[arm64-v8a] Compile++      : cryptest.exe <= regtest1.cpp
[arm64-v8a] Compile++      : cryptest.exe <= regtest2.cpp
[arm64-v8a] Compile++      : cryptest.exe <= regtest3.cpp
[arm64-v8a] Compile++      : cryptest.exe <= regtest4.cpp
[arm64-v8a] Prebuilt       : libc++_shared.so <= <NDK>/sources/cxx-stl/llvm-libc++/libs/arm64-v8a/
[arm64-v8a] Compile++      : cryptopp_static <= cryptlib.cpp
[arm64-v8a] Compile++      : cryptopp_static <= cpu.cpp
[arm64-v8a] Compile++      : cryptopp_static <= integer.cpp
[arm64-v8a] Compile++      : cryptopp_static <= 3way.cpp
[arm64-v8a] Compile++      : cryptopp_static <= adler32.cpp
[arm64-v8a] Compile++      : cryptopp_static <= algebra.cpp
[arm64-v8a] Compile++      : cryptopp_static <= algparam.cpp
[arm64-v8a] Compile++      : cryptopp_static <= arc4.cpp
[arm64-v8a] Compile++      : cryptopp_static <= aria_simd.cpp
[arm64-v8a] Compile++      : cryptopp_static <= aria.cpp
[arm64-v8a] Compile++      : cryptopp_static <= ariatab.cpp
[arm64-v8a] Compile++      : cryptopp_static <= asn.cpp
[arm64-v8a] Compile++      : cryptopp_static <= authenc.cpp
...

При наличии достаточного количества времени и дискового пространства ndk-build создаст все архитектуры Android.

Я не знаю, как использовать Kotlin или другие системы сборки, такие как Maven. Я ими не пользуюсь, поэтому не могу помочь, если твоя проблема лежит там.

Я думаю, вам нужно указать ошибки, с которыми вы сталкиваетесь, чтобы люди знали, как вам помочь.


Примечание : cryptopp-android ранее отсутствовали теги, которые следовали за выпусками Crypto ++. Мы исправили это сегодня вечером, но вернемся только к Crypto ++ 7.0. Вы должны убедиться, что вы загрузили cryptopp-android релиз , который соответствует используемой вами версии Crypto ++. Они используют те же теги, как CRYPTOPP_7_0_0, CRYPTOPP_8_0_0 и CRYPTOPP_8_1_0. Мастер должен примерно следовать за мастером в обоих проектах.

...