gpt4 book ai didi

linux-kernel - 如何在 Linux 内核中计算数组的 SHA1

转载 作者:行者123 更新时间:2023-12-04 04:17:26 25 4
gpt4 key购买 nike

我正在尝试在 Linux 内核中计算整数数组的 SHA1。我已经通过 crypto.c/crypto.hsecurity/integrity/ima/ima_crypto.c 但我不知道如何到 init,然后 update SHA1 计算机。有人可以向我指出如何执行此操作的教程或指南吗?

最佳答案

Documentation/crypto/api-intro.txt 中有一个很好的关于 linux 密码学 api 的介绍。 .另请查看 fs/ecryptfs/crypto.c有关如何使用函数的真实示例。

这里有一个简短的总结,让您开始:

第 1 步:声明

创建一些局部变量:

struct scatterlist sg;
struct hash_desc desc;
char *plaintext = "plaintext goes here";
size_t len = strlen(plaintext);
u8 hashval[20];
  • struct scatterlist 用于以 crypto.h 函数可以理解的格式保存明文,而使用 struct hash_desc配置散列。
  • 变量 plaintext 保存我们的明文字符串,而 hashval 将保存我们明文的哈希值。
  • 最后,len 保存明文字符串的长度。

请注意,虽然我在此示例中使用 ASCII 纯文本,但您也可以传递一个整数数组 - 只需将总内存大小存储在 len 中并替换 plaintext 与您的整数数组:

int myarr[4] = { 1, 3, 3, 7 };
size_t len = sizeof(myarr);

但请注意:int 元素的大小通常大于一个字节,因此将整数值存储在 int 数组中的内部表示形式与一个 char 数组——你可能会在值之间填充空字节。

此外,如果您打算散列整数的 ASCII 表示,您必须首先将数组中的值转换为字符串字符序列(可能使用 sprintf)。

第 2 步:初始化

初始化sgdesc:

sg_init_one(&sg, plaintext, len);
desc.tfm = crypto_alloc_hash("sha1", 0, CRYPTO_ALG_ASYNC);

注意 "sha1" 被传递给 crypto_alloc_hash;这可以设置为 "md5" 用于 MD5 散列,或任何其他支持的字符串,以便使用相应的散列方法。

第 3 步:散列

现在使用三个函数调用执行散列:

crypto_hash_init(&desc);
crypto_hash_update(&desc, &sg, len);
crypto_hash_final(&desc, hashval);
  • crypto_hash_init 根据提供的 struct hash_desc 配置哈希引擎。
  • crypto_hash_update 对明文执行实际的散列方法。
  • 最后,crypto_hash_final 将哈希复制到一个字符数组中。

第 4 步:清理

desc.tfm持有的空闲分配内存:

crypto_free_hash(desc.tfm);

另见

how to use CryptoAPI in the linux kernel 2.6

关于linux-kernel - 如何在 Linux 内核中计算数组的 SHA1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16861332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com