crypto.odin 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package crypto
  2. import "core:mem"
  3. // compare_constant_time returns 1 iff a and b are equal, 0 otherwise.
  4. //
  5. // The execution time of this routine is constant regardless of the contents
  6. // of the slices being compared, as long as the length of the slices is equal.
  7. // If the length of the two slices is different, it will early-return 0.
  8. compare_constant_time :: proc "contextless" (a, b: []byte) -> int {
  9. // If the length of the slices is different, early return.
  10. //
  11. // This leaks the fact that the slices have a different length,
  12. // but the routine is primarily intended for comparing things
  13. // like MACS and password digests.
  14. n := len(a)
  15. if n != len(b) {
  16. return 0
  17. }
  18. return compare_byte_ptrs_constant_time(raw_data(a), raw_data(b), n)
  19. }
  20. // compare_byte_ptrs_constant_time returns 1 iff the bytes pointed to by
  21. // a and b are equal, 0 otherwise.
  22. //
  23. // The execution time of this routine is constant regardless of the
  24. // contents of the memory being compared.
  25. @(optimization_mode="none")
  26. compare_byte_ptrs_constant_time :: proc "contextless" (a, b: ^byte, n: int) -> int {
  27. x := mem.slice_ptr(a, n)
  28. y := mem.slice_ptr(b, n)
  29. v: byte
  30. for i in 0..<n {
  31. v |= x[i] ~ y[i]
  32. }
  33. // After the loop, v == 0 iff a == b. The subtraction will underflow
  34. // iff v == 0, setting the sign-bit, which gets returned.
  35. return int((u32(v)-1) >> 31)
  36. }
  37. // rand_bytes fills the dst buffer with cryptographic entropy taken from
  38. // the system entropy source. This routine will block if the system entropy
  39. // source is not ready yet. All system entropy source failures are treated
  40. // as catastrophic, resulting in a panic.
  41. rand_bytes :: proc (dst: []byte) {
  42. // zero-fill the buffer first
  43. mem.zero_explicit(raw_data(dst), len(dst))
  44. _rand_bytes(dst)
  45. }