Guest User

Untitled

a guest
Apr 5th, 2024
13
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 53.12 KB | Source Code | 0 0
  1. #!/usr/bin/python
  2. #
  3. # aes.py: implements AES - Advanced Encryption Standard
  4. # from the SlowAES project, http://code.google.com/p/slowaes/
  5. #
  6. # Copyright (c) 2008    Josh Davis ( http://www.josh-davis.org ),
  7. #           Alex Martelli ( http://www.aleax.it )
  8. #
  9. # Ported from C code written by Laurent Haan ( http://www.progressive-coding.com )
  10. #
  11. # Licensed under the Apache License, Version 2.0
  12. # http://www.apache.org/licenses/
  13. #
  14. import os
  15. #import sys
  16. import math
  17.  
  18. from hashlib import md5
  19.  
  20.  
  21. def append_PKCS7_padding(s):
  22.     """return s padded to a multiple of 16-bytes by PKCS7 padding"""
  23.     numpads = 16 - (len(s)%16)
  24.     return s + numpads*chr(numpads)
  25.  
  26. def strip_PKCS7_padding(s):
  27.     """return s stripped of PKCS7 padding"""
  28.     if len(s)%16 or not s:
  29.         raise ValueError("String of len %d can't be PCKS7-padded" % len(s))
  30.     numpads = ord(s[-1])
  31.     if numpads > 16:
  32.         raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1])
  33.     return s[:-numpads]
  34.  
  35. class AES(object):
  36.     # valid key sizes
  37.     keySize = dict(SIZE_128=16, SIZE_192=24, SIZE_256=32)
  38.  
  39.     # Rijndael S-box
  40.     sbox =  [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
  41.             0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
  42.             0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
  43.             0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
  44.             0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
  45.             0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
  46.             0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,
  47.             0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
  48.             0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
  49.             0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
  50.             0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
  51.             0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  52.             0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
  53.             0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
  54.             0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
  55.             0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
  56.             0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
  57.             0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
  58.             0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
  59.             0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
  60.             0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
  61.             0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
  62.             0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
  63.             0x54, 0xbb, 0x16]
  64.  
  65.     # Rijndael Inverted S-box
  66.     rsbox = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
  67.             0x9e, 0x81, 0xf3, 0xd7, 0xfb , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
  68.             0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb , 0x54,
  69.             0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
  70.             0x42, 0xfa, 0xc3, 0x4e , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
  71.             0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 , 0x72, 0xf8,
  72.             0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
  73.             0x65, 0xb6, 0x92 , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
  74.             0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 , 0x90, 0xd8, 0xab,
  75.             0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
  76.             0x45, 0x06 , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
  77.             0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b , 0x3a, 0x91, 0x11, 0x41,
  78.             0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
  79.             0x73 , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
  80.             0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e , 0x47, 0xf1, 0x1a, 0x71, 0x1d,
  81.             0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b ,
  82.             0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
  83.             0xfe, 0x78, 0xcd, 0x5a, 0xf4 , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
  84.             0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f , 0x60,
  85.             0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
  86.             0x93, 0xc9, 0x9c, 0xef , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
  87.             0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 , 0x17, 0x2b,
  88.             0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
  89.             0x21, 0x0c, 0x7d]
  90.  
  91.     def getSBoxValue(self,num):
  92.         """Retrieves a given S-Box Value"""
  93.         return self.sbox[num]
  94.  
  95.     def getSBoxInvert(self,num):
  96.         """Retrieves a given Inverted S-Box Value"""
  97.         return self.rsbox[num]
  98.  
  99.     def rotate(self, word):
  100.         """ Rijndael's key schedule rotate operation.
  101.  
  102.        Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
  103.        Word is an char list of size 4 (32 bits overall).
  104.        """
  105.         return word[1:] + word[:1]
  106.  
  107.     # Rijndael Rcon
  108.     Rcon = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
  109.             0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97,
  110.             0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  111.             0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66,
  112.             0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
  113.             0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  114.             0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
  115.             0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61,
  116.             0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  117.             0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
  118.             0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc,
  119.             0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  120.             0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
  121.             0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
  122.             0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  123.             0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
  124.             0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4,
  125.             0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  126.             0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08,
  127.             0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
  128.             0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  129.             0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2,
  130.             0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74,
  131.             0xe8, 0xcb ]
  132.  
  133.     def getRconValue(self, num):
  134.         """Retrieves a given Rcon Value"""
  135.         return self.Rcon[num]
  136.  
  137.     def core(self, word, iteration):
  138.         """Key schedule core."""
  139.         # rotate the 32-bit word 8 bits to the left
  140.         word = self.rotate(word)
  141.         # apply S-Box substitution on all 4 parts of the 32-bit word
  142.         for i in range(4):
  143.             word[i] = self.getSBoxValue(word[i])
  144.         # XOR the output of the rcon operation with i to the first part
  145.         # (leftmost) only
  146.         word[0] = word[0] ^ self.getRconValue(iteration)
  147.         return word
  148.  
  149.     def expandKey(self, key, size, expandedKeySize):
  150.         """Rijndael's key expansion.
  151.  
  152.        Expands an 128,192,256 key into an 176,208,240 bytes key
  153.  
  154.        expandedKey is a char list of large enough size,
  155.        key is the non-expanded key.
  156.        """
  157.         # current expanded keySize, in bytes
  158.         currentSize = 0
  159.         rconIteration = 1
  160.         expandedKey = [0] * expandedKeySize
  161.  
  162.         # set the 16, 24, 32 bytes of the expanded key to the input key
  163.         for j in range(size):
  164.             expandedKey[j] = key[j]
  165.         currentSize += size
  166.  
  167.         while currentSize < expandedKeySize:
  168.             # assign the previous 4 bytes to the temporary value t
  169.             t = expandedKey[currentSize-4:currentSize]
  170.  
  171.             # every 16,24,32 bytes we apply the core schedule to t
  172.             # and increment rconIteration afterwards
  173.             if currentSize % size == 0:
  174.                 t = self.core(t, rconIteration)
  175.                 rconIteration += 1
  176.             # For 256-bit keys, we add an extra sbox to the calculation
  177.             if size == self.keySize["SIZE_256"] and ((currentSize % size) == 16):
  178.                 for l in range(4): t[l] = self.getSBoxValue(t[l])
  179.  
  180.             # We XOR t with the four-byte block 16,24,32 bytes before the new
  181.             # expanded key.  This becomes the next four bytes in the expanded
  182.             # key.
  183.             for m in range(4):
  184.                 expandedKey[currentSize] = expandedKey[currentSize - size] ^ \
  185.                         t[m]
  186.                 currentSize += 1
  187.  
  188.         return expandedKey
  189.  
  190.     def addRoundKey(self, state, roundKey):
  191.         """Adds (XORs) the round key to the state."""
  192.         for i in range(16):
  193.             state[i] ^= roundKey[i]
  194.         return state
  195.  
  196.     def createRoundKey(self, expandedKey, roundKeyPointer):
  197.         """Create a round key.
  198.        Creates a round key from the given expanded key and the
  199.        position within the expanded key.
  200.        """
  201.         roundKey = [0] * 16
  202.         for i in range(4):
  203.             for j in range(4):
  204.                 roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]
  205.         return roundKey
  206.  
  207.     def galois_multiplication(self, a, b):
  208.         """Galois multiplication of 8 bit characters a and b."""
  209.         p = 0
  210.         for counter in range(8):
  211.             if b & 1: p ^= a
  212.             hi_bit_set = a & 0x80
  213.             a <<= 1
  214.             # keep a 8 bit
  215.             a &= 0xFF
  216.             if hi_bit_set:
  217.                 a ^= 0x1b
  218.             b >>= 1
  219.         return p
  220.  
  221.     #
  222.     # substitute all the values from the state with the value in the SBox
  223.     # using the state value as index for the SBox
  224.     #
  225.     def subBytes(self, state, isInv):
  226.         if isInv: getter = self.getSBoxInvert
  227.         else: getter = self.getSBoxValue
  228.         for i in range(16): state[i] = getter(state[i])
  229.         return state
  230.  
  231.     # iterate over the 4 rows and call shiftRow() with that row
  232.     def shiftRows(self, state, isInv):
  233.         for i in range(4):
  234.             state = self.shiftRow(state, i*4, i, isInv)
  235.         return state
  236.  
  237.     # each iteration shifts the row to the left by 1
  238.     def shiftRow(self, state, statePointer, nbr, isInv):
  239.         for i in range(nbr):
  240.             if isInv:
  241.                 state[statePointer:statePointer+4] = \
  242.                         state[statePointer+3:statePointer+4] + \
  243.                         state[statePointer:statePointer+3]
  244.             else:
  245.                 state[statePointer:statePointer+4] = \
  246.                         state[statePointer+1:statePointer+4] + \
  247.                         state[statePointer:statePointer+1]
  248.         return state
  249.  
  250.     # galois multiplication of the 4x4 matrix
  251.     def mixColumns(self, state, isInv):
  252.         # iterate over the 4 columns
  253.         for i in range(4):
  254.             # construct one column by slicing over the 4 rows
  255.             column = state[i:i+16:4]
  256.             # apply the mixColumn on one column
  257.             column = self.mixColumn(column, isInv)
  258.             # put the values back into the state
  259.             state[i:i+16:4] = column
  260.  
  261.         return state
  262.  
  263.     # galois multiplication of 1 column of the 4x4 matrix
  264.     def mixColumn(self, column, isInv):
  265.         if isInv: mult = [14, 9, 13, 11]
  266.         else: mult = [2, 1, 1, 3]
  267.         cpy = list(column)
  268.         g = self.galois_multiplication
  269.  
  270.         column[0] = g(cpy[0], mult[0]) ^ g(cpy[3], mult[1]) ^ \
  271.                     g(cpy[2], mult[2]) ^ g(cpy[1], mult[3])
  272.         column[1] = g(cpy[1], mult[0]) ^ g(cpy[0], mult[1]) ^ \
  273.                     g(cpy[3], mult[2]) ^ g(cpy[2], mult[3])
  274.         column[2] = g(cpy[2], mult[0]) ^ g(cpy[1], mult[1]) ^ \
  275.                     g(cpy[0], mult[2]) ^ g(cpy[3], mult[3])
  276.         column[3] = g(cpy[3], mult[0]) ^ g(cpy[2], mult[1]) ^ \
  277.                     g(cpy[1], mult[2]) ^ g(cpy[0], mult[3])
  278.         return column
  279.  
  280.     # applies the 4 operations of the forward round in sequence
  281.     def aes_round(self, state, roundKey):
  282.         state = self.subBytes(state, False)
  283.         state = self.shiftRows(state, False)
  284.         state = self.mixColumns(state, False)
  285.         state = self.addRoundKey(state, roundKey)
  286.         return state
  287.  
  288.     # applies the 4 operations of the inverse round in sequence
  289.     def aes_invRound(self, state, roundKey):
  290.         state = self.shiftRows(state, True)
  291.         state = self.subBytes(state, True)
  292.         state = self.addRoundKey(state, roundKey)
  293.         state = self.mixColumns(state, True)
  294.         return state
  295.  
  296.     # Perform the initial operations, the standard round, and the final
  297.     # operations of the forward aes, creating a round key for each round
  298.     def aes_main(self, state, expandedKey, nbrRounds):
  299.         state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
  300.         i = 1
  301.         while i < nbrRounds:
  302.             state = self.aes_round(state,
  303.                                    self.createRoundKey(expandedKey, 16*i))
  304.             i += 1
  305.         state = self.subBytes(state, False)
  306.         state = self.shiftRows(state, False)
  307.         state = self.addRoundKey(state,
  308.                                  self.createRoundKey(expandedKey, 16*nbrRounds))
  309.         return state
  310.  
  311.     # Perform the initial operations, the standard round, and the final
  312.     # operations of the inverse aes, creating a round key for each round
  313.     def aes_invMain(self, state, expandedKey, nbrRounds):
  314.         state = self.addRoundKey(state,
  315.                                  self.createRoundKey(expandedKey, 16*nbrRounds))
  316.         i = nbrRounds - 1
  317.         while i > 0:
  318.             state = self.aes_invRound(state,
  319.                                       self.createRoundKey(expandedKey, 16*i))
  320.             i -= 1
  321.         state = self.shiftRows(state, True)
  322.         state = self.subBytes(state, True)
  323.         state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
  324.         return state
  325.  
  326.     # encrypts a 128 bit input block against the given key of size specified
  327.     def encrypt(self, iput, key, size):
  328.         output = [0] * 16
  329.         # the number of rounds
  330.         nbrRounds = 0
  331.         # the 128 bit block to encode
  332.         block = [0] * 16
  333.         # set the number of rounds
  334.         if size == self.keySize["SIZE_128"]: nbrRounds = 10
  335.         elif size == self.keySize["SIZE_192"]: nbrRounds = 12
  336.         elif size == self.keySize["SIZE_256"]: nbrRounds = 14
  337.         else: return None
  338.  
  339.         # the expanded keySize
  340.         expandedKeySize = 16*(nbrRounds+1)
  341.  
  342.         # Set the block values, for the block:
  343.         # a0,0 a0,1 a0,2 a0,3
  344.         # a1,0 a1,1 a1,2 a1,3
  345.         # a2,0 a2,1 a2,2 a2,3
  346.         # a3,0 a3,1 a3,2 a3,3
  347.         # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
  348.         #
  349.         # iterate over the columns
  350.         for i in range(4):
  351.             # iterate over the rows
  352.             for j in range(4):
  353.                 block[(i+(j*4))] = iput[(i*4)+j]
  354.  
  355.         # expand the key into an 176, 208, 240 bytes key
  356.         # the expanded key
  357.         expandedKey = self.expandKey(key, size, expandedKeySize)
  358.  
  359.         # encrypt the block using the expandedKey
  360.         block = self.aes_main(block, expandedKey, nbrRounds)
  361.  
  362.         # unmap the block again into the output
  363.         for k in range(4):
  364.             # iterate over the rows
  365.             for l in range(4):
  366.                 output[(k*4)+l] = block[(k+(l*4))]
  367.         return output
  368.  
  369.     # decrypts a 128 bit input block against the given key of size specified
  370.     def decrypt(self, iput, key, size):
  371.         output = [0] * 16
  372.         # the number of rounds
  373.         nbrRounds = 0
  374.         # the 128 bit block to decode
  375.         block = [0] * 16
  376.         # set the number of rounds
  377.         if size == self.keySize["SIZE_128"]: nbrRounds = 10
  378.         elif size == self.keySize["SIZE_192"]: nbrRounds = 12
  379.         elif size == self.keySize["SIZE_256"]: nbrRounds = 14
  380.         else: return None
  381.  
  382.         # the expanded keySize
  383.         expandedKeySize = 16*(nbrRounds+1)
  384.  
  385.         # Set the block values, for the block:
  386.         # a0,0 a0,1 a0,2 a0,3
  387.         # a1,0 a1,1 a1,2 a1,3
  388.         # a2,0 a2,1 a2,2 a2,3
  389.         # a3,0 a3,1 a3,2 a3,3
  390.         # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
  391.  
  392.         # iterate over the columns
  393.         for i in range(4):
  394.             # iterate over the rows
  395.             for j in range(4):
  396.                 block[(i+(j*4))] = iput[(i*4)+j]
  397.         # expand the key into an 176, 208, 240 bytes key
  398.         expandedKey = self.expandKey(key, size, expandedKeySize)
  399.         # decrypt the block using the expandedKey
  400.         block = self.aes_invMain(block, expandedKey, nbrRounds)
  401.         # unmap the block again into the output
  402.         for k in range(4):
  403.             # iterate over the rows
  404.             for l in range(4):
  405.                 output[(k*4)+l] = block[(k+(l*4))]
  406.         return output
  407.  
  408.  
  409. class AESModeOfOperation(object):
  410.  
  411.     aes = AES()
  412.  
  413.     # structure of supported modes of operation
  414.     modeOfOperation = dict(OFB=0, CFB=1, CBC=2)
  415.  
  416.     # converts a 16 character string into a number array
  417.     def convertString(self, string, start, end, mode):
  418.         if end - start > 16: end = start + 16
  419.         if mode == self.modeOfOperation["CBC"]: ar = [0] * 16
  420.         else: ar = []
  421.  
  422.         i = start
  423.         j = 0
  424.         while len(ar) < end - start:
  425.             ar.append(0)
  426.         while i < end:
  427.             ar[j] = ord(string[i])
  428.             j += 1
  429.             i += 1
  430.         return ar
  431.  
  432.     # Mode of Operation Encryption
  433.     # stringIn - Input String
  434.     # mode - mode of type modeOfOperation
  435.     # hexKey - a hex key of the bit length size
  436.     # size - the bit length of the key
  437.     # hexIV - the 128 bit hex Initilization Vector
  438.     def encrypt(self, stringIn, mode, key, size, IV):
  439.         if len(key) % size:
  440.             return None
  441.         if len(IV) % 16:
  442.             return None
  443.         # the AES input/output
  444.         plaintext = []
  445.         iput = [0] * 16
  446.         output = []
  447.         ciphertext = [0] * 16
  448.         # the output cipher string
  449.         cipherOut = []
  450.         # char firstRound
  451.         firstRound = True
  452.         if stringIn != None:
  453.             for j in range(int(math.ceil(float(len(stringIn))/16))):
  454.                 start = j*16
  455.                 end = j*16+16
  456.                 if  end > len(stringIn):
  457.                     end = len(stringIn)
  458.                 plaintext = self.convertString(stringIn, start, end, mode)
  459.                 # print 'PT@%s:%s' % (j, plaintext)
  460.                 if mode == self.modeOfOperation["CFB"]:
  461.                     if firstRound:
  462.                         output = self.aes.encrypt(IV, key, size)
  463.                         firstRound = False
  464.                     else:
  465.                         output = self.aes.encrypt(iput, key, size)
  466.                     for i in range(16):
  467.                         if len(plaintext)-1 < i:
  468.                             ciphertext[i] = 0 ^ output[i]
  469.                         elif len(output)-1 < i:
  470.                             ciphertext[i] = plaintext[i] ^ 0
  471.                         elif len(plaintext)-1 < i and len(output) < i:
  472.                             ciphertext[i] = 0 ^ 0
  473.                         else:
  474.                             ciphertext[i] = plaintext[i] ^ output[i]
  475.                     for k in range(end-start):
  476.                         cipherOut.append(ciphertext[k])
  477.                     iput = ciphertext
  478.                 elif mode == self.modeOfOperation["OFB"]:
  479.                     if firstRound:
  480.                         output = self.aes.encrypt(IV, key, size)
  481.                         firstRound = False
  482.                     else:
  483.                         output = self.aes.encrypt(iput, key, size)
  484.                     for i in range(16):
  485.                         if len(plaintext)-1 < i:
  486.                             ciphertext[i] = 0 ^ output[i]
  487.                         elif len(output)-1 < i:
  488.                             ciphertext[i] = plaintext[i] ^ 0
  489.                         elif len(plaintext)-1 < i and len(output) < i:
  490.                             ciphertext[i] = 0 ^ 0
  491.                         else:
  492.                             ciphertext[i] = plaintext[i] ^ output[i]
  493.                     for k in range(end-start):
  494.                         cipherOut.append(ciphertext[k])
  495.                     iput = output
  496.                 elif mode == self.modeOfOperation["CBC"]:
  497.                     for i in range(16):
  498.                         if firstRound:
  499.                             iput[i] =  plaintext[i] ^ IV[i]
  500.                         else:
  501.                             iput[i] =  plaintext[i] ^ ciphertext[i]
  502.                     # print 'IP@%s:%s' % (j, iput)
  503.                     firstRound = False
  504.                     ciphertext = self.aes.encrypt(iput, key, size)
  505.                     # always 16 bytes because of the padding for CBC
  506.                     for k in range(16):
  507.                         cipherOut.append(ciphertext[k])
  508.         return mode, len(stringIn), cipherOut
  509.  
  510.     # Mode of Operation Decryption
  511.     # cipherIn - Encrypted String
  512.     # originalsize - The unencrypted string length - required for CBC
  513.     # mode - mode of type modeOfOperation
  514.     # key - a number array of the bit length size
  515.     # size - the bit length of the key
  516.     # IV - the 128 bit number array Initilization Vector
  517.     def decrypt(self, cipherIn, originalsize, mode, key, size, IV):
  518.         # cipherIn = unescCtrlChars(cipherIn)
  519.         if len(key) % size:
  520.             return None
  521.         if len(IV) % 16:
  522.             return None
  523.         # the AES input/output
  524.         ciphertext = []
  525.         iput = []
  526.         output = []
  527.         plaintext = [0] * 16
  528.         # the output plain text string
  529.         stringOut = ''
  530.         # char firstRound
  531.         firstRound = True
  532.         if cipherIn != None:
  533.             for j in range(int(math.ceil(float(len(cipherIn))/16))):
  534.                 start = j*16
  535.                 end = j*16+16
  536.                 if j*16+16 > len(cipherIn):
  537.                     end = len(cipherIn)
  538.                 ciphertext = cipherIn[start:end]
  539.                 if mode == self.modeOfOperation["CFB"]:
  540.                     if firstRound:
  541.                         output = self.aes.encrypt(IV, key, size)
  542.                         firstRound = False
  543.                     else:
  544.                         output = self.aes.encrypt(iput, key, size)
  545.                     for i in range(16):
  546.                         if len(output)-1 < i:
  547.                             plaintext[i] = 0 ^ ciphertext[i]
  548.                         elif len(ciphertext)-1 < i:
  549.                             plaintext[i] = output[i] ^ 0
  550.                         elif len(output)-1 < i and len(ciphertext) < i:
  551.                             plaintext[i] = 0 ^ 0
  552.                         else:
  553.                             plaintext[i] = output[i] ^ ciphertext[i]
  554.                     for k in range(end-start):
  555.                         stringOut += chr(plaintext[k])
  556.                     iput = ciphertext
  557.                 elif mode == self.modeOfOperation["OFB"]:
  558.                     if firstRound:
  559.                         output = self.aes.encrypt(IV, key, size)
  560.                         firstRound = False
  561.                     else:
  562.                         output = self.aes.encrypt(iput, key, size)
  563.                     for i in range(16):
  564.                         if len(output)-1 < i:
  565.                             plaintext[i] = 0 ^ ciphertext[i]
  566.                         elif len(ciphertext)-1 < i:
  567.                             plaintext[i] = output[i] ^ 0
  568.                         elif len(output)-1 < i and len(ciphertext) < i:
  569.                             plaintext[i] = 0 ^ 0
  570.                         else:
  571.                             plaintext[i] = output[i] ^ ciphertext[i]
  572.                     for k in range(end-start):
  573.                         stringOut += chr(plaintext[k])
  574.                     iput = output
  575.                 elif mode == self.modeOfOperation["CBC"]:
  576.                     output = self.aes.decrypt(ciphertext, key, size)
  577.                     for i in range(16):
  578.                         if firstRound:
  579.                             plaintext[i] = IV[i] ^ output[i]
  580.                         else:
  581.                             plaintext[i] = iput[i] ^ output[i]
  582.                     firstRound = False
  583.                     if originalsize is not None and originalsize < end:
  584.                         for k in range(originalsize-start):
  585.                             stringOut += chr(plaintext[k])
  586.                     else:
  587.                         for k in range(end-start):
  588.                             stringOut += chr(plaintext[k])
  589.                     iput = ciphertext
  590.         return stringOut
  591.  
  592.  
  593. def encryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
  594.     """encrypt `data` using `key`
  595.  
  596.    `key` should be a string of bytes.
  597.  
  598.    returned cipher is a string of bytes prepended with the initialization
  599.    vector.
  600.  
  601.    """
  602.     key = map(ord, key)
  603.     if mode == AESModeOfOperation.modeOfOperation["CBC"]:
  604.         data = append_PKCS7_padding(data)
  605.     keysize = len(key)
  606.     assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
  607.     # create a new iv using random data
  608.     iv = [ord(i) for i in os.urandom(16)]
  609.     moo = AESModeOfOperation()
  610.     (mode, length, ciph) = moo.encrypt(data, mode, key, keysize, iv)
  611.     # With padding, the original length does not need to be known. It's a bad
  612.     # idea to store the original message length.
  613.     # prepend the iv.
  614.     return ''.join(map(chr, iv)) + ''.join(map(chr, ciph))
  615.  
  616. def decryptData(key, data, mode=AESModeOfOperation.modeOfOperation["CBC"]):
  617.     """decrypt `data` using `key`
  618.  
  619.    `key` should be a string of bytes.
  620.  
  621.    `data` should have the initialization vector prepended as a string of
  622.    ordinal values.
  623.  
  624.    """
  625.  
  626.     key = map(ord, key)
  627.     keysize = len(key)
  628.     assert keysize in AES.keySize.values(), 'invalid key size: %s' % keysize
  629.     # iv is first 16 bytes
  630.     iv = map(ord, data[:16])
  631.     data = map(ord, data[16:])
  632.     moo = AESModeOfOperation()
  633.     decr = moo.decrypt(data, None, mode, key, keysize, iv)
  634.     if mode == AESModeOfOperation.modeOfOperation["CBC"]:
  635.         decr = strip_PKCS7_padding(decr)
  636.     return decr
  637.  
  638. def generateRandomKey(keysize):
  639.     """Generates a key from random data of length `keysize`.
  640.  
  641.    The returned key is a string of bytes.
  642.  
  643.    """
  644.     if keysize not in (16, 24, 32):
  645.         emsg = 'Invalid keysize, %s. Should be one of (16, 24, 32).'
  646.         raise ValueError, emsg % keysize
  647.     return os.urandom(keysize)
  648.  
  649.  
  650. ### NOTE: If using the BASE64-encoded variety, with b"Salted__" prefix,
  651. # call it like so:
  652. # data = base64.b64decode(encrypted)
  653. # decryptCryptoJS(data[16:], passphrase, data[8:16])
  654. #
  655. # Otherwise, call as normal.
  656. def decryptCryptoJS(data, passphrase, salt):
  657.     # Code from 'bytes_to_key()' from: https://stackoverflow.com/a/36780727
  658.     temp = passphrase + salt
  659.     key = md5(temp).digest()
  660.     key_iv = key
  661.     while len(key_iv) < 48:
  662.         key = md5(key + temp).digest()
  663.         key_iv += key
  664.     key = key_iv[:32]
  665.     iv = key_iv[32:48]
  666.  
  667.     result = AESModeOfOperation().decrypt(
  668.         map(ord, data), None, AESModeOfOperation.modeOfOperation["CBC"], map(ord, key), len(key), map(ord, iv)
  669.     )
  670.     try:
  671.         return strip_PKCS7_padding(result)
  672.     except:
  673.         return result
  674.  
  675.  
  676. #def pad(data):
  677. #    length = BLOCK_SIZE - (len(data) % BLOCK_SIZE)
  678. #    return (data + (chr(length)*length)).encode()
  679. #
  680. #
  681. #def unpad(data):
  682. #    return data[:-(data[-1] if type(data[-1]) == int else ord(data[-1]))]
  683. #
  684. #
  685. #def bytes_to_key(data, salt, output=48):
  686. #    # extended from https://gist.github.com/gsakkis/4546068
  687. #    assert len(salt) == 8, len(salt)
  688. #    data += salt
  689. #    key = md5(data).digest()
  690. #    final_key = key
  691. #    while len(final_key) < output:
  692. #        key = md5(key + data).digest()
  693. #        final_key += key
  694. #    return final_key[:output]
  695. #
  696. #def decrypt(encrypted, passphrase):
  697. #    encrypted = base64.b64decode(encrypted)
  698. #    assert encrypted[0:8] == b"Salted__"
  699. #    salt = encrypted[8:16]
  700. #    key_iv = bytes_to_key(passphrase, salt, 32+16)
  701. #    key = key_iv[:32]
  702. #    iv = key_iv[32:]
  703. #    aes = AES.new(key, AES.MODE_CBC, iv)
  704. #    return unpad(aes.decrypt(encrypted[16:]))
  705.  
  706.  
  707. #if __name__ == "__main__":
  708. #    moo = AESModeOfOperation()
  709. #    cleartext = "This is a test!"
  710. #    cypherkey = [143,194,34,208,145,203,230,143,177,246,97,206,145,92,255,84]
  711. #    iv = [103,35,148,239,76,213,47,118,255,222,123,176,106,134,98,92]
  712. #    mode, orig_len, ciph = moo.encrypt(cleartext, moo.modeOfOperation["CBC"],
  713. #            cypherkey, moo.aes.keySize["SIZE_128"], iv)
  714. #    print 'm=%s, ol=%s (%s), ciph=%s' % (mode, orig_len, len(cleartext), ciph)
  715. #    decr = moo.decrypt(ciph, orig_len, mode, cypherkey,
  716. #            moo.aes.keySize["SIZE_128"], iv)
  717. #    print decr
  718.  
  719.  
  720. # =============================================================================
  721. # Blowfish encryption Scheme
  722. # Taken from here: https://gist.github.com/eigenein/a56ce4d572484a582e14
  723.  
  724. class Blowfish:
  725.     # This class implements the encryption and decryption
  726.     # functionality of the Blowfish cipher.
  727.     # Public functions:
  728.         # def __init__ (self, key)
  729.             # Creates an instance of blowfish using 'key'
  730.             # as the encryption key. Key is a string of
  731.             # length ranging from 8 to 56 bytes (64 to 448
  732.             # bits). Once the instance of the object is
  733.             # created, the key is no longer necessary.
  734.         # def encrypt (self, data):
  735.             # Encrypt an 8 byte (64-bit) block of text
  736.             # where 'data' is an 8 byte string. Returns an
  737.             # 8-byte encrypted string.
  738.         # def decrypt (self, data):
  739.             # Decrypt an 8 byte (64-bit) encrypted block
  740.             # of text, where 'data' is the 8 byte encrypted
  741.             # string. Returns an 8-byte string of plaintext.
  742.         # def cipher (self, xl, xr, direction):
  743.             # Encrypts a 64-bit block of data where xl is
  744.             # the upper 32-bits and xr is the lower 32-bits.
  745.             # 'direction' is the direction to apply the
  746.             # cipher, either ENCRYPT or DECRYPT constants.
  747.             # returns a tuple of either encrypted or decrypted
  748.             # data of the left half and right half of the
  749.             # 64-bit block.
  750.     # Private members:
  751.         # def __round_func (self, xl)
  752.             # Performs an obscuring function on the 32-bit
  753.             # block of data 'xl', which is the left half of
  754.             # the 64-bit block of data. Returns the 32-bit
  755.             # result as a long integer.
  756.  
  757.     # Cipher directions
  758.     ENCRYPT = 0
  759.     DECRYPT = 1
  760.  
  761.     # For the __round_func
  762.     modulus = int (2) ** 32
  763.  
  764.     def __init__ (self, key):
  765.  
  766.         if not key or len (key) < 8 or len (key) > 56:
  767.             raise RuntimeError("Attempted to initialize Blowfish cipher with key of invalid length: %s" %len (key))
  768.  
  769.         # Key needs to be a list of ints.
  770. # Cycle through the p-boxes and round-robin XOR the
  771.         # key with the p-boxes
  772.         key_len = len (key)
  773.         index = 0
  774.         for i in range (len (self.p_boxes)):
  775.             val = ((key[index % key_len]) << 24) + \
  776.                   ((key[(index + 1) % key_len]) << 16) + \
  777.                   ((key[(index + 2) % key_len]) << 8) + \
  778.                    (key[(index + 3) % key_len])
  779.             self.p_boxes[i] = self.p_boxes[i] ^ val
  780.             index = index + 4
  781.  
  782.         # For the chaining process
  783.         l, r = 0, 0
  784.  
  785.         # Begin chain replacing the p-boxes
  786.         for i in range (0, len (self.p_boxes), 2):
  787.             l, r = self.cipher (l, r, self.ENCRYPT)
  788.             self.p_boxes[i] = l
  789.             self.p_boxes[i + 1] = r
  790.  
  791.         # Chain replace the s-boxes
  792.         for i in range (len (self.s_boxes)):
  793.             for j in range (0, len (self.s_boxes[i]), 2):
  794.                 l, r = self.cipher (l, r, self.ENCRYPT)
  795.                 self.s_boxes[i][j] = l
  796.                 self.s_boxes[i][j + 1] = r
  797.  
  798.     def cipher (self, xl, xr, direction):
  799.  
  800.         if direction == self.ENCRYPT:
  801.             for i in range (16):
  802.                 xl = xl ^ self.p_boxes[i]
  803.                 xr = self.__round_func (xl) ^ xr
  804.                 xl, xr = xr, xl
  805.             xl, xr = xr, xl
  806.             xr = xr ^ self.p_boxes[16]
  807.             xl = xl ^ self.p_boxes[17]
  808.         else:
  809.             for i in range (17, 1, -1):
  810.                 xl = xl ^ self.p_boxes[i]
  811.                 xr = self.__round_func (xl) ^ xr
  812.                 xl, xr = xr, xl
  813.             xl, xr = xr, xl
  814.             xr = xr ^ self.p_boxes[1]
  815.             xl = xl ^ self.p_boxes[0]
  816.         return xl, xr
  817.  
  818.     def __round_func (self, xl):
  819.         a = (xl & 0xFF000000) >> 24
  820.         b = (xl & 0x00FF0000) >> 16
  821.         c = (xl & 0x0000FF00) >> 8
  822.         d = xl & 0x000000FF
  823.  
  824.         # Perform all ops as longs then and out the last 32-bits to
  825.         # obtain the integer
  826.         f = (int (self.s_boxes[0][a]) + int (self.s_boxes[1][b])) % self.modulus
  827.         f = f ^ int (self.s_boxes[2][c])
  828.         f = f + int (self.s_boxes[3][d])
  829.         f = (f % self.modulus) & 0xFFFFFFFF
  830.  
  831.         return f
  832.  
  833.     # def encrypt (self, data):
  834.  
  835.         # if not len (data) == 8:
  836.             # raise RuntimeError("Attempted to encrypt data of invalid block length: %s" %len (data))
  837.  
  838.         # Use big endianess since that's what everyone else uses
  839.         # xl = ord (data[3]) | (ord (data[2]) << 8) | (ord (data[1]) << 16) | (ord (data[0]) << 24)
  840.         # xr = ord (data[7]) | (ord (data[6]) << 8) | (ord (data[5]) << 16) | (ord (data[4]) << 24)
  841.  
  842.         # cl, cr = self.cipher (xl, xr, self.ENCRYPT)
  843.         # chars = ''.join ([
  844.             # chr ((cl >> 24) & 0xFF), chr ((cl >> 16) & 0xFF), chr ((cl >> 8) & 0xFF), chr (cl & 0xFF),
  845.             # chr ((cr >> 24) & 0xFF), chr ((cr >> 16) & 0xFF), chr ((cr >> 8) & 0xFF), chr (cr & 0xFF)
  846.         # ])
  847.         # return chars
  848.  
  849.     # def decrypt (self, data):
  850.  
  851.         # if not len (data) == 8:
  852.             # raise RuntimeError("Attempted to encrypt data of invalid block length: %s" %len (data))
  853.  
  854.         # Use big endianess since that's what everyone else uses
  855.         # cl = (data[3]) | ((data[2]) << 8) | ((data[1]) << 16) | ((data[0]) << 24)
  856.         # cr = (data[7]) | ((data[6]) << 8) | ((data[5]) << 16) | ((data[4]) << 24)
  857.  
  858.         # xl, xr = self.cipher (cl, cr, self.DECRYPT)
  859.         # chars = bytes ([
  860.             # ((xl >> 24) & 0xFF), ((xl >> 16) & 0xFF), ((xl >> 8) & 0xFF), (xl & 0xFF),
  861.             # ((xr >> 24) & 0xFF), ((xr >> 16) & 0xFF), ((xr >> 8) & 0xFF), (xr & 0xFF)
  862.         # ])
  863.         # return chars
  864.  
  865.     # ---------------------------------------------------------------------------------
  866.     # Blowfish decryption. How to use:
  867.     #
  868.     # stringKey = 'mySpecialKey123'
  869.     # b = Blowfish(stringKey)
  870.     # result = b.decrypt(stringData)
  871.     #
  872.     def decrypt (self, stringData):
  873.         data = tuple(map(ord, stringData))
  874.         result = [None] * len(data)
  875.  
  876.         if (len(data) % 8): # Data needs to be divisible by 8.
  877.             raise Exception('Blowfish data must be divisible by 8 (data length: %i)' % len(data))
  878.  
  879.         for index in range(0, len(data), 8):
  880.             temp = data[index:index+8]
  881.  
  882.             # Use big endianess since that's what everyone else uses
  883.             cl = (temp[3]) | ((temp[2]) << 8) | ((temp[1]) << 16) | ((temp[0]) << 24)
  884.             cr = (temp[7]) | ((temp[6]) << 8) | ((temp[5]) << 16) | ((temp[4]) << 24)
  885.  
  886.             xl, xr = self.cipher (cl, cr, self.DECRYPT)
  887.             result[index:index+8] = (
  888.                 ((xl >> 24) & 0xFF), ((xl >> 16) & 0xFF), ((xl >> 8) & 0xFF), (xl & 0xFF),
  889.                 ((xr >> 24) & 0xFF), ((xr >> 16) & 0xFF), ((xr >> 8) & 0xFF), (xr & 0xFF)
  890.             )
  891.         return ''.join(map(chr, result))
  892.  
Add Comment
Please, Sign In to add comment