File: Python_AES.py

package info (click to toggle)
python-gdata 2.0.18%2Bdfsg1-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 8,460 kB
  • ctags: 17,143
  • sloc: python: 70,779; ansic: 150; makefile: 27; sh: 3
file content (68 lines) | stat: -rwxr-xr-x 2,121 bytes parent folder | download | duplicates (10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Pure-Python AES implementation."""

from cryptomath import *

from AES import *
from rijndael import rijndael

def new(key, mode, IV):
    return Python_AES(key, mode, IV)

class Python_AES(AES):
    def __init__(self, key, mode, IV):
        AES.__init__(self, key, mode, IV, "python")
        self.rijndael = rijndael(key, 16)
        self.IV = IV

    def encrypt(self, plaintext):
        AES.encrypt(self, plaintext)

        plaintextBytes = stringToBytes(plaintext)
        chainBytes = stringToBytes(self.IV)

        #CBC Mode: For each block...
        for x in range(len(plaintextBytes)/16):

            #XOR with the chaining block
            blockBytes = plaintextBytes[x*16 : (x*16)+16]
            for y in range(16):
                blockBytes[y] ^= chainBytes[y]
            blockString = bytesToString(blockBytes)

            #Encrypt it
            encryptedBytes = stringToBytes(self.rijndael.encrypt(blockString))

            #Overwrite the input with the output
            for y in range(16):
                plaintextBytes[(x*16)+y] = encryptedBytes[y]

            #Set the next chaining block
            chainBytes = encryptedBytes

        self.IV = bytesToString(chainBytes)
        return bytesToString(plaintextBytes)

    def decrypt(self, ciphertext):
        AES.decrypt(self, ciphertext)

        ciphertextBytes = stringToBytes(ciphertext)
        chainBytes = stringToBytes(self.IV)

        #CBC Mode: For each block...
        for x in range(len(ciphertextBytes)/16):

            #Decrypt it
            blockBytes = ciphertextBytes[x*16 : (x*16)+16]
            blockString = bytesToString(blockBytes)
            decryptedBytes = stringToBytes(self.rijndael.decrypt(blockString))

            #XOR with the chaining block and overwrite the input with output
            for y in range(16):
                decryptedBytes[y] ^= chainBytes[y]
                ciphertextBytes[(x*16)+y] = decryptedBytes[y]

            #Set the next chaining block
            chainBytes = blockBytes

        self.IV = bytesToString(chainBytes)
        return bytesToString(ciphertextBytes)