以 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'
>>>