C语言-比较字符串是否相等(计时攻击)

19 篇文章 0 订阅

C 语言版

#include <stdio.h>

int util_cmp_const(const void *a, const void *b, const size_t size)
{
    const unsigned char *_a = (const unsigned char *)a;
    const unsigned char *_b = (const unsigned char *)b;
    unsigned char result = 0;
    size_t i;

    for (i = 0; i < size; i++)
    {
        result |= _a[i] ^ _b[i];
    }

    return result; /* returns 0 if equal, nonzero otherwise */
}

int main(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);

    return 1;
}

/*
 编译: gcc -o out timming_attack.c 
 运行: ./out
 结果:
 hello tyustli
 result = 3
 result = 0
*/

/******************** end of file ***********************/

python 版

def constant_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.
    """
    if len(val1) != len(val2):
        return False
    result = 0
    for x, y in zip(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)

应用

  • 计时攻击
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值