c# - Comparing two byte arrays guarding against timing attacks -


i want write method compare 2 byte arrays, not want use these solutions because want method resistant timing attacks. method looks like:

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

(with assumption a1 , a2 have same length).

my concern sufficiently smart just-in-time compiler might optimize returning if result ever set false.

i have checked jitted assembly code produced .net 4.0.30319, , not:

                          ; `bool result = true;' 00e000d1 bb01000000      mov     ebx,1                          ; `int = 0;' 00e000d6 33f6            xor     esi,esi                          ; store `a1.length' in eax , @ dword ptr [ebp-10h] 00e000d8 8b4104          mov     eax,dword ptr [ecx+4] 00e000db 8945f0          mov     dword ptr [ebp-10h],eax                          ; if `a1.length' 0, jump `return result;' 00e000de 85c0            test    eax,eax 00e000e0 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     00e00102 00e000ec 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],esi 00e000f8 7fe8            jg      00e000e2                          ; `return result;' 00e000fa 8bc3            mov     eax,ebx 00e000fc 59              pop     ecx 00e000fd 5b              pop     ebx 00e000fe 5e              pop     esi 00e000ff 5f              pop     edi 00e00100 5d              pop     ebp 00e00101 c3              ret 00e00102 e81f7a1772      call    clr!createhistoryreader+0x8e97c (72f77b26) 00e00107 cc              int     3 00e00108 0000            add     byte ptr [eax],al 00e0010a 0000            add     byte ptr [eax],al 00e0010c 0000            add     byte ptr [eax],al 00e0010e 0000            add     byte ptr [eax],al ... 

however, thinking change in future.

is there way prevent jit compiler optimizing method? alternatively, there library function can use checks 2 byte arrays equality, resistant timing attacks?

you can use methodimplattribute-class of system.runtime.compilerservices namespace methodimploptions.nooptimization option this:

[methodimpl(methodimploptions.nooptimization)] static bool areequal(byte[] a1, byte[] a2) {     // ... } 

Comments

Popular posts from this blog

jquery - How do you format the date used in the popover widget title of FullCalendar? -

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -