在Go语言中进行字符串的安全比较

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

Secure Compare of Strings in Go

问题

在Go语言中,有一种内置的方法可以实现常数时间的字符串比较吗?

在Ruby中,我在需要这种功能时使用了Devise.secure_compare方法(链接:https://github.com/plataformatec/devise/blob/7d114271164c7ae39801b07b620d4eddf429a96a/lib/devise.rb#L476-L485)。

英文:

Is the a built-in way of doing constant time string comparison in Go?

I've used the Devise.secure_compare method when I've needed this functionality in Ruby.

答案1

得分: 36

不是针对字符串,而是针对[]byte类型。请参考crypto/subtle,特别是ConstantTimeCompare函数:

> func ConstantTimeCompare(x, y []byte) int
>
> ConstantTimeCompare函数在两个等长的切片x和y的内容相等时返回1。所花费的时间取决于切片的长度,与内容无关。

正如你可能知道的,你可以很容易地将字符串转换为字节切片:

var x []byte = []byte("someString")
英文:

Not for strings but for []byte. See crypto/subtle, especially ConstantTimeCompare:

> func ConstantTimeCompare(x, y []byte) int
>
> ConstantTimeCompare returns 1 iff the two equal length slices, x and y, have equal contents. The time taken is a function of the length of the slices and is independent of the contents.

As you may know, you can easily convert a string to a byte slice:

var x []byte = []byte("someString")

huangapple
  • 本文由 发表于 2013年12月19日 00:32:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/20663468.html
匿名

发表评论

匿名网友

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

确定