美文网首页
Android端使用国密SM2进行加密

Android端使用国密SM2进行加密

作者: 王煜仁 | 来源:发表于2023-08-14 17:23 被阅读0次

前言

最近研究SM2加密在app中的应用,在掉了1024根头发的时候,终于给找到解决方案了。

背景

项目中使用的是签发公私钥证书进行的加解密的,证书的格式为.cer文件格式。也就是app端在应用中载入公钥,然后调用SM2的加密方法对数据进行加密,将加密的数据传给后端,后端通过对应的私钥解密。
long long ago,在iOS系统进行过一次大版本的升级过后,iPhone端的SM2加密就失效了,官方的原生方法无法读取.cer文件,这样就无法获取到证书中的公钥,也就无法完成整个加密过程了。
而今在Android端也出现了这样的问题,大概看了一下项目中使用的一些第三方框架,大体就是对官方这样的方法做了几层封装,然后将国密的一些加密方式整合在一起。所以这样的第三方框架已经无法继续使用。
没办法,项目还坚持使用SM2进行加密,那么只能继续寻找解决办法。作为一个非专业Android开发者来说,具有钻研的精神可能是我最后的倔强了。首先是全网各种查找方案,无一例外,都是老旧的实现方法,中间确实想过放弃,也讨论过切换加密方案,但是又需要考虑切换加密方案对用户的影响已经各端的工作量,也就暂时搁浅了。
大概是思维进入死胡同了,漫无目的的看着各种各样的处理方法。最后还是回归到原始方法。

解决方案

方法一
dependencies {
    // 强强联手
    implementation 'cn.hutool:hutool-all:5.8.21'
    implementation 'org.bouncycastle:bcprov-jdk15to18:1.76'
}
  • 实现
// 重要的导包
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import java.security.PublicKey;

import org.bouncycastle.asn1.DERBitString;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.util.encoders.Hex;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import cn.hutool.crypto.ECKeyUtil;

try {
            // 将.cer文件放置在Android应用的res/raw目录下。如果该目录不存在,可以手动创建它。
            // 请确保将your_certificate替换为你实际的.cer文件的名称,而且要处理异常以确保代码的健壮性。
            InputStream is = getResources().openRawResource(R.raw. your_certificate);  // 读取.cer文件,不限于这种读取方式
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate)cf.generateCertificate(is);
            is.close();

            PublicKey pk = cert.getPublicKey();
            byte[] pubkey = pk.getEncoded();
            byte[] publicKey_XY = readPublicKey(pubkey);
            // 获取公钥值,在公钥的前面加上04前缀
            String pubkeyStr = "04" + bytesToHex(publicKey_XY);
            // 待加密内容
            String jsonStr = "{\"name\":\"zhangsan\",\"userid\":\"1234567890\"}";
            final SM2 sm2 = new SM2(null, ECKeyUtil.toSm2PublicParams(pubkeyStr));
            sm2.usePlainEncoding();
            // jsonStr通过公钥加密后的加密内容,转成十六进制
            String encryptStr = sm2.encryptHex(jsonStr, KeyType.PublicKey).toUpperCase();

            System.out.println(encryptStr);
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

