Trying to understand this function from Go, why make a function that always run in constant time and how does this work?

huangapple go评论75阅读模式
英文:

Trying to understand this function from Go, why make a function that always run in constant time and how does this work?

问题

我遇到了以下函数crypto/subtle包,引起了我很大的好奇心,希望有人能解释一下它的目的。谢谢。

// ConstantTimeByteEq 如果 x == y,则返回1,否则返回0。
func ConstantTimeByteEq(x, y uint8) int {
    z := ^(x ^ y)
    z &= z >> 4
    z &= z >> 2
    z &= z >> 1

    return int(z)
}

这个函数的目的是比较两个字节是否相等,并以常量时间运行,以防止侧信道攻击。它使用位运算来实现常量时间比较。具体来说,它通过对两个字节进行异或操作,然后对结果进行按位取反,最后通过一系列的位运算来将结果限制在0或1的范围内。如果两个字节相等,返回1,否则返回0。这种方法可以防止根据运行时间的差异来推断出密钥或其他敏感信息。

英文:

I was encounter the following function crypto/subtle package which caused me a lot curiosity, wish someone can explain the purpose behind it. Thanks,

// ConstantTimeByteEq returns 1 if x == y and 0 otherwise.
    27	func ConstantTimeByteEq(x, y uint8) int {
    28		z := ^(x ^ y)
    29		z &= z >> 4
    30		z &= z >> 2
    31		z &= z >> 1
    32	
    33		return int(z)
    34	}

答案1

得分: 17

它可以防止针对加密系统的时序攻击:任何代码路径都需要完全相同的时间。

如果你对时序不够小心,就会打开一个侧信道,泄露有关你的秘密信息的信息。例如,你可以通过系统在10纳秒内失败得更快来确定密码的第一个字符是'R',然后继续尝试下一个字符,直到找到密码。

实现密码学确实非常困难。真的非常非常困难。

英文:

It prevents timing attacks against cryptosystems: Any code path takes exactly the same amount of time.

If you are careless about timing you open up a sidechannel which leaks information about your secret. E.g. you could determine that the first character of a password is 'R' because the system fails 10ns faster if your wrong password starts with 'R'. Repeat with next character until you found the password.

Implementing cryptography is really hard. Really really hard.

huangapple
  • 本文由 发表于 2013年12月6日 06:17:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/20411964.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定