core.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  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. # https://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. """Core mathematical operations.
  15. This is the actual core RSA implementation, which is only defined
  16. mathematically on integers.
  17. """
  18. def assert_int(var: int, name: str) -> None:
  19. if isinstance(var, int):
  20. return
  21. raise TypeError("%s should be an integer, not %s" % (name, var.__class__))
  22. def encrypt_int(message: int, ekey: int, n: int) -> int:
  23. """Encrypts a message using encryption key 'ekey', working modulo n"""
  24. assert_int(message, "message")
  25. assert_int(ekey, "ekey")
  26. assert_int(n, "n")
  27. if message < 0:
  28. raise ValueError("Only non-negative numbers are supported")
  29. if message > n:
  30. raise OverflowError("The message %i is too long for n=%i" % (message, n))
  31. return pow(message, ekey, n)
  32. def decrypt_int(cyphertext: int, dkey: int, n: int) -> int:
  33. """Decrypts a cypher text using the decryption key 'dkey', working modulo n"""
  34. assert_int(cyphertext, "cyphertext")
  35. assert_int(dkey, "dkey")
  36. assert_int(n, "n")
  37. message = pow(cyphertext, dkey, n)
  38. return message