forked from chanxuehong/wechat
/
security.go
36 lines (32 loc) · 944 Bytes
/
security.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package util
import (
"crypto/subtle"
)
func SecureCompare(given, actual []byte) bool {
if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
if subtle.ConstantTimeCompare(given, actual) == 1 {
return true
}
return false
}
// Securely compare actual to itself to keep constant time, but always return false
if subtle.ConstantTimeCompare(actual, actual) == 1 {
return false
}
return false
}
func SecureCompareString(given, actual string) bool {
// The following code is incorrect:
// return SecureCompare([]byte(given), []byte(actual))
if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
if subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1 {
return true
}
return false
}
// Securely compare actual to itself to keep constant time, but always return false
if subtle.ConstantTimeCompare([]byte(actual), []byte(actual)) == 1 {
return false
}
return false
}