• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
15"""Core mathematical operations.
16
17This is the actual core RSA implementation, which is only defined
18mathematically on integers.
19"""
20
21
22def assert_int(var: int, name: str) -> None:
23    if isinstance(var, int):
24        return
25
26    raise TypeError('%s should be an integer, not %s' % (name, var.__class__))
27
28
29def encrypt_int(message: int, ekey: int, n: int) -> int:
30    """Encrypts a message using encryption key 'ekey', working modulo n"""
31
32    assert_int(message, 'message')
33    assert_int(ekey, 'ekey')
34    assert_int(n, 'n')
35
36    if message < 0:
37        raise ValueError('Only non-negative numbers are supported')
38
39    if message > n:
40        raise OverflowError("The message %i is too long for n=%i" % (message, n))
41
42    return pow(message, ekey, n)
43
44
45def decrypt_int(cyphertext: int, dkey: int, n: int) -> int:
46    """Decrypts a cypher text using the decryption key 'dkey', working modulo n"""
47
48    assert_int(cyphertext, 'cyphertext')
49    assert_int(dkey, 'dkey')
50    assert_int(n, 'n')
51
52    message = pow(cyphertext, dkey, n)
53    return message
54