utils.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # Copyright 2013-2017 Donald Stufft and individual contributors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import, division, print_function
  15. import nacl.exceptions as exc
  16. from nacl._sodium import ffi, lib
  17. from nacl.exceptions import ensure
  18. def sodium_memcmp(inp1, inp2):
  19. """
  20. Compare contents of two memory regions in constant time
  21. """
  22. ensure(isinstance(inp1, bytes),
  23. raising=exc.TypeError)
  24. ensure(isinstance(inp2, bytes),
  25. raising=exc.TypeError)
  26. ln = max(len(inp1), len(inp2))
  27. buf1 = ffi.new("char []", ln)
  28. buf2 = ffi.new("char []", ln)
  29. ffi.memmove(buf1, inp1, len(inp1))
  30. ffi.memmove(buf2, inp2, len(inp2))
  31. eqL = len(inp1) == len(inp2)
  32. eqC = lib.sodium_memcmp(buf1, buf2, ln) == 0
  33. return eqL and eqC