]> gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - rsa_source/rsa/core.py
on ajoute le module rsa car le client aussi en a besoin
[NK2015_Client_Python_Alpha.git] / rsa_source / rsa / core.py
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 # http://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 '''Core mathematical operations.
17
18 This is the actual core RSA implementation, which is only defined
19 mathematically on integers.
20 '''
21
22 import types
23
24 def assert_int(var, name):
25
26 if type(var) in (types.IntType, types.LongType):
27 return
28
29 raise TypeError('%s should be an integer, not %s' % (name, var.__class__))
30
31 def encrypt_int(message, ekey, n):
32 """Encrypts a message using encryption key 'ekey', working modulo n"""
33
34 assert_int(message, 'message')
35 assert_int(ekey, 'ekey')
36 assert_int(n, 'n')
37
38 if message < 0:
39 raise ValueError('Only non-negative numbers are supported')
40
41 if message > n:
42 raise OverflowError("The message %i is too long for n=%i" % (message, n))
43
44 return pow(message, ekey, n)
45
46 def decrypt_int(cyphertext, dkey, n):
47 """Decrypts a cypher text using the decryption key 'dkey', working
48 modulo n"""
49
50 if type(cyphertext) not in (types.IntType, types.LongType):
51 raise TypeError('cyphertext should be an integer, not %s' %
52 cyphertext.__type__)
53
54 assert_int(cyphertext, 'cyphertext')
55 assert_int(dkey, 'dkey')
56 assert_int(n, 'n')
57
58 message = pow(cyphertext, dkey, n)
59 return message
60