Monday, July 21, 2014

Securely compare two memory blocks

This function would be necessary to prevent timing attack, when you compare two passwords or two passphrases.

#include<stdint.h>
typedef uint8_t t1u;
typedef int8_t t1s;
typedef uint16_t t2u;
typedef int16_t t2s;
typedef uint32_t t4u;
typedef int32_t t4s;typedef float t4f;
typedef uint64_t t8u;
typedef int64_t t8s;typedef double t8f;
typedef void v;


/*Compare two memory blocks, both of equal size 'O'
1, if same
0, if not the same*/
bool xbEqScr(v const*p,v const*q,t4u O)noexcept{t1u const*A,*B;t8u F=0;t4u l=O>>3;O&=7;
if(l){t8u const*C=(t8u const*)p,*D=(t8u const*)q;
A=O+(t1u const*)(C+l);
B=O+(t1u const*)(D+l);
while(l--){F|=*C++^*D++;}}
else{A=O+(t1u const*)p,B=O+(t1u const*)q;}
switch(O){
case 7:F|=*--A^*--B;
case 6:F|=*--A^*--B;
case 5:F|=*--A^*--B;
case 4:F|=*--A^*--B;
case 3:F|=*--A^*--B;
case 2:F|=*--A^*--B;
case 1:F|=*--A^*--B;}return!F;}

No comments:

Post a Comment