Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 17.77 KB | None | 0 0
  1. import binascii
  2. import re
  3.  
  4.  
  5. class AES(object):
  6.     """ Started on 3/16/2017
  7.    The Advanced Encryption Standard (AES), also known by its original
  8.    name Rijndael, is a specification for the encryption of electronic
  9.    data established by the U.S. National Institute of Standards and
  10.    Technology (NIST) in 2001. AES is a subset of the Rijndael cipher
  11.    developed by two Belgian cryptographers, Joan Daemen and Vincent
  12.    Rijmen, who submitted a proposal to NIST during the AES selection
  13.    process. Rijndael is a family of ciphers with different key
  14.    and block sizes.
  15.  
  16.    # Instructions for my AES implication
  17.    aes = AES(mode='ecb', input_type='hex')
  18.            
  19.    # Test vector 128-bit key
  20.    key = '000102030405060708090a0b0c0d0e0f'
  21.        
  22.    # Encrypt data with your key
  23.    cyphertext = aes.encryption('00112233445566778899aabbccddeeff', key)
  24.        
  25.    # Decrypt data with the same key
  26.    plaintext = aes.decryption(cyphertext, key)
  27.    """
  28.     def __init__(self, mode, input_type, iv=None):
  29.         self.mode = mode
  30.         self.input = input_type
  31.         self.iv = iv
  32.         self.Nb = 0
  33.         self.Nk = 0
  34.         self.Nr = 0
  35.  
  36.         # Rijndael S-box
  37.         self.sbox = [
  38.             0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
  39.             0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
  40.             0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
  41.             0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
  42.             0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
  43.             0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
  44.             0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,
  45.             0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
  46.             0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
  47.             0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
  48.             0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
  49.             0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  50.             0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
  51.             0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
  52.             0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
  53.             0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
  54.             0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
  55.             0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
  56.             0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
  57.             0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
  58.             0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
  59.             0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
  60.             0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
  61.             0x54, 0xbb, 0x16]
  62.  
  63.         # Rijndael Inverted S-box
  64.         self.rsbox = [
  65.             0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
  66.             0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
  67.             0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54,
  68.             0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
  69.             0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
  70.             0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8,
  71.             0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
  72.             0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
  73.             0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab,
  74.             0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
  75.             0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
  76.             0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41,
  77.             0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
  78.             0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
  79.             0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d,
  80.             0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
  81.             0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
  82.             0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
  83.             0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60,
  84.             0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
  85.             0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
  86.             0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b,
  87.             0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
  88.             0x21, 0x0c, 0x7d]
  89.  
  90.         self.rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]
  91.  
  92.     @staticmethod
  93.     def pad(data, block=16):
  94.         """ Padding method for data
  95.  
  96.        :param data: Data to pad
  97.        :param int block: Block size
  98.        :return: Padded data """
  99.         if block < 2 or block > 255:
  100.             raise ValueError("Block Size must be < 2 and > 255")
  101.  
  102.         if len(data) is block: return data
  103.         pads = block - (len(data) % block)
  104.         return data + binascii.unhexlify(('%02x' % int(pads)).encode()) + b'\x00' * (pads - 1)
  105.  
  106.     @staticmethod
  107.     def unpad(data):
  108.         """ Un-Padding for data
  109.  
  110.        :param data: Data to be un-padded
  111.        :return: Data with removed padding """
  112.         p = None
  113.         for x in data[::-1]:
  114.             if x is 0:
  115.                 continue
  116.             elif x is not 0:
  117.                 p = x; break
  118.         data = data[::-1]
  119.         data = data[p:]
  120.         return data[::-1]
  121.  
  122.     @staticmethod
  123.     def unblock(data, size=16):
  124.         """ Unblock binary data
  125.  
  126.        :param bytes data: Binary data to split into blocks
  127.        :param int size: Block size
  128.        :return: Blocked binary data """
  129.         # Return 64-bit blocks from data
  130.         return [data[x:x + size] for x in range(0, len(data), size)]
  131.  
  132.     @staticmethod
  133.     def RotWord(word):
  134.         """ Takes a word [a0, a1, a2, a3] as input and perform a
  135.        cyclic permutation that returns the word [a1, a2, a3, a0].
  136.  
  137.        :param str word: Row within State Matrix
  138.        :return: Circular byte left shift """
  139.         return int(word[2:] + word[0:2], 16)
  140.  
  141.     @staticmethod
  142.     def StateMatrix(state):
  143.         """ Formats a State Matrix str to a properly formatted list.
  144.  
  145.        :param str state: String State Matrix
  146.        :return: Formatted State Matrix """
  147.         new_state = []
  148.         split = re.findall('.' * 2, state)
  149.         for x in range(4):
  150.             new_state.append(split[0:4][x]); new_state.append(split[4:8][x])
  151.             new_state.append(split[8:12][x]); new_state.append(split[12:16][x])
  152.         return new_state
  153.  
  154.     @staticmethod
  155.     def RevertStateMatrix(state):
  156.         """ Reverts State Matrix format as str
  157.  
  158.        :param list state: Final State Matrix
  159.        :return: Reverted State Matrix """
  160.         columns = [state[x:x + 4] for x in range(0, 16, 4)]
  161.         return ''.join(''.join([columns[0][x], columns[1][x], columns[2][x], columns[3][x]]) for x in range(4))
  162.  
  163.     @staticmethod
  164.     def galois(a, b):
  165.         """ Galois multiplication of 8 bit characters a and b
  166.  
  167.        :param a: State Matrix col or row
  168.        :param b: Fixed number
  169.        :return: Galois field GF(2^8) """
  170.         p = 0
  171.         for counter in range(8):
  172.             if b & 1: p ^= a
  173.             hi_bit_set = a & 0x80
  174.             a <<= 1
  175.             # keep a 8 bit
  176.             a &= 0xFF
  177.             if hi_bit_set:
  178.                 a ^= 0x1b
  179.             b >>= 1
  180.         return p
  181.  
  182.     @staticmethod
  183.     def AddRoundKey(state, key):
  184.         """ Round Key is added to the State using an XOR operation.
  185.  
  186.        :param list state: State Matrix
  187.        :param list key: Round Key
  188.        :return: Hex values of XOR operation """
  189.         return ['%02x' % (int(state[x], 16) ^ int(key[x], 16)) for x in range(16)]
  190.  
  191.     def ShiftRows(self, state, isInv):
  192.         """ Changes the State by cyclically shifting the last
  193.        three rows of the State by different offsets.
  194.  
  195.        :param list state: State Matrix
  196.        :param isInv: Encrypt or Decrypt
  197.        :return: Shifted state by offsets [0, 1, 2, 3] """
  198.         offset = 0
  199.         if isInv: state = re.findall('.' * 2, self.RevertStateMatrix(state))
  200.         for x in range(0, 16, 4):
  201.             state[x:x + 4] = state[x:x + 4][offset:] + state[x:x + 4][:offset]
  202.             if not isInv:
  203.                 offset += 1
  204.             elif isInv:
  205.                 offset -= 1
  206.         if isInv: return self.StateMatrix(''.join(state))
  207.         return state
  208.  
  209.     def SubWord(self, byte):
  210.         """ Key Expansion routine that takes a four-byte
  211.        input word and applies an S-box substitution.
  212.  
  213.        :param int byte: Output from the circular byte left shift
  214.        :return: Substituted bytes through sbox """
  215.         return ((self.sbox[(byte >> 24 & 0xff)] << 24) + (self.sbox[(byte >> 16 & 0xff)] << 16) +
  216.                 (self.sbox[(byte >> 8 & 0xff)] << 8) + self.sbox[byte & 0xff])
  217.  
  218.     def SubBytes(self, state, isInv):
  219.         """  Transforms the State Matrix using a nonlinear byte S-box
  220.        that operates on each of the State bytes independently.
  221.  
  222.        :param state: State matrix input
  223.        :param isInv: Encrypt or decrypt mode
  224.        :returns: Byte substitution from the state matrix """
  225.         if not isInv: return ['%02x' % self.sbox[int(state[x], 16)] for x in range(16)]
  226.         elif isInv: return ['%02x' % self.rsbox[int(state[x], 16)] for x in range(16)]
  227.  
  228.     # noinspection PyAssignmentToLoopOrWithParameter
  229.     def MixColumns(self, state, isInv):
  230.         """ Operates on the State column-by-column, treating each column as
  231.        a four-term polynomial. The columns are considered as polynomials
  232.        over GF(2^8) and multiplied modulo x^4 + 1 with a fixed polynomial a(x).
  233.  
  234.        :param state: State Matrix input
  235.        :param isInv: Encrypt or decrypt mode
  236.        :return:
  237.        """
  238.         if isInv: fixed = [14, 9, 13, 11]; state = self.StateMatrix(''.join(state))
  239.         else: fixed = [2, 1, 1, 3]
  240.         columns = [state[x:x + 4] for x in range(0, 16, 4)]
  241.         row = [0, 3, 2, 1]
  242.         col = 0
  243.         output = []
  244.         for _ in range(4):
  245.             for _ in range(4):
  246.                 # noinspection PyTypeChecker
  247.                 output.append('%02x' % (
  248.                     self.galois(int(columns[row[0]][col], 16), fixed[0]) ^
  249.                     self.galois(int(columns[row[1]][col], 16), fixed[1]) ^
  250.                     self.galois(int(columns[row[2]][col], 16), fixed[2]) ^
  251.                     self.galois(int(columns[row[3]][col], 16), fixed[3])))
  252.                 row = [row[-1]] + row[:-1]
  253.             col += 1
  254.         return output
  255.  
  256.     def Cipher(self, expandedKey, data):
  257.         """ At the start of the Cipher, the input is copied to the
  258.        State Matrix. After an initial Round Key addition, the
  259.        State Matrix is transformed by implementing a round function
  260.        10, 12, or 14 times (depending on the key length), with the final
  261.        round differing slightly from the first Nr -1 rounds. The final
  262.        State Matrix is then copied as the output.
  263.  
  264.        :param list expandedKey: The expanded key schedule
  265.        :param str data: Hex string to encrypt
  266.        :return: Encrypted data as a Hex string """
  267.         # (data, key)
  268.         state = self.AddRoundKey(self.StateMatrix(data), expandedKey[0])
  269.        
  270.         for r in range(self.Nr - 1):
  271.             state = self.SubBytes(state, False) # replace with SBOX[07] = c5 ...
  272.             state = self.ShiftRows(state, False)
  273.             state = self.StateMatrix(''.join(self.MixColumns(state, False)))
  274.             state = self.AddRoundKey(state, expandedKey[r + 1])
  275.  
  276.         state = self.SubBytes(state, False)
  277.         state = self.ShiftRows(state, False)
  278.         state = self.AddRoundKey(state, expandedKey[self.Nr])
  279.         return self.RevertStateMatrix(state)
  280.  
  281.     def InvCipher(self, expandedKey, data):
  282.         state = self.AddRoundKey(re.findall('.' * 2, data), expandedKey[self.Nr])
  283.  
  284.         for r in range(self.Nr - 1):
  285.             state = self.ShiftRows(state, True)
  286.             state = self.SubBytes(state, True)
  287.             state = self.AddRoundKey(state, expandedKey[-(r + 2)])
  288.             state = self.MixColumns(state, True)
  289.  
  290.         state = self.ShiftRows(state, True)
  291.         state = self.SubBytes(state, True)
  292.         state = self.AddRoundKey(state, expandedKey[0])
  293.         return ''.join(state)
  294.  
  295.     def ExpandKey(self, key):
  296.         """ Takes the Cipher Key and performs a Key Expansion routine to
  297.        generate a key schedule thus generating a total of Nb (Nr + 1) words.
  298.  
  299.        :param str key: 128, 192, 256 bit Cipher Key
  300.        :return: Expanded Cipher Keys """
  301.         w = ['%08x' % int(x, 16) for x in re.findall('.' * 8, key)]
  302.  
  303.         i = self.Nk
  304.         while i < self.Nb * (self.Nr + 1):
  305.             temp = w[i - 1]
  306.             if i % self.Nk is 0:
  307.                 temp = '%08x' % (self.SubWord(self.RotWord(temp)) ^ (self.rcon[i // self.Nk] << 24))
  308.             elif self.Nk > 6 and i % self.Nk is 4:
  309.                 temp = '%08x' % self.SubWord(int(temp, 16))
  310.             w.append('%08x' % (int(w[i - self.Nk], 16) ^ int(temp, 16)))
  311.             i += 1
  312.  
  313.         return [self.StateMatrix(''.join(w[x:x + 4])) for x in range(0, len(w), self.Nk)]
  314.  
  315.     def key_handler(self, key, isInv):
  316.         """ Gets the key length and sets Nb, Nk, Nr accordingly.
  317.  
  318.        :param str key: 128, 192, 256 bit Cipher Key
  319.        :param isInv: Encrypt or decrypt mode
  320.        :return: Expanded Cipher Keys """
  321.         # 128-bit key
  322.         if len(key) is 32:
  323.             #self.Nb = 4; self.Nk = 4; self.Nr = 10
  324.             self.Nb = 4; self.Nk = 4; self.Nr = 4
  325.         # 192-bit key
  326.         elif len(key) is 48:
  327.             self.Nb = 4; self.Nk = 6; self.Nr = 12
  328.         # 256-bit key
  329.         elif len(key) is 64:
  330.             self.Nb = 4; self.Nk = 8; self.Nr = 14
  331.         # Raise error on invalid key size
  332.         else: raise AssertionError("%s Is an invalid Key!\nUse a 128-bit, 192-bit or 256-bit key!" % key)
  333.         # Return the expanded key
  334.         if not isInv: return self.ExpandKey(key)
  335.         # Return the inverse expanded key
  336.         if isInv: return [re.findall('.' * 2, self.RevertStateMatrix(x)) for x in self.ExpandKey(key)]
  337.  
  338.     def aes_main(self, data, key, isInv):
  339.         """ Handle encryption and decryption modes
  340.  
  341.        :param data: Data to be handled (type defined by input type)
  342.        :param key: Cipher Key to be expanded
  343.        :param isInv: Encrypt or decrypt mode
  344.        :return: Data as hex string or binary data (defined by output type) """
  345.         # Get the expanded key set
  346.         expanded_key = self.key_handler(key, isInv)
  347.         # Encrypt using ECB mode
  348.         if self.mode is 'ecb': return self.ecb(data, expanded_key, isInv)
  349.         # Encrypt using CBC mode
  350.         elif self.mode is 'cbc': return self.cbc(data, expanded_key, isInv)
  351.         # Raise error on invalid mode
  352.         else: raise AttributeError("\n\n\tSupported AES Modes of Operation are ['ecb', 'cbc']")
  353.  
  354.     def encryption(self, data, key):
  355.         """ Main AES Encryption function
  356.  
  357.        :param data: Input for encryption
  358.        :param key: Encryption key
  359.        :return: Encrypted data """
  360.         return self.aes_main(data, key, False)
  361.  
  362.     def decryption(self, data, key):
  363.         """ Main AES Decryption function
  364.  
  365.        :param data: Input for decryption
  366.        :param key: Decryption key
  367.        :return: Decrypted data """
  368.         return self.aes_main(data, key, True)
  369.  
  370.     @staticmethod
  371.     def xor(first, last):
  372.         """ Xor method for CBC usage    
  373.    
  374.        :param first: first encrypted block
  375.        :param last: last encrypted block
  376.        :return: Xor output of two blocks """
  377.         first = re.findall('.' * 2, first)
  378.         last = re.findall('.' * 2, last)
  379.         return ''.join('%02x' % (int(first[x], 16) ^ int(last[x], 16)) for x in range(16))
  380.  
  381.     def ecb(self, data, expanded_key, isInv):
  382.         """ ECB mode:
  383.        The simplest of the encryption modes is the Electronic
  384.        Codebook (ECB) mode. The message is divided into blocks,
  385.        and each block is encrypted separately.
  386.  
  387.        :param isInv:
  388.        :param data: Data to be encrypted (type defined by input type)
  389.        :param expanded_key: The AES expanded key set
  390.        :return: Data as string or binary data (defined by output type)"""
  391.         # Encrypt hex string data
  392.         if self.input is 'hex':
  393.             if not isInv: return self.Cipher(expanded_key, data)
  394.             elif isInv: return self.InvCipher(expanded_key, data)
  395.         # Encrypt an text string
  396.         elif self.input is 'text':
  397.             if not isInv: return self.Cipher(expanded_key, ''.join('%02x' % x for x in self.pad(data.encode())))
  398.             elif isInv: return str(self.unpad(binascii.unhexlify(self.InvCipher(expanded_key, data).encode())))[2:-1]
  399.         # Encrypt a stream of binary data
  400.         elif self.input is 'data':
  401.             if not isInv: return b''.join(binascii.unhexlify(self.Cipher(
  402.                 expanded_key, str(binascii.hexlify(x))[2:-1]).encode()) for x in self.unblock(data))
  403.             if isInv: return b''.join(binascii.unhexlify(self.InvCipher(
  404.                 expanded_key, str(binascii.hexlify(x))[2:-1]).encode()) for x in self.unblock(data))
  405.         # Raise error on invalid input
  406.         else: raise AttributeError("\n\n\tSupported Input types are ['hex', 'text', 'data']")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement