Advertisement
fransafu

AES Cifrado

Aug 28th, 2015
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1. from Crypto.Cipher import AES
  2. #base64 is used for encoding. dont confuse encoding with encryption#
  3. #encryption is used for disguising data
  4. #encoding is used for putting data in a specific format
  5. import base64
  6. # os is for urandom, which is an accepted producer of randomness that
  7. # is suitable for cryptology.
  8. import os
  9. def encryption(privateInfo):
  10.     #32 bytes = 256 bits
  11.     #16 = 128 bits
  12.     # the block size for cipher obj, can be 16 24 or 32. 16 matches 128 bit.
  13.     BLOCK_SIZE = 16
  14.     # the character used for padding
  15.     # used to ensure that your value is always a multiple of BLOCK_SIZE
  16.     PADDING = '{'
  17.     # function to pad the functions. Lambda
  18.     # is used for abstraction of functions.
  19.     # basically, its a function, and you define it, followed by the param
  20.     # followed by a colon,
  21.     # ex = lambda x: x+5
  22.     pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
  23.     # encrypt with AES, encode with base64
  24.     EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
  25.     # generate a randomized secret key with urandom
  26.     secret = os.urandom(BLOCK_SIZE)
  27.     secret = bytes(secret)
  28.     #print 'encryption key:',secret
  29.     # creates the cipher obj using the key
  30.     cipher = AES.new(secret)
  31.     # encodes you private info!
  32.     encoded = EncodeAES(cipher, privateInfo)
  33.     #print 'Encrypted string:', encoded
  34.     respuesta = [secret, encoded] # key y mensaje_cifrado
  35.     return respuesta
  36.  
  37.  
  38. def decryption(encryptedString, key):
  39.     PADDING = '{'
  40.     DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
  41.     #Key is FROM the printout of 'secret' in encryption
  42.     #below is the encryption.
  43.     encryption = encryptedString
  44.     #key = ''
  45.     cipher = AES.new(key)
  46.     decoded = DecodeAES(cipher, encryption)
  47.     print decoded
  48.  
  49. def main():
  50.     lista_respuesta = encryption("Hola como estas")
  51.     print lista_respuesta[1]
  52.     print lista_respuesta[0]
  53.     decryption(lista_respuesta[1], lista_respuesta[0])
  54.  
  55. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement