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