Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/rsa/core.py: 20%
20 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:40 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-08 06:40 +0000
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.
15"""Core mathematical operations.
17This is the actual core RSA implementation, which is only defined
18mathematically on integers.
19"""
22def assert_int(var: int, name: str) -> None:
23 if isinstance(var, int):
24 return
26 raise TypeError("%s should be an integer, not %s" % (name, var.__class__))
29def encrypt_int(message: int, ekey: int, n: int) -> int:
30 """Encrypts a message using encryption key 'ekey', working modulo n"""
32 assert_int(message, "message")
33 assert_int(ekey, "ekey")
34 assert_int(n, "n")
36 if message < 0:
37 raise ValueError("Only non-negative numbers are supported")
39 if message > n:
40 raise OverflowError("The message %i is too long for n=%i" % (message, n))
42 return pow(message, ekey, n)
45def decrypt_int(cyphertext: int, dkey: int, n: int) -> int:
46 """Decrypts a cypher text using the decryption key 'dkey', working modulo n"""
48 assert_int(cyphertext, "cyphertext")
49 assert_int(dkey, "dkey")
50 assert_int(n, "n")
52 message = pow(cyphertext, dkey, n)
53 return message