Advertisement
Transfusion

AES Sample in Python

Dec 31st, 2012
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. from Crypto.Cipher import AES
  2. import base64
  3. import os
  4.  
  5. # the block size for the cipher object; must be 16, 24, or 32 for AES
  6. BLOCK_SIZE = 32
  7.  
  8. # the character used for padding--with a block cipher such as AES, the value
  9. # you encrypt must be a multiple of BLOCK_SIZE in length.  This character is
  10. # used to ensure that your value is always a multiple of BLOCK_SIZE
  11. PADDING = '{'
  12.  
  13. # one-liner to sufficiently pad the text to be encrypted
  14. pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
  15.  
  16. # one-liners to encrypt/encode and decrypt/decode a string
  17. # encrypt with AES, encode with base64
  18. EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
  19. DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
  20.  
  21. # generate a random secret key
  22. secret = os.urandom(BLOCK_SIZE)
  23.  
  24. # create a cipher object using the random secret
  25. cipher = AES.new(secret)
  26.  
  27. # encode a string
  28. encoded = EncodeAES(cipher, 'Encryption is the free of mind, i safe[23:12:36] *IdleBot* You found a level 7 set of leggings! Your current set of leggings is only level 4, so it seems Luck is with you!')
  29. print 'Encrypted string:', encoded
  30.  
  31. # decode the encoded string
  32. decoded = DecodeAES(cipher, encoded)
  33. print 'Decrypted string:', decoded
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement