crypto_scalarmult.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2013 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. from nacl import exceptions as exc
  16. from nacl._sodium import ffi, lib
  17. from nacl.exceptions import ensure
  18. crypto_scalarmult_BYTES = lib.crypto_scalarmult_bytes()
  19. crypto_scalarmult_SCALARBYTES = lib.crypto_scalarmult_scalarbytes()
  20. def crypto_scalarmult_base(n):
  21. """
  22. Computes and returns the scalar product of a standard group element and an
  23. integer ``n``.
  24. :param n: bytes
  25. :rtype: bytes
  26. """
  27. q = ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
  28. rc = lib.crypto_scalarmult_base(q, n)
  29. ensure(rc == 0,
  30. 'Unexpected library error',
  31. raising=exc.RuntimeError)
  32. return ffi.buffer(q, crypto_scalarmult_SCALARBYTES)[:]
  33. def crypto_scalarmult(n, p):
  34. """
  35. Computes and returns the scalar product of the given group element and an
  36. integer ``n``.
  37. :param p: bytes
  38. :param n: bytes
  39. :rtype: bytes
  40. """
  41. q = ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
  42. rc = lib.crypto_scalarmult(q, n, p)
  43. ensure(rc == 0,
  44. 'Unexpected library error',
  45. raising=exc.RuntimeError)
  46. return ffi.buffer(q, crypto_scalarmult_SCALARBYTES)[:]