]>
gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - rsa_source/rsa/core.py
1 # -*- coding: utf-8 -*-
3 # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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 '''Core mathematical operations.
18 This is the actual core RSA implementation, which is only defined
19 mathematically on integers.
24 def assert_int(var
, name
):
26 if type(var
) in (types
.IntType
, types
.LongType
):
29 raise TypeError('%s should be an integer, not %s' % (name
, var
.__class
__))
31 def encrypt_int(message
, ekey
, n
):
32 """Encrypts a message using encryption key 'ekey', working modulo n"""
34 assert_int(message
, 'message')
35 assert_int(ekey
, 'ekey')
39 raise ValueError('Only non-negative numbers are supported')
42 raise OverflowError("The message %i is too long for n=%i" % (message
, n
))
44 return pow(message
, ekey
, n
)
46 def decrypt_int(cyphertext
, dkey
, n
):
47 """Decrypts a cypher text using the decryption key 'dkey', working
50 if type(cyphertext
) not in (types
.IntType
, types
.LongType
):
51 raise TypeError('cyphertext should be an integer, not %s' %
54 assert_int(cyphertext
, 'cyphertext')
55 assert_int(dkey
, 'dkey')
58 message
= pow(cyphertext
, dkey
, n
)