使用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