crypto.odin 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. compare_byte_ptrs_constant_time :: proc "contextless" (a, b: ^byte, n: int) -> int {
  26. x := mem.slice_ptr(a, n)
  27. y := mem.slice_ptr(b, n)
  28. v: byte
  29. for i in 0..<n {
  30. v |= x[i] ~ y[i]
  31. }
  32. // After the loop, v == 0 iff a == b. The subtraction will underflow
  33. // iff v == 0, setting the sign-bit, which gets returned.
  34. return int((u32(v)-1) >> 31)
  35. }
  36. // rand_bytes fills the dst buffer with cryptographic entropy taken from
  37. // the system entropy source. This routine will block if the system entropy
  38. // source is not ready yet. All system entropy source failures are treated
  39. // as catastrophic, resulting in a panic.
  40. rand_bytes :: proc (dst: []byte) {
  41. // zero-fill the buffer first
  42. mem.zero_explicit(raw_data(dst), len(dst))
  43. _rand_bytes(dst)
  44. }