fork download
  1. #!/usr/bin/env python
  2.  
  3. from Crypto.Cipher import AES
  4. import base64
  5. import os
  6.  
  7. # the block size for the cipher object; must be 16, 24, or 32 for AES
  8. BLOCK_SIZE = 32
  9.  
  10. # the character used for padding--with a block cipher such as AES, the value
  11. # you encrypt must be a multiple of BLOCK_SIZE in length. This character is
  12. # used to ensure that your value is always a multiple of BLOCK_SIZE
  13. PADDING = '{'
  14.  
  15. # one-liner to sufficiently pad the text to be encrypted
  16. pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING
  17.  
  18. # one-liners to encrypt/encode and decrypt/decode a string
  19. # encrypt with AES, encode with base64
  20. EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
  21. DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)
  22.  
  23. # generate a random secret key
  24. secret = os.urandom(BLOCK_SIZE)
  25.  
  26. # create a cipher object using the random secret
  27. cipher = AES.new(secret)
  28.  
  29. # encode a string
  30. encoded = EncodeAES(cipher, 'password')
  31. print 'Encrypted string:', encoded
  32.  
  33. # decode the encoded string
  34. decoded = DecodeAES(cipher, encoded)
  35. print 'Decrypted string:', decoded
  36.  
  37. # your code goes here
Success #stdin #stdout 0.02s 7628KB
stdin
Standard input is empty
stdout
Encrypted string: cYqvtu+v/PTiexfvWvJZ1bnCzhH29Y1iza0GI0Hq0wQ=
Decrypted string: password