主要结构体
char key[16];
struct task_struct* task;
struct crypto_skcipher *tfm = NULL;
struct skcipher_request *req = NULL;
struct scatterlist sg;
size_t block_size;
DECLARE_CRYPTO_WAIT(wait);
初始化crypto_skcipher
tfm = crypto_alloc_skcipher("ecb(sm4)", 0, 0);
if(IS_ERR(tfm)) {
printk("<1>failed to load transform for sm4 ECB mode !\n");
result = PTR_ERR(tfm);
goto free_data;
}
校验算法数据块大小
block_size = crypto_skcipher_blocksize(tfm);
if (count % block_size != 0) {
printk("data len not aligned: %d, %d\n", block_size, count);
result = -EINVAL;
goto free_skcipher;
}
初始化request
req = skcipher_request_alloc(tfm, GFP_KERNEL);
if (!req) {
printk("skcipher_request_alloc fail\n");
result = -ENOMEM;
goto free_skcipher;
}
设置key
result = crypto_skcipher_setkey(tfm, key, sizeof(key));
if (result)
{
printk("<1>failed to set key for sm4 ECB mode !\n");
goto free_req;
}
初始化数据开始加解密
sg_init_one(&sg, data, count);//初始化数据
skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG | CRYPTO_TFM_REQ_MAY_SLEEP,
crypto_req_done, &wait);
//dst和src数据可以是同一个sg
skcipher_request_set_crypt(req, &sg, &sg, count, NULL);
//等待异步处理完成
result = crypto_wait_req(crypto_skcipher_decrypt(req), &wait);
if (result) {
pr_err("Error decrypting data: %d\n", result);
goto free_req;
}
释放内存
free_req:
if(req)
skcipher_request_free(req);
free_skcipher:
if(tfm)
crypto_free_skcipher(tfm);
free_data:
kfree(data);
out:
return result;