OLD | NEW |
(Empty) | |
| 1 # -*- coding: ascii -*- |
| 2 # |
| 3 # Util/Counter.py : Fast counter for use with CTR-mode ciphers |
| 4 # |
| 5 # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net> |
| 6 # |
| 7 # =================================================================== |
| 8 # The contents of this file are dedicated to the public domain. To |
| 9 # the extent that dedication to the public domain is not available, |
| 10 # everyone is granted a worldwide, perpetual, royalty-free, |
| 11 # non-exclusive license to exercise all rights associated with the |
| 12 # contents of this file for any purpose whatsoever. |
| 13 # No rights are reserved. |
| 14 # |
| 15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 16 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 17 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
| 18 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS |
| 19 # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN |
| 20 # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
| 21 # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 # SOFTWARE. |
| 23 # =================================================================== |
| 24 """Fast counter functions for CTR cipher modes. |
| 25 |
| 26 CTR is a chaining mode for symmetric block encryption or decryption. |
| 27 Messages are divideded into blocks, and the cipher operation takes |
| 28 place on each block using the secret key and a unique *counter block*. |
| 29 |
| 30 The most straightforward way to fulfil the uniqueness property is |
| 31 to start with an initial, random *counter block* value, and increment it as |
| 32 the next block is processed. |
| 33 |
| 34 The block ciphers from `Crypto.Cipher` (when configured in *MODE_CTR* mode) |
| 35 invoke a callable object (the *counter* parameter) to get the next *counter bloc
k*. |
| 36 Unfortunately, the Python calling protocol leads to major performance degradatio
ns. |
| 37 |
| 38 The counter functions instantiated by this module will be invoked directly |
| 39 by the ciphers in `Crypto.Cipher`. The fact that the Python layer is bypassed |
| 40 lead to more efficient (and faster) execution of CTR cipher modes. |
| 41 |
| 42 An example of usage is the following: |
| 43 |
| 44 >>> from Crypto.Cipher import AES |
| 45 >>> from Crypto.Util import Counter |
| 46 >>> |
| 47 >>> pt = b'\x00'*1000000 |
| 48 >>> ctr = Counter.new(128) |
| 49 >>> cipher = AES.new(b'\x00'*16, AES.MODE_CTR, counter=ctr) |
| 50 >>> ct = cipher.encrypt(pt) |
| 51 |
| 52 :undocumented: __package__ |
| 53 """ |
| 54 import sys |
| 55 if sys.version_info[0] == 2 and sys.version_info[1] == 1: |
| 56 from Crypto.Util.py21compat import * |
| 57 from Crypto.Util.py3compat import * |
| 58 |
| 59 from Crypto.Util import _counter |
| 60 import struct |
| 61 |
| 62 # Factory function |
| 63 def new(nbits, prefix=b(""), suffix=b(""), initial_value=1, overflow=0, little_e
ndian=False, allow_wraparound=False, disable_shortcut=False): |
| 64 """Create a stateful counter block function suitable for CTR encryption mode
s. |
| 65 |
| 66 Each call to the function returns the next counter block. |
| 67 Each counter block is made up by three parts:: |
| 68 |
| 69 prefix || counter value || postfix |
| 70 |
| 71 The counter value is incremented by one at each call. |
| 72 |
| 73 :Parameters: |
| 74 nbits : integer |
| 75 Length of the desired counter, in bits. It must be a multiple of 8. |
| 76 prefix : byte string |
| 77 The constant prefix of the counter block. By default, no prefix is |
| 78 used. |
| 79 suffix : byte string |
| 80 The constant postfix of the counter block. By default, no suffix is |
| 81 used. |
| 82 initial_value : integer |
| 83 The initial value of the counter. Default value is 1. |
| 84 little_endian : boolean |
| 85 If True, the counter number will be encoded in little endian format. |
| 86 If False (default), in big endian format. |
| 87 allow_wraparound : boolean |
| 88 If True, the function will raise an *OverflowError* exception as soon |
| 89 as the counter wraps around. If False (default), the counter will |
| 90 simply restart from zero. |
| 91 disable_shortcut : boolean |
| 92 If True, do not make ciphers from `Crypto.Cipher` bypass the Python |
| 93 layer when invoking the counter block function. |
| 94 If False (default), bypass the Python layer. |
| 95 :Returns: |
| 96 The counter block function. |
| 97 """ |
| 98 |
| 99 # Sanity-check the message size |
| 100 (nbytes, remainder) = divmod(nbits, 8) |
| 101 if remainder != 0: |
| 102 # In the future, we might support arbitrary bit lengths, but for now we
don't. |
| 103 raise ValueError("nbits must be a multiple of 8; got %d" % (nbits,)) |
| 104 if nbytes < 1: |
| 105 raise ValueError("nbits too small") |
| 106 elif nbytes > 0xffff: |
| 107 raise ValueError("nbits too large") |
| 108 |
| 109 initval = _encode(initial_value, nbytes, little_endian) |
| 110 |
| 111 if little_endian: |
| 112 return _counter._newLE(bstr(prefix), bstr(suffix), initval, allow_wrapar
ound=allow_wraparound, disable_shortcut=disable_shortcut) |
| 113 else: |
| 114 return _counter._newBE(bstr(prefix), bstr(suffix), initval, allow_wrapar
ound=allow_wraparound, disable_shortcut=disable_shortcut) |
| 115 |
| 116 def _encode(n, nbytes, little_endian=False): |
| 117 retval = [] |
| 118 n = long(n) |
| 119 for i in range(nbytes): |
| 120 if little_endian: |
| 121 retval.append(bchr(n & 0xff)) |
| 122 else: |
| 123 retval.insert(0, bchr(n & 0xff)) |
| 124 n >>= 8 |
| 125 return b("").join(retval) |
| 126 |
| 127 # vim:set ts=4 sw=4 sts=4 expandtab: |
OLD | NEW |