最近在做android native layer的三种加密代码书写,可惜我的c和c ++实现太烂,只能去github上找找资源,md5和base64的加密比较简单,自己梳理了一下,完美运行起来了。就是sha256实现起来有点烦,折腾了好几天,找了一个只能在32位的android机子上运行起来,64位机子就出现了问题,故舍弃,最后黄天不负有心人,终于解决了sha256的问题。以下是cmake编译的配置文件
cmake_minimum_required(VERSION 3.4.1) file(GLOB_RECURSE cpp_srcs_h "src/main/cpp/header/*.h") #添加该目录下的所有h文件 file(GLOB_RECURSE cpp_srcs_c "src/main/cpp/*.c") #添加该目录下的所有c文件 file(GLOB_RECURSE cpp_srcs_cpp "src/main/cpp/*.cpp") #添加该目录下的所有cpp文件 #add_compile_options(-std=c++11) set(cpp_srcs ${cpp_srcs_h} ${cpp_srcs_c} ${cpp_srcs_cpp} ) add_library( # Sets the name of the library. native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ${cpp_srcs} ) find_library( # Sets the name of the path variable. log-lib # Specifies the name of the NDK library that # you want CMake to locate. log ) target_link_libraries( # Specifies the target library. native-lib # Links the target library to the log library # included in the NDK. ${log-lib} )
activity的代码很简单:
package com.example.jacky.myso; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class MainActivity extends AppCompatActivity { // Used to load the 'native-lib' library on application startup. static { System.loadLibrary("native-lib"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("ddd",md5("123")); Log.d("ddd",base64("123")); Log.d("ddd",sha256("123")); } /** * A native method that is implemented by the 'native-lib' native library, * which is packaged with this application. */ public native String md5(String str); public native String base64(String str); public native String sha256(String str); }
运行结果:
05-12 11:32:58.529 7537-7537/com.example.jacky.myso D/ddd: 202cb962ac59075b964b07152d234b70
05-12 11:32:58.530 7537-7537/com.example.jacky.myso D/ddd: MTIz
05-1211:32:58.5307537-7537/com.example.jacky.mysoD/ddd: a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3
运行结果可以去在线网站进行对比:http://tool.oschina.net/encrypt?type=3
c和c++代码资源文件请点击下载:代码下载