python对字符串做加密解密处理,大致有三种方法:base64,win32com.client和自定义加密解密算法,最安全可靠的方式,建议是自写加密解密算法。
1,使用base64: 代码示例:
#!/bin/python
#edit: www.#
#
import base64
s1 = base64.encodestring('hello world')
s2 = base64.decodestring(s1)
print s1,s2
# aGVsbG8gd29ybGQ=\n
# hello world
注: 此方法简单便不安全,当别人拿到你的密文时,即可解密得到明文;
不过可以把密文字符串进行处理,如字母转换成数字或是特殊字符等,自己解密的时候在替换回去在进行base64.decodestring,要安全很多。
2,使用win32com.client 代码示例:
#!/bin/python
#
import win32com.client
def encrypt(key,content): # key:密钥,content:明文
EncryptedData = win32com.client.Dispatch('CAPICOM.EncryptedData')
EncryptedData.Algorithm.KeyLength = 5
EncryptedData.Algorithm.Name = 2
EncryptedData.SetSecret(key)