Linux Kernel(Android) 加密算法总结(四)-应用程序调用OpenSSL加密算法

Linux Kernel(Android) 加密算法总结(三)-应用程序调用内核加密算法接口

讲到了如何调用内核中的接口的方法。

本节主要是介绍如何Android C/C++应用程序调用Openssl的AES加密算法。


crypt_ssl.c


#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <aes.h>
#include <sys/socket.h>
#include <linux/if_alg.h>
#include <evp.h>


#include <stdio.h>
#include <stdlib.h>

#ifndef AF_ALG
    #define AF_ALG 38
    #define SOL_ALG 279
#endif

#define BUF_SIZE 16


static void crypt_ssl(char *in, int inlen, char *out,const char *key, char *iv)
{
    AES_KEY akey;
    AES_set_encrypt_key(key, 128, &akey);
    AES_cbc_encrypt(in, out, inlen, &akey, iv, 1);
}

int main(int argc, char **argv)
{
    int i;
    char out[BUF_SIZE] = {0};
    char in[BUF_SIZE] = "Single block msg";
    const char key[16] =
    "x06xa9x21x40x36xb8xa1x5b"
    "x51x2ex03xd5x34x12x00x06";
    char iv[16] =
    "x3dxafxbax42x9dx9exb4x30"
    "xb4x22xdax80x2cx9fxacx41";

    if(argc != 2)
    {
        printf("usage:compare openssl / compare kernel \n");
    }

    if(strncmp(argv[1], "openssl", 7) == 0)
    {
        printf("encrypt by openssl...n");
        crypt_ssl(in, BUF_SIZE, out, key, iv);
    }

    for (i = 0; i < BUF_SIZE; i )
        printf("0x", (unsigned char)out[i]);
    printf("n");
    return 0;
} 

在Android 源代码编译文件:

Android.mk


LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE := myencrypt

LOCAL_MODULE_TAGS := optional

LOCAL_SRC_FILES :=     crypt_ssl.c

LOCAL_SHARED_LIBRARIES :=     libdl      liblog     libcrypto

LOCAL_C_INCLUDES :=     external/openssl/include/openssl     external/openssl/include

include $(BUILD_EXECUTABLE)


编译完成后在

adb push testhash /system/bin/

adb shell chmod a+x /system/bin/testhash

adb shell testhash

验证输出结果.

Linux Kernel(Android) 加密算法总结(四)-应用程序调用OpenSSL加密算法

上一篇:windows server 2012安装.net framework3.5失败解决方法


下一篇:Ubuntu 32下Android NDK+NEON的配置过程及简单使用举例