在Linux内核空间中计算MD5值

使用Crypto API。

代码示例:

#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <crypto/hash.h> //md5

#define DATA_LEN 1000

bool md5_hash(char *result, char* data, size_t len)
{
    size_t size = 0;
    struct shash_desc *desc;
    struct crypto_shash **shash = NULL;

    shash = kmalloc(sizeof(struct crypto_shash*), GFP_KERNEL);
    if(NULL == shash)
    {
         return false;
    }
    *shash = crypto_alloc_shash("md5", 0, CRYPTO_ALG_ASYNC);
    size = sizeof(struct shash_desc) + crypto_shash_descsize(*shash);
    desc = kmalloc(size, GFP_KERNEL);
    if(desc == NULL)
    {
        return false;
    }
    desc->tfm = *shash;

    crypto_shash_init(desc);
    crypto_shash_update(desc, data, len);
    crypto_shash_final(desc, result);
    crypto_free_shash(desc->tfm);

    kfree(shash);
    kfree(desc);
    return true;
}

char data[DATA_LEN] = {0};
static int __init rtl_init(void)
{
    bool ret = false;
    char result[16];
    size_t len = DATA_LEN;
    ret = md5_hash(result, data, len);
    printk("result:%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x, len:%lu.", 
           result[0] & 0xFFu, result[1] & 0xFFu, result[2] & 0xFFu, result[3] & 0xFFu,         
           result[4] & 0xFFu, result[5] & 0xFFu, result[6] & 0xFFu, result[7] & 0xFFu, 
           result[0] & 0xFFu, result[1] & 0xFFu, result[2] & 0xFFu, result[3] & 0xFFu,         
           result[4] & 0xFFu, result[5] & 0xFFu, result[6] & 0xFFu, result[7] & 0xFFu,
           strlen(result));
    return 0;
}

static void __exit rtl_exit(void)
{
}

module_init(rtl_init);
module_exit(rtl_exit);

MODULE_LICENSE("GPL");

参考链接:https://stackoverflow.com/questions/11126027/using-md5-in-kernel-space-of-linux

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值