gpt4 book ai didi

c# - C#中的GF(256)有限域乘法函数

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:50 25 4
gpt4 key购买 nike

我在 C# 中实现 AES,在某些时候(MixColumns 函数)我必须在 GF(2^8) 有限域上乘以两个字节。

所以,我有三个选择:

  • 使用 dotNet 的默认函数(它有类似的东西吗?)
  • 编写一个执行此操作的自定义函数
  • 使用查找表

对于自定义函数,我找到了一段 C 代码,我试图为 C# 重写它,但它不起作用(我得到错误的结果)。 (*)

这是原始的 C 代码 ( source ):

/* Multiply two numbers in the GF(2^8) finite field defined 
* by the polynomial x^8 + x^4 + x^3 + x + 1 */
uint8_t gmul(uint8_t a, uint8_t b) {
uint8_t p = 0;
uint8_t counter;
uint8_t hi_bit_set;
for (counter = 0; counter < 8; counter++) {
if (b & 1)
p ^= a;
hi_bit_set = (a & 0x80);
a <<= 1;
if (hi_bit_set)
a ^= 0x1b; /* x^8 + x^4 + x^3 + x + 1 */
b >>= 1;
}
return p;
}

这是我重写的内容:

public Byte GMul(Byte a, Byte b) { // Galois Field (256) Multiplication
Byte p = 0;
Byte counter;
Byte hi_bit_set;
for (counter = 0; counter < 8; counter++) {
if ((b & 1) != 0) {
p ^= a;
}
hi_bit_set = (Byte) (a & 0x80);
a <<= 1;
if (hi_bit_set != 0) {
a ^= 0x1b; /* x^8 + x^4 + x^3 + x + 1 */
}
b >>= 1;
}
return p;
}

我还找到了一些查找表 here ,这似乎是一种简单而好的方法,但我真的不知道如何使用它们,尽管我有一种预感。 (**)

底线:我应该选择哪个选项,以及我怎样才能让它发挥作用,鉴于我上面写的是我目前所知道的,而且我真的不想深入了解数学知识。

更新:

*) 与此同时,我意识到我的 C# 重写代码产生了正确的答案,这只是我的错,因为我在验证它们时搞砸了。

**) 这些表可以用作 Byte[256] 数组,比方说,x*3 的答案是 table_3[ x]x 在用作表数组的索引时从 HEX 转换为 DECIMAL。

最佳答案

为了在 GF(2) 中乘以 x * 3,只需访问 x=table_3[x];

可能有一种使用对数方法的 3 查找表方法可用。

就像在常规数字 a*b = 2^(log2(a)+log2(b)) 中一样,在 GF(2) 中也会发生同样的情况,但没有 float 或舍入错误。

关于c# - C#中的GF(256)有限域乘法函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13239816/

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