#include<stdio.h>intutil_cmp_const(constvoid*a,constvoid*b,const size_t size){constunsignedchar*_a =(constunsignedchar*)a;constunsignedchar*_b =(constunsignedchar*)b;unsignedchar result =0;
size_t i;for(i =0; i < size; i++){
result |= _a[i]^ _b[i];}return result;/* returns 0 if equal, nonzero otherwise */}intmain(int argc,char*argv[]){char result =0;printf("hello tyustli\r\n");
result =util_cmp_const("abcdef","abcdee",6);printf("result = %d\n", result);
result =util_cmp_const("abcdef","abcdef",6);printf("result = %d\n", result);return1;}/*
编译: gcc -o out timming_attack.c
运行: ./out
结果:
hello tyustli
result = 3
result = 0
*//******************** end of file ***********************/
python 版
defconstant_time_compare(val1, val2):"""
Returns True if the two strings are equal, False otherwise.
The time taken is independent of the number of characters that match.
For the sake of simplicity, this function executes in constant time only
when the two strings have the same length. It short-circuits when they
have different lengths.
"""iflen(val1)!=len(val2):returnFalse
result =0for x, y inzip(val1, val2):
result |=ord(x)^ord(y)return result ==0
result = constant_time_compare("abcdef","abcdee")print(result)
result = constant_time_compare("abcdef","abcdef")print(result)