Python解密字符串的实现

2530阅读 0评论2015-03-10 swenker
分类:Python/Ruby

env: python 6.6
install pip install PyCrypto==2.3


点击(此处)折叠或打开

  1. from Crypto.Cipher import AES

  2. import base64
  3. import urllib
  4. import binascii


  5. """
  6.   reference : https://www.dlitz.net/software/pycrypto/api/current/
  7. """
  8. padding = "ThisisPadding"
  9. CHARSET_UTF8="UTF8"
  10. key=b"abcdefghijklmnop"

  11. originalUrl = ""
  12. originalUrl = ""*3+"123"

  13. def encrypt(msg):

  14.     #base64_encoded = base64.encodestring(encoded_url) generate multiple lines

  15.     EncodeAES = lambda c,e:c.encrypt(e)

  16.     #AES key must be either 16, 24, or 32 bytes long
  17.     cipher = AES.new(key)

  18.     #The string here must be multiple 16 length
  19.     encrypted_msg = EncodeAES(cipher,msg+padding)

  20.     base64_encoded = base64.b64encode(encrypted_msg)

  21.     encoded = urllib.quote(base64_encoded).encode(CHARSET_UTF8)
  22.     return encoded



  23. def decrypt(msg):

  24.     print "msg:%d" % len(msg)
  25.     decoded_url = urllib.unquote(msg).decode(CHARSET_UTF8)

  26.     print "durl:%d" %len(decoded_url)

  27.     base64_decoded = base64.decodestring(decoded_url)

  28.     print "b64:%d" %len(base64_decoded)

  29.     DecodeAES = lambda c, e: c.decrypt(e).rstrip(padding)

  30.     cipher = AES.new(key)

  31.     decoded = DecodeAES(cipher, base64_decoded)

  32.     print decoded

  33. enmsg=encrypt(originalUrl)

  34. print enmsg

  35. decrypt(enmsg)

上一篇:Install Mp3 Player On centos6
下一篇:Mysql install issues