linux内核hmac-sha1使用

55 篇文章 2 订阅
53 篇文章 2 订阅

最近开发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");

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值