Skip to content

Commit

Permalink
change mul and div functions (hashicorp#19495)
Browse files Browse the repository at this point in the history
  • Loading branch information
rculpepper authored Mar 13, 2023
1 parent 55bf601 commit ed08e45
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 107 deletions.
39 changes: 24 additions & 15 deletions shamir/shamir.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,31 +86,40 @@ func div(a, b uint8) uint8 {
panic("divide by zero")
}

log_a := logTable[a]
log_b := logTable[b]
diff := ((int(log_a) - int(log_b)) + 255) % 255

ret := int(expTable[diff])
ret := int(mult(a, inverse(b)))

// Ensure we return zero if a is zero but aren't subject to timing attacks
ret = subtle.ConstantTimeSelect(subtle.ConstantTimeByteEq(a, 0), 0, ret)
return uint8(ret)
}

// inverse calculates the inverse of a number in GF(2^8)
func inverse(a uint8) uint8 {
b := mult(a, a)
c := mult(a, b)
b = mult(c, c)
b = mult(b, b)
c = mult(b, c)
b = mult(b, b)
b = mult(b, b)
b = mult(b, c)
b = mult(b, b)
b = mult(a, b)

return mult(b, b)
}

// mult multiplies two numbers in GF(2^8)
func mult(a, b uint8) (out uint8) {
log_a := logTable[a]
log_b := logTable[b]
sum := (int(log_a) + int(log_b)) % 255

ret := int(expTable[sum])
var r uint8 = 0
var i uint8 = 8

// Ensure we return zero if either a or b are zero but aren't subject to
// timing attacks
ret = subtle.ConstantTimeSelect(subtle.ConstantTimeByteEq(a, 0), 0, ret)
ret = subtle.ConstantTimeSelect(subtle.ConstantTimeByteEq(b, 0), 0, ret)
for i > 0 {
i--
r = (-(b >> i & 1) & a) ^ (-(r >> 7) & 0x1B) ^ (r + r)
}

return uint8(ret)
return r
}

// add combines two numbers in GF(2^8)
Expand Down
79 changes: 0 additions & 79 deletions shamir/tables.go

This file was deleted.

13 changes: 0 additions & 13 deletions shamir/tables_test.go

This file was deleted.

0 comments on commit ed08e45

Please sign in to comment.