如何用golang实现slowEqual

时间:2014-04-19 15:25:48

标签: go

我尝试用golang实现slowEqual,但xor操作仅限于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       
    }
}

1 个答案:

答案 0 :(得分:0)

也许这就是:

import "crypto/subtle"

func SlowEquals(a, b string) bool {
    if len(a) != len(b) {
        return false
    }
    return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}

如果长度不同,则返回很快,但是对原始代码的定时攻击显示a的长度,所以我认为这不会更糟。