如何ConstantTimeByteEq工作? [英] How does ConstantTimeByteEq work?

查看:297
本文介绍了如何ConstantTimeByteEq工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Go的crytography图书馆,我发现这个功能<一个href=\"http://golang.org/src/pkg/crypto/subtle/constant_time.go?s=897:936#L17\"><$c$c>ConstantTimeByteEq.它是做什么,它是如何工作的?

  // ConstantTimeByteEq返回1如果x == y和否则为0。
FUNC ConstantTimeByteEq(X,Y UINT8)INT {
    Z:= ^(X ^ Y)
    ž&安培; = Z&GT;&GT; 4
    ž&安培; = Z&GT;&GT; 2
    ž&安培; = Z&GT;&GT; 1    返回INT(Z)
}


解决方案

X ^是 X XOR是时,结果有1位x和y是不同的,0为比特它们是相同的:

  X = 01010011
Y = 00010011
X ^ Y = 01000000

^(X ^ Y)否定这一点,即,你会得到0因为他们是不同的位,否则为1:

  ^(X ^ Y)= 10111111 = GT; ž

然后,我们开始转向Z到适合自身的屏蔽位。移位焊盘的数量的左侧与零位:

 以Z&GT;&GT; 4 = 00001011

通过在传播以Z 的零到结果的目标,开始AND运算:

  Z = 10111111
ž&GT;&GT; 4 = 00001011
ž&安培; (Z&GT;→4)= 00001011

也折了新价值的任何零向右移动:

  Z = 00001011
ž&GT;&GT; 2 = 00000010
ž&安培; (Z&GT;→2)= 00000010

进一步折到最后一点:

  Z = 00001010
ž&GT;&GT; 1 = 00000001
ž&安培; (Z&GT;→1)= 00000000

在另一方面,如果你有 X ==是最初,它是这样的:

  Z = 11111111
Z(&放大器; Z&GT;&→4)= 00001111
Z(&放大器; Z&GT;&→2)= 00000011
Z(&放大器; Z&GT;→1)= 00000001

所以,它真的返回1时 X ==是,否则为0。

一般地,如果x和y是零的比较可以比其它情况下的时间更少。该函数试图让这个所有调用需要的同时,无论其输入的值。这样,攻击者不能使用基于定时攻击。

In Go's crytography library, I found this function ConstantTimeByteEq. What does it do, how does it work?

// ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
func ConstantTimeByteEq(x, y uint8) int {
    z := ^(x ^ y)
    z &= z >> 4
    z &= z >> 2
    z &= z >> 1

    return int(z)
}

解决方案

x ^ y is x XOR y, the result has 1 for the bits x and y are different and 0 for the bits they are same:

x            = 01010011
y            = 00010011
x ^ y        = 01000000

^(x ^ y) negates this, i.e., you get 0 for the bits they are different and 1 otherwise:

^(x ^ y)     = 10111111 => z

Then we start shifting z to right for masking its bits by itself. A shift pads the left side of the number with zero bits:

z >> 4       = 00001011

With the goal of propagating any zeros in z to the result, start ANDing:

z            = 10111111
z >> 4       = 00001011
z & (z >> 4) = 00001011

also fold the new value to move any zero to the right:

z            = 00001011
z >> 2       = 00000010
z & (z >> 2) = 00000010

further fold to the last bit:

z            = 00001010
z >> 1       = 00000001
z & (z >> 1) = 00000000

On the other hand, if you have x == y initially, it goes like this:

z            = 11111111
z (& z >> 4) = 00001111
z (& z >> 2) = 00000011
z (& z >> 1) = 00000001

So it really returns 1 when x == y, 0 otherwise.

Generally, if both x and y are zero the comparison can take less time than other cases. This function tries to make it so that all calls take the same time regardless of the values of its inputs. This way, an attacker can't use timing based attacks.

这篇关于如何ConstantTimeByteEq工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