tlslite.utils.python_aes

Package tlslite :: Package utils :: Module python_aes |
[hide private]
[frames] | no frames]

# Source Code for Module tlslite.utils.python_aes

     1  # Author: Trevor Perrin
     2  # See the LICENSE file for legal information regarding use of this file.
     3
     4  """Pure-Python AES implementation."""
     5
     6  from .cryptomath import *
     7
     8  from .aes import *
     9  from .rijndael import rijndael
    10
    11 -def new(key, mode, IV):
    12      return Python_AES(key, mode, IV)
    13
    14 -class Python_AES(AES):
    15 -    def __init__(self, key, mode, IV):
    16          AES.__init__(self, key, mode, IV, "python")
    17          self.rijndael = rijndael(key, 16)
    18          self.IV = IV
    19
    20 -    def encrypt(self, plaintext):
    21          AES.encrypt(self, plaintext)
    22
    23          plaintextBytes = stringToBytes(plaintext)
    24          chainBytes = stringToBytes(self.IV)
    25
    26          #CBC Mode: For each block...
    27          for x in range(len(plaintextBytes)//16):
    28
    29              #XOR with the chaining block
    30              blockBytes = plaintextBytes[x*16 : (x*16)+16]
    31              for y in range(16):
    32                  blockBytes[y] ^= chainBytes[y]
    33              blockString = bytesToString(blockBytes)
    34
    35              #Encrypt it
    36              encryptedBytes = stringToBytes(self.rijndael.encrypt(blockString))
    37
    38              #Overwrite the input with the output
    39              for y in range(16):
    40                  plaintextBytes[(x*16)+y] = encryptedBytes[y]
    41
    42              #Set the next chaining block
    43              chainBytes = encryptedBytes
    44
    45          self.IV = bytesToString(chainBytes)
    46          return bytesToString(plaintextBytes)
    47
    48 -    def decrypt(self, ciphertext):
    49          AES.decrypt(self, ciphertext)
    50
    51          ciphertextBytes = stringToBytes(ciphertext)
    52          chainBytes = stringToBytes(self.IV)
    53
    54          #CBC Mode: For each block...
    55          for x in range(len(ciphertextBytes)//16):
    56
    57              #Decrypt it
    58              blockBytes = ciphertextBytes[x*16 : (x*16)+16]
    59              blockString = bytesToString(blockBytes)
    60              decryptedBytes = stringToBytes(self.rijndael.decrypt(blockString))
    61
    62              #XOR with the chaining block and overwrite the input with output
    63              for y in range(16):
    64                  decryptedBytes[y] ^= chainBytes[y]
    65                  ciphertextBytes[(x*16)+y] = decryptedBytes[y]
    66
    67              #Set the next chaining block
    68              chainBytes = blockBytes
    69
    70          self.IV = bytesToString(chainBytes)
    71          return bytesToString(ciphertextBytes)
    72