现在的位置: 首页 > 综合 > 正文

linux内核hmac-sha1使用

2014年09月05日 ⁄ 综合 ⁄ 共 1185字 ⁄ 字号 评论关闭

最近开发IPSec模块时,需要用到内核中hmac-sha1算法下面为hmac-sha1的简单使用方式

#include <linux/crypto.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <crypto/hash.h>
#include <linux/scatterlist.h>

static void hexdump(char *data, int len)
{
	int i = 0;
	for(; i < len; i++){
		if((len % 16) == 0)
			printk("\n");
		printk("%2x ", data[i]);
	}	
	printk("\n");
}

static int __init hmac_sha1(void) 
{
	struct crypto_hash  *hash;
	struct hash_desc *desc;

	char key[20];
	struct scatterlist sg;
	char data[100];
	char digest[20];

	memset(data, 0 ,100);
	memset(key, 0 ,20);
		
	hash = crypto_alloc_hash("hmac(sha1)", 0, CRYPTO_ALG_ASYNC);

	if(IS_ERR(hash)){
		printk(KERN_INFO "Can't alloc hmac\n");
		return -2;
	}

	desc->tfm = hash;
	desc->flags = 0;

	if(crypto_hash_setkey(hash, key, 20)){
		printk(KERN_INFO "crypto_hash_setkey()\n");
		return -1;
	}	

	if((crypto_hash_init(desc))){
		printk("crypto_hash_init failed\n");
		return -1;
	}

	sg_init_table(&sg, 1);
	sg_set_buf(&sg, data, sizeof(data));

	if (crypto_hash_update(desc, &sg, sizeof(data))){
		printk(KERN_INFO "crypto_hash_update()\n");
		return -1;
	}

	if((crypto_hash_final(desc, digest))){
		printk("crypto_hash_final\n");
		return -1;
	}

	hexdump(digest, 20);
}

static void __exit hmac_sha1_exit(void)
{
	printk("hmac_exit\n");
}

module_init(hmac_sha1);
module_exit(hmac_sha1_exit);

MODULE_LICENSE("GPL");

抱歉!评论已关闭.