1

我正在尝试使用 md5 算法(md5.h 和 md5.c)的内核空间实现。事实证明,md5.h 没有声明 md5.c 中的函数,所以我不能简单地将 md5.h 包含到我的 c 文件中。我还想避免更改 md5.h 来声明函数,因为这可能会产生意想不到的后果。还有其他方法可以在内核空间中使用 md5 吗?

4

4 回答 4

1

Use Crypto API instead of rolling your own.

于 2012-06-20T18:42:22.830 回答
0

请注意,wande chen发布的代码会导致内核堆损坏。

结构 shash_desc *desc;

desc = kmalloc(sizeof(*desc), GFP_KERNEL);

desc->tfm = crypto_alloc_shash("md5", 0, CRYPTO_ALG_ASYNC);

这是因为 md5 引擎将使用struct shash_desc 之后的内存来存储 md5 上下文。

可以在这里找到分配struct shash_desc的正确方法。

*shash = crypto_alloc_shash(name, 0, 0);

大小 = sizeof(struct shash_desc) + crypto_shash_descsize(*shash);

*sdesc = kmalloc(大小, GFP_KERNEL);

于 2020-03-23T12:54:30.947 回答
0
struct sdesc {
    struct shash_desc shash;
    char ctx[];
};

static struct sdesc *init_sdesc(struct crypto_shash *alg)
{
    struct sdesc *sdesc;
    int size;

    size = sizeof(struct shash_desc) + crypto_shash_descsize(alg);
    sdesc = kmalloc(size, GFP_KERNEL);
    if (!sdesc)
        return ERR_PTR(-ENOMEM);
    sdesc->shash.tfm = alg;
    return sdesc;
}

static int calc_hash(struct crypto_shash *alg,
             const unsigned char *data, unsigned int datalen,
             unsigned char *digest)
{
    struct sdesc *sdesc;
    int ret;

    sdesc = init_sdesc(alg);
    if (IS_ERR(sdesc)) {
        pr_info("can't alloc sdesc\n");
        return PTR_ERR(sdesc);
    }

    ret = crypto_shash_digest(&sdesc->shash, data, datalen, digest);
    kfree(sdesc);
    return ret;
}

static int do_md5(const unsigned char *data, unsigned char *out_digest)
{
    struct crypto_shash *alg;
    char *hash_alg_name = "md5";
    unsigned int datalen = strlen(data); // remove the null byte

    alg = crypto_alloc_shash(hash_alg_name, 0, 0);
    if(IS_ERR(alg)){
        pr_info("can't alloc alg %s\n", hash_alg_name);
        return PTR_ERR(alg);
    }

    unsigned char hash[32];
    calc_hash(alg, data, datalen, hash);

    // Very dirty print of 8 first bytes for comparaison with sha256sum
    printk(KERN_INFO "HASH(%s, %i): %02x%02x%02x%02x%02x%02x%02x%02x\n",
          data, datalen, hash[0] & 0xFFu, hash[1] & 0xFFu, hash[2] & 0xFFu, hash[3] & 0xFFu, hash[4] & 0xFFu, 
          hash[5] & 0xFFu, hash[6] & 0xFFu, hash[7] & 0xFFu);

    char c[3];
    for (int i = 0; i < 16; i++)
    {
        sprintf( c, "%02x", hash[i] & 0xFFu);
        memcpy(out_digest+i*2, c, 2);
    }

    crypto_free_shash(alg);
    return 0;
}

tested.
于 2021-02-05T07:58:20.300 回答
0
#include <crypto/hash.h>

bool md5_hash(char *result, char* data, size_t len){
    struct shash_desc *desc;
    desc = kmalloc(sizeof(*desc), GFP_KERNEL);
    desc->tfm = crypto_alloc_shash("md5", 0, CRYPTO_ALG_ASYNC);

    if(desc->tfm == NULL)
        return false;

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

    return true;
}
于 2019-01-23T08:42:04.587 回答