kernel crypto hmac sha256 API call code

这段代码展示了在Linux内核中如何使用crypto API进行HMAC-SHA256的加密操作。通过crypto_alloc_hash获取哈希对象,设置密钥,然后对明文数据进行加密,最后释放哈希对象。
摘要由CSDN通过智能技术生成
static int hmac_sha256(char *plaintext, unsigned int plain_text_size, char *key, unsigned int key_size, uint8_t *result)
{
    struct scatterlist sg;
    struct crypto_hash *tfm;
    struct hash_desc desc;
    int ret;

    if (!result) {
        printk(KERN_ERR "param err\n"); 
        return -EINVAL; 
    } 

    tfm = crypto_alloc_hash("hmac(sha256)", 0, CRYPTO_ALG_ASYNC);
    if (IS_ERR(tfm)) { 
        printk(KERN_ERR "crypto_alloc_ahash failed: err %ld", PTR_ERR(tfm));
        return -EINVAL; 
     } 

     desc.tfm = tfm;
     desc.flags = 0; 
     sg_set_buf(&sg, plaintext, plain_text_size); 
     ret = crypto_hash_setkey(tfm, key, key_size); 
     if (ret) {
         printk(KERN_ERR "crypto_ahash_setkey failed: err %d", ret); 
         goto out; 
     } 

     ret = crypto_hash_digest(&desc, &sg, plain_text_size, result);
     if(ret) { 
         printk(KERN_ERR "digest() failed ret = %d\n", ret);
         goto out; 
     } 
     printk(KERN_DEBUG, "crypto hash digest size %d\n", crypto_hash_digestsize(tfm));

out: 
    crypto_free_hash(tfm); 
    return -EINVAL;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值