31 lines
1.0 KiB
Go
31 lines
1.0 KiB
Go
package tools
|
|
|
|
import "crypto/subtle"
|
|
|
|
// SecureCompare use constant time function to compare the two given array.
|
|
func SecureCompare(given, actual []byte) bool {
|
|
if subtle.ConstantTimeEq(int32(len(given)), int32(len(actual))) == 1 {
|
|
return subtle.ConstantTimeCompare(given, actual) == 1
|
|
}
|
|
// Securely compare actual to itself to keep constant time, but always return false
|
|
if subtle.ConstantTimeCompare(actual, actual) == 1 {
|
|
return false
|
|
}
|
|
return false
|
|
}
|
|
|
|
// SecureCompareString use constant time function to compare the two given string.
|
|
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 {
|
|
return subtle.ConstantTimeCompare([]byte(given), []byte(actual)) == 1
|
|
}
|
|
// 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
|
|
}
|