summaryrefslogtreecommitdiff
path: root/rsa/core.py
blob: 639cba9ba931de313ce49c02d7df420fe641076e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
'''Core mathematical operations.

This is the actual core RSA implementation, which is only defined
mathematically on integers.
'''

import types

import rsa.common

def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0:
        raise ValueError('Only non-negative numbers are supported')
         
    if message > n:
        raise OverflowError("The message %i is too long for n=%i" % (message, n))

    # TODO: reinstate safebit
    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    #safebit = rsa.common.bit_size(n) - 2        # compute safe bit (MSB - 1)
    #message += (1 << safebit)                   # add safebit to ensure folding

    return pow(message, ekey, n)

def decrypt_int(cyphertext, dkey, n):
    """Decrypts a cypher text using the decryption key 'dkey', working
    modulo n"""

    message = pow(cyphertext, dkey, n)

    # TODO: reinstate safebit
    #safebit = rsa.common.bit_size(n) - 2        # compute safe bit (MSB - 1)
    #message -= (1 << safebit)                   # remove safebit before decode

    return message