gpt4 book ai didi

c# - 比较两个字节数组以防止时序攻击

转载 作者:行者123 更新时间:2023-11-30 17:44:17 24 4
gpt4 key购买 nike

我想写一个方法来比较两个字节数组,但我不想使用 these solutions因为我希望该方法能够抵抗定时攻击。我的方法本质上是这样的:

static bool AreEqual(byte[] a1, byte[] a2)
{
bool result = true;
for (int i = 0; i < a1.Length; ++i)
{
if (a1[i] != a2[i])
result = false;
}
return result;
}

(假设 a1a2 的长度相同)。

我担心的是,如果 result 被设置为 false,足够智能的即时编译器可能会通过提前返回来优化这一点。

have checked .NET 4.0.30319 生成的 JITted 汇编代码,它不会:

                         ; `bool result = true;'00e000d1 bb01000000      mov     ebx,1                         ; `int i = 0;'00e000d6 33f6            xor     esi,esi                         ; store `a1.Length' in eax and at dword ptr [ebp-10h]00e000d8 8b4104          mov     eax,dword ptr [ecx+4]00e000db 8945f0          mov     dword ptr [ebp-10h],eax                         ; if `a1.Length' is 0, then jump to `return result;'00e000de 85c0            test    eax,eax00e000e0 7e18            jle     00e000fa                         ; `if (a1[i] != a2[i])'00e000e2 0fb6443108      movzx   eax,byte ptr [ecx+esi+8]00e000e7 3b7704          cmp     esi,dword ptr [edi+4]00e000ea 7316            jae     00e0010200e000ec 3a443708        cmp     al,byte ptr [edi+esi+8]00e000f0 7402            je      00e000f4                         ; `result = false;'00e000f2 33db            xor     ebx,ebx                         ; `++i'00e000f4 46              inc     esi                         ; check: `a1.Length > i'00e000f5 3975f0          cmp     dword ptr [ebp-10h],esi00e000f8 7fe8            jg      00e000e2                         ; `return result;'00e000fa 8bc3            mov     eax,ebx00e000fc 59              pop     ecx00e000fd 5b              pop     ebx00e000fe 5e              pop     esi00e000ff 5f              pop     edi00e00100 5d              pop     ebp00e00101 c3              ret00e00102 e81f7a1772      call    clr!CreateHistoryReader+0x8e97c (72f77b26)00e00107 cc              int     300e00108 0000            add     byte ptr [eax],al00e0010a 0000            add     byte ptr [eax],al00e0010c 0000            add     byte ptr [eax],al00e0010e 0000            add     byte ptr [eax],al...

不过,我认为这在未来可能会改变。

有没有办法阻止 JIT 编译器优化这个方法?或者,是否有一个我可以使用的库函数专门检查两个字节数组是否相等,但能抵抗时序攻击?

最佳答案

您可以使用 MethodImplAttribute -System.Runtime.CompilerServices 命名空间的类,带有 MethodImplOptions.NoOptimization像这样的选项:

[MethodImpl(MethodImplOptions.NoOptimization)]
static bool AreEqual(byte[] a1, byte[] a2)
{
// ...
}

关于c# - 比较两个字节数组以防止时序攻击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29868298/

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