英文:
How to implement slowEqual with golang
问题
我尝试使用golang实现了一个slowEqual函数,但是异或操作只能用于int和int8类型,我不知道如何将字符串转换为int[]或int8[],即使可以转换,似乎也有些别扭。我发现了bytes.Equal函数,但它似乎不是一个slowEqual的实现。有什么建议吗?
这是我的实现代码:
//TODO real slow equal
func slowEquals(a, b string) bool {
al := len(a)
bl := len(b)
aInts := make([]int, al)
bInts := make([]int, bl)
for i := 0; i < al; i++ {
aInts[i] = int(a[i])
}
for i := 0; i < bl; i++ {
bInts[i] = int(b[i])
}
var diff uint8 = uint8(al ^ bl)
for i := 0; i < al && i < bl; i++ {
diff |= a[i] ^ b[i]
}
return diff == 0
//长度相等为0
/*
abytes := []int8()
bbytes := []int8()
al := len(a)
bl := len(b)
diff := al ^ bl
for i := 0; i < al && i < bl; i++ {
diff |= a[i] ^ b[i]
}
return diff == 0
*/
}
或者(在第一个回答之后):
import "crypto/subtle"
func SlowEquals(a, b string) bool {
if len(a) != len(b) {
return subtle.ConstantTimeCompare([]byte(a), make([]byte,len(a))) == 1
}else{
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
}
英文:
I tried to implement a slowEqual with golang,but xor operation is limited to int and int8 and I have no idea to convert string to int[] or int8[] , even it can be converted it seems little awkward, and I found bytes.Equal but it seems not a slowEqual implementation.Any advices?
This is my impletation.
//TODO real slow equal
func slowEquals(a, b string) bool {
al := len(a)
bl := len(b)
aInts := make([]int, al)
bInts := make([]int, bl)
for i := 0; i < al; i++ {
aInts[i] = int(a[i])
}
for i := 0; i < bl; i++ {
bInts[i] = int(b[i])
}
var diff uint8 = uint8(al ^ bl)
for i := 0; i < al && i < bl; i++ {
diff |= a[i] ^ b[i]
}
return diff == 0
//长度相等为0
/*
abytes := []int8()
bbytes := []int8()
al := len(a)
bl := len(b)
diff := al ^ bl
for i := 0; i < al && i < bl; i++ {
diff |= a[i] ^ b[i]
}
return diff == 0
*/
}
Or:(after first answer)
import "crypto/subtle"
func SlowEquals(a, b string) bool {
if len(a) != len(b) {
return subtle.ConstantTimeCompare([]byte(a), make([]byte,len(a))) == 1
}else{
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
}
答案1
得分: 1
也许是这样的:
import "crypto/subtle"
func SlowEquals(a, b string) bool {
if len(a) != len(b) {
return false
}
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
如果长度不同,这段代码会很快返回false。但是原始代码存在一种时序攻击,可以揭示a的长度,所以我认为这个版本并不更糟糕。
英文:
Perhaps this:
import "crypto/subtle"
func SlowEquals(a, b string) bool {
if len(a) != len(b) {
return false
}
return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
This returns quickly if the lengths are different, but there's a timing attack against the original code that reveals the length of a, so I think this isn't worse.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论