本文实例讲述了Python实现对字符串的加密解密方法。分享给大家供大家参考,具体如下:
需求是是要将密码存在数据库里,所以要加密解密是可逆的,在数据库里不要有特殊字符,防止数据库备份和恢复中出错。
安装[code]PyCrypto[/code],可以用AES和DES。我使用DES加解密。加密后将密文转为16进制,在入库。测试代码如下。
; html-script: false ]#!/bin/python
#-*- coding:utf-8 -*-
# Filename:
# Revision:
# Date: 2013-06-07
# Author: simonzhang
# web: www.simonzhang.net
# Email: simon-zzm@163.com
### END INIT INFO
# easy_install PyCrypto
from binascii import b2a_hex, a2b_hex
from Crypto.Cipher import DES
key = '12345678' #长度必须是8位的
text = 'simonzhang.net ' #长度必须是8的倍数,我用空格补的
# 实例化
obj = DES.new(key)
# 加密
cryp = obj.encrypt(text)
pass_hex = b2a_hex(cryp)
print pass_hex
print '=' * 20
# 解密
get_cryp = a2b_hex(pass_hex)
after_text = obj.decrypt(get_cryp)
print after_text
[b]PS:关于加密解密感兴趣的朋友还可以参考本站在线工具:[/b]
[b]MD5在线加密工具:
[/b][url=http://tools.jb51.net/password/CreateMD5Password]http://tools.jb51.net/password/CreateMD5Password[/url]
[b]迅雷、快车、旋风URL加密/解密工具:
[/b][url=http://tools.jb51.net/password/urlrethunder]http://tools.jb51.net/password/urlrethunder[/url]
[b]在线散列/哈希算法加密工具:
[/b][url=http://tools.jb51.net/password/hash_encrypt]http://tools.jb51.net/password/hash_encrypt[/url]
[b]在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
[/b][url=http://tools.jb51.net/password/hash_md5_sha]http://tools.jb51.net/password/hash_md5_sha[/url]
[b]在线sha1/sha224/sha256/sha384/sha512加密工具:
[/b][url=http://tools.jb51.net/password/sha_encode]http://tools.jb51.net/password/sha_encode[/url]
更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/648.htm]Python Socket编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》
希望本文所述对大家Python程序设计有所帮助。