在模块里使用内核crypto api

        以 crc32 为例,模块代码如下:

#include <crypto/hash.h>
#include <linux/err.h>
#include <linux/module.h>

int test_crc32(void)
{
    struct crypto_shash *tfm;
    u32 val;       
    int err;       
    u32 type = 0, mask = 0;
    char *driver = "crc32-mips-hw";
                   
    tfm = crypto_alloc_shash(driver, type, mask);
    if (IS_ERR(tfm)) {
        if (PTR_ERR(tfm) == -ENOENT) {
            printk(KERN_ERR "alg: crc32: Failed to alloc shash\n");
            return 0;
        }          
        printk(KERN_ERR "alg: crc32: Failed to load transform for %s: "
               "%ld\n", driver, PTR_ERR(tfm));
        return PTR_ERR(tfm);
    }              
               
    do {           
        SHASH_DESC_ON_STACK(shash, tfm);
        u32 *ctx = (u32 *)shash_desc_ctx(shash);
        u64 num = 12345678;

        shash->tfm = tfm; 
        shash->flags = 0; 
                   
        err = crypto_shash_init(shash);
        if (err){
            printk(KERN_ERR "%s:%d, alg: crc32: init operation"
		"failed for %s: %d\n", __func__, __LINE__, driver, err);
        }

        *ctx = 0xffffffff;
        err = crypto_shash_update(shash, (u8 *)&num, 8);
        if (err) {
            printk(KERN_ERR "%s:%d, alg: crc32: update operation"
                "failed for %s: %d\n", __func__, __LINE__, driver, err);
            break;
        }

        err = crypto_shash_final(shash, (u8 *)&val);
        val ^= 0xffffffff;
        printk(KERN_INFO "crc32 for %llu: 0x%0x\n", num, val);
        if (err) {
            printk(KERN_ERR "%s:%d, alg: crc32: final operation"
                "failed for %s: %d\n", __func__, __LINE__, driver, err);
            break;
        }           
    } while (0);
          
    crypto_free_shash(tfm);

    return err;
}
static int __init crypto_test_init(void)
{
    int err;
	
    printk(KERN_INFO "begin to insert crypto_test module ...\n");
    err = test_crc32();
    if (err) {
        printk(KERN_ERR "test crc32 failed!\n");
    }

    printk(KERN_INFO "insert crypto_test module done!\n");

    return err;
}

static void __exit crypto_test_exit(void)
{

    printk(KERN_INFO "exiting crypto_test module!\n");
}

module_init(crypto_test_init);
module_exit(crypto_test_exit);

MODULE_LICENSE("GPL");

        内核 crc32 计算结果如下:

[ 1135.510865] begin to insert crypto_test module ...
[ 1135.510885] crc32 for 12345678: 0x19fc9be9
[ 1135.510888] insert crypto_test module done!

        python zlib.crc32() 计算结果如下:

$ python
...
>>> from zlib import crc32
>>> import numpy as np
>>> hex(crc32(np.int64("12345678")))
'0x19fc9be9'
>>>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值