安卓 native加密(md5,base64和sha256)

本文分享了作者在Android Native层实现MD5、Base64及SHA256加密过程中的经验,特别是解决SHA256在不同架构设备上的兼容性问题。提供了CMake配置示例与活动代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在做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++代码资源文件请点击下载:代码下载


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值