restructered padding
[python-cryptoplus.git] / src / CryptoPlus / Cipher / python_Serpent.py
blob29f9860a974677e8e9c7289fd037fa151cc5d68d
1 from blockcipher import *
2 from pyserpent import Serpent
4 def new(key,mode=MODE_ECB,IV=None,counter=None):
5 """Create a new cipher object
7 Wrapper for pure python implementation pyserpent.py
9 key = raw string containing the key
10 -> when using XTS mode: the key should be a tuple containing the 2 keys needed
11 mode = python_Serpent.MODE_ECB/CBC/CFB/OFB/CTR/XTS/CMAC, default is ECB
12 -> for every mode, except ECB and CTR, it is important to construct a seperate cipher for encryption and decryption
13 IV = IV as a raw string
14 -> needed for CBC, CFB and OFB mode
15 counter = counter object (CryptoPlus.Util.util.Counter)
16 -> only needed for CTR mode
17 -> use a seperate counter object for the cipher and decipher: the counter is updated directly, not a copy
18 see CTR example further on in the docstring
20 EXAMPLES:
21 **********
22 IMPORTING:
23 -----------
24 >>> from CryptoPlus.Cipher import python_Serpent
26 EXAMPLE:
27 ---------
28 NESSIE Test Vectors: http://www.cs.technion.ac.il/~biham/Reports/Serpent/Serpent-128-128.verified.test-vectors
30 >>> cipher = python_Serpent.new(('000102030405060708090A0B0C0D0E0F').decode('hex'))
31 >>> (cipher.encrypt(('33B3DC87EDDD9B0F6A1F407D14919365').decode('hex'))).encode('hex').upper()
32 '00112233445566778899AABBCCDDEEFF'
33 >>> ( cipher.decrypt((_).decode('hex')) ).encode('hex').upper()
34 '33B3DC87EDDD9B0F6A1F407D14919365'
36 >>> cipher = python_Serpent.new(('FDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFD').decode('hex'))
37 >>> (cipher.encrypt(('FDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFD').decode('hex'))).encode('hex').upper()
38 '81F9163BDF39B5BB2932AB91DF2A5FFC'
39 >>> ( cipher.decrypt((_).decode('hex')) ).encode('hex').upper()
40 'FDFDFDFDFDFDFDFDFDFDFDFDFDFDFDFD'
42 CBC EXAMPLE:
43 -------------
44 >>> key = ('000102030405060708090A0B0C0D0E0F').decode('hex')
45 >>> IV = ('00000000000000000000000000000000').decode('hex')
46 >>> plaintext = ('33B3DC87EDDD9B0F6A1F407D14919365'*3).decode('hex')
47 >>> cipher = python_Serpent.new(key,python_Serpent.MODE_CBC,IV)
48 >>> ciphertext = cipher.encrypt(plaintext)
49 >>> decipher = python_Serpent.new(key,python_Serpent.MODE_CBC,IV)
50 >>> ( decipher.decrypt(ciphertext)).encode('hex').upper()
51 '33B3DC87EDDD9B0F6A1F407D1491936533B3DC87EDDD9B0F6A1F407D1491936533B3DC87EDDD9B0F6A1F407D14919365'
52 """
53 return python_Serpent(key,mode,IV,counter)
55 class python_Serpent(BlockCipher):
56 def __init__(self,key,mode,IV,counter):
57 if len(key) not in (16,24,32) and type(key) is not tuple:
58 raise ValueError("Key should be 128, 192 or 256 bits")
59 cipher_module = Serpent
60 self.blocksize = 16
61 BlockCipher.__init__(self,key,mode,IV,counter,cipher_module)
63 def _test():
64 import doctest
65 doctest.testmod()
67 if __name__ == "__main__":
68 _test()