core.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # https://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Core mathematical operations.
  17. This is the actual core RSA implementation, which is only defined
  18. mathematically on integers.
  19. """
  20. from rsa._compat import is_integer
  21. def assert_int(var, name):
  22. if is_integer(var):
  23. return
  24. raise TypeError('%s should be an integer, not %s' % (name, var.__class__))
  25. def encrypt_int(message, ekey, n):
  26. """Encrypts a message using encryption key 'ekey', working modulo n"""
  27. assert_int(message, 'message')
  28. assert_int(ekey, 'ekey')
  29. assert_int(n, 'n')
  30. if message < 0:
  31. raise ValueError('Only non-negative numbers are supported')
  32. if message > n:
  33. raise OverflowError("The message %i is too long for n=%i" % (message, n))
  34. return pow(message, ekey, n)
  35. def decrypt_int(cyphertext, dkey, n):
  36. """Decrypts a cypher text using the decryption key 'dkey', working modulo n"""
  37. assert_int(cyphertext, 'cyphertext')
  38. assert_int(dkey, 'dkey')
  39. assert_int(n, 'n')
  40. message = pow(cyphertext, dkey, n)
  41. return message