]>
gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - rsa_source/rsa/transform.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.
17 '''Data transformation functions.
19 From bytes to a number, number to bytes, etc.
25 from rsa
import common
28 r
"""Converts a list of bytes or an 8-bit string to an integer.
30 When using unicode strings, encode it to some encoding like UTF8 first.
32 >>> (((128 * 256) + 64) * 256) + 15
34 >>> bytes2int('\x80@\x0f')
39 return int(binascii
.hexlify(bytes
), 16)
41 def int2bytes(number
, block_size
=None):
42 r
'''Converts a number to a string of bytes.
44 @param number: the number to convert
45 @param block_size: the number of bytes to output. If the number encoded to
46 bytes is less than this, the block will be zero-padded. When not given,
47 the returned block is not padded.
49 @throws OverflowError when block_size is given and the number takes up more
50 bytes than fit into the block.
53 >>> int2bytes(123456789)
55 >>> bytes2int(int2bytes(123456789))
58 >>> int2bytes(123456789, 6)
59 '\x00\x00\x07[\xcd\x15'
60 >>> bytes2int(int2bytes(123456789, 128))
63 >>> int2bytes(123456789, 3)
64 Traceback (most recent call last):
66 OverflowError: Needed 4 bytes for number, but block size is 3
71 if type(number
) not in (types
.LongType
, types
.IntType
):
72 raise TypeError("You must pass an integer for 'number', not %s" %
76 raise ValueError('Negative numbers cannot be used: %i' % number
)
78 # Do some bounds checking
79 if block_size
is not None:
80 needed_bytes
= common
.byte_size(number
)
81 if needed_bytes
> block_size
:
82 raise OverflowError('Needed %i bytes for number, but block size '
83 'is %i' % (needed_bytes
, block_size
))
85 # Convert the number to bytes.
88 bytes
.insert(0, chr(number
& 0xFF))
91 # Pad with zeroes to fill the block
92 if block_size
is not None:
93 padding
= (block_size
- needed_bytes
) * '\x00'
97 return padding
+ ''.join(bytes
)
100 if __name__
== '__main__':