public static byte[] readPublicKey(byte[] pubkey) throws Exception {
        SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(pubkey);
        DERBitString publicKeyData = (DERBitString) subjectPublicKeyInfo.getPublicKeyData();
        byte[] publicKey = publicKeyData.getEncoded();
        byte[] encodedPublicKey = publicKey;
        byte[] ecP = new byte[64];
        System.arraycopy(encodedPublicKey, 4, ecP, 0, ecP.length);

        // 公钥的X值
        byte[] certPKX = new byte[32];
        // 公钥的Y值
        byte[] certPKY = new byte[32];
        System.arraycopy(ecP, 0, certPKX, 0, 32);
        System.arraycopy(ecP, 32, certPKY, 0, 32);

        return ecP;
}

    /**
     * 字节转16进制
     * @param b 字节
     * @return 返回转换后的十六进制值
     */
    public static String byteToHex(byte b) {
        String hexString = Integer.toHexString(b & 0xFF);
        if (hexString.length() < 2) {
            hexString = new StringBuilder(String.valueOf(0)).append(hexString).toString();
        }
        return hexString.toUpperCase(Locale.ROOT);
    }

    /**
     * 字节数组转16进制
     * @param bytes 字节数组
     * @return 返回十六进制字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer buffer = new StringBuffer();
        if (bytes != null && bytes.length > 0) {
            for (int i = 0; i < bytes.length; i++) {
                String hex = byteToHex(bytes[i]);
                buffer.append(hex);
            }
        }
        return buffer.toString();
    }
方法二
  • 使用OpenSSL库或者使用gmssl
    两大利器,都是从c++底层去处理证书文件结构,这个就不会受系统大版本升级影响了。我的iOS端app内就是使用OpenSSL的方式去实现的。
    首先需要在Android端配置支持C++混合开发的环境,见官方介绍
  • native-lib.cpp
#include <jni.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include "openssl/crypto.h"
#include "openssl/x509.h"

using namespace std;

extern "C" JNIEXPORT jstring JNICALL
Java_com_zsplat_opensslsupportedapp_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    unsigned char usrCertificate[4096];
    const unsigned char *certDataBytes = NULL;
    unsigned long usrCertificateLen;
    X509 *x509Cert = NULL;
    FILE *fp = NULL;
    fp = fopen("./app/src/main/cpp/test.cer", "rb");
    if (fp == NULL) {
        cout << "读取文件错误。。。" << endl;
    } else {

        usrCertificateLen = fread(usrCertificate, 1, 4096, fp);
        fclose(fp);
        certDataBytes = usrCertificate;
        x509Cert = d2i_X509(NULL, &certDataBytes, usrCertificateLen);
        if (x509Cert == NULL) {
            cout << "x509错误" << endl;
            return "";
        }
        ASN1_BIT_STRING *pubkey = X509_get0_pubkey_bitstr(x509Cert);
        for (int i = 0; i < pubkey->length; i++) {
            // 打印公钥
            printf("%02x", pubkey->data[i]);
            // 将(char *)data数据转为string
        }
        // 返回公钥即可
    }

    return env->NewStringUTF(OpenSSL_version(OPENSSL_VERSION));
}
  • CMakeLists.txt
# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Declares and names the project.

project("native-lib")

#将openssl的头文件目录包含进来
include_directories(src/main/cpp)

#添加两个静态库文件
add_library(
        openssl-crypto
        STATIC
        IMPORTED)
set_target_properties(
        openssl-crypto
        PROPERTIES
        IMPORTED_LOCATION
        ${CMAKE_SOURCE_DIR}/src/main/cpp/libs/libcrypto.a)

add_library(
        openssl-ssl
        STATIC
        IMPORTED)
set_target_properties(
        openssl-ssl
        PROPERTIES
        IMPORTED_LOCATION
        ${CMAKE_SOURCE_DIR}/src/main/cpp/libs/libssl.a)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.

add_library( # Sets the name of the library.
#        opensslsupportedapp
        native-lib
        # Sets the library as a shared library.
        # SHARED不注释程序会报错,项目启动闪退,不知道是不是这边造成的,还没找到解决办法
#        SHARED
        # Provides a relative path to your source file(s).
        native-lib.cpp)

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

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)

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
#        opensslsupportedapp
        native-lib
        # Links the target library to the log library
        # included in the NDK.
        ${log-lib}
        openssl-ssl
        openssl-crypto)

项目中的.a静态文件库是使用NDK和OpenSSL源码编译的,根据Android Studio中使用的NDK版本去做编译。具体编译方法可以去搜索。后续抽空写一个关于编译OpenSSL静态库的操作吧。

可能安卓端配置C++环境对我来说稍微麻烦点,不过只要配置好,那是真的方便,对于大部分加密的问题,OpenSSL都能解决的。

相关文章

  • SM2国密算法封装 C++

    背景介绍: 项目应某客户要求,需要对密码等安全属性要求高的字段进行加密保护与传输,并且必须使用国密(SM2, SM...

  • 国密sm2,sm4(前台vue,后台java)加解密

    项目背景 项目改造需要使用国密sm2,sm4加密SM2SM2为非对称加密,基于ECC。该算法已公开。由于该算法基于...

  • python实现sm2、sm3、sm4算法计算

    安装: pip 安装 SM2 国密公钥加解密签名验签 a. 密钥生成 签名 验签 加密 解密 SM3 国密哈希 a...

  • 椭圆加密简介

    椭圆加密算法 区块链入门时候最难理解的应该就时候这个椭圆加密算法,椭圆加密算法用于生成公钥生成,现在国密SM2算法...

  • SM2 裸签名

    最近在处理一个需求,使用国密SM2进行签名,在实际需求中有这样的一个场景:对PDF进行签名,其实是签署PDF sm...

  • 交叉编译openssl、gmssl的正确方式

    最近要在arm设备上使用国密sm2、sm3算法,经了解,gmssl(openssl分支)能够支持,而且最新的ope...

  • gmssl java api 编译

    GmSSL是一个开源的密码工具箱,支持SM2/SM3/SM4/SM9等国密(国家商用密码)算法、SM2国...

  • 加密

    对称加密: 原理:使用秘钥和加密算法对数据进行转换,得到的无意义数据即为密文;使用密钥和解密算法对密文进行逆向转换...

  • 国密SM2 SM3 SM4 SM9 ZUC EEA3 EIA3

    OpenSSL 1.1.1 国密SM2 SM3 SM4 SM9 ZUC EEA3 EIA3 SM2 +SM3签名 ...

  • 【项目收集】好的的github项目

    未完待续 1、SM2/SM3/SM4 基于BC库:国密SM2/SM3/SM4算法简单封装;实现SM2 X509v3...

网友评论

      本文标题:Android端使用国密SM2进行加密

      本文链接:https://www.haomeiwen.com/subject/dhlcmdtx.html