1,python对字符串加密常见的方法:

<pre code_snippet_id="340592" snippet_file_name="blog_20140512_1_2282504" name="code" class="python">1. 最简单的方法是用base64:     

import base64

s1 = base64.encodestring('hello world')
s2 = base64.decodestring(s1)
print s1,s2

# aGVsbG8gd29ybGQ=n
# hello world

注: 这是最简单的方法了,但是不够保险,因为如果别人拿到你的密文,也可以自己解密来得到明文;不过可以把密文字符串进行处理,如字母转换成数字或是特殊字符等,自己解密的时候在替换回去在进行base64.decodestring,这样要安全很多。




2. 第二种方法是使用win32com.client

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)
EncryptedData.Content = content
return EncryptedData.Encrypt()

def decrypt(key,content): # key:密钥,content:密文
EncryptedData = win32com.client.Dispatch('CAPICOM.EncryptedData')
EncryptedData.Algorithm.KeyLength = 5
EncryptedData.Algorithm.Name = 2
EncryptedData.SetSecret(key)
EncryptedData.Decrypt(content)
str = EncryptedData.Content
return str

s1 = encrypt('lovebread', 'hello world')
s2 = decrypt('lovebread', s1)
print s1,s2

# MGEGCSsGAQQBgjdYA6BUMFIGCisGAQQBgjdYAwGgRDBCAgMCAAECAmYBAgFABAgq
# GpllWj9cswQQh/fnBUZ6ijwKDTH9DLZmBgQYmfaZ3VFyS/lq391oDtjlcRFGnXpx
# lG7o
# hello world


注: 这种方法也很方便,而且可以设置自己的密钥,比第一种方法更加安全,如果对安全级别要求不太高的话这种方法是加密解密的首选之策!



3. 还有就是自己写加密解密算法,比如:

def encrypt(key, s):
b = bytearray(str(s).encode("gbk"))
n = len(b) # 求出 b 的字节数
c = bytearray(n*2)
j = 0
for i in range(0, n):
b1 = b[i]
b2 = b1 ^ key # b1 = b2^ key
c1 = b2 % 16
c2 = b2 // 16 # b2 = c2*16 + c1
c1 = c1 + 65
c2 = c2 + 65 # c1,c2都是0~15之间的数,加上65就变成了A-P 的字符的编码
c[j] = c1
c[j+1] = c2
j = j+2
return c.decode("gbk")

def decrypt(key, s):
c = bytearray(str(s).encode("gbk"))
n = len(c) # 计算 b 的字节数
if n % 2 != 0 :
return ""
n = n // 2
b = bytearray(n)
j = 0
for i in range(0, n):
c1 = c[j]
c2 = c[j+1]
j = j+2
c1 = c1 - 65
c2 = c2 - 65
b2 = c2*16 + c1
b1 = b2^ key
b[i]= b1
try:
return b.decode("gbk")
except:
return "failed"

key = 15
s1 = encrypt(key, 'hello world')
s2 = decrypt(key, s1)
print s1,'n',s2

# HGKGDGDGAGPCIHAGNHDGLG
# hello world


注: 这是网上抄来的一个简单的例子,大家可以自定义自己算法进行加密解密;还有许许多多复杂的加密算法,大家可以自行查阅密码学的相关算法。

4.对于python来说,也可以把python源码文件编译成pyc二进制格式的文件,这样别人就看不到你的源码,也算是一种加密方法吧,方法如下:
执行命令python -m py_compile create_slave.py 可以直接生成一个create_slave.pyc文件,然后可以用create_slave.pyc来替换create_slave.py作为脚本来执行。


 

 

更多相关文章

  1. python魔法方法、构造函数、序列与映射、迭代器、生成器
  2. Python 字典 pop() 方法
  3. 对照java和spring理解python中单例模式的装饰器方法
  4. Python下numpy不成功的解决办法(wheel方法安装,试用其他包)
  5. 关于python中的类方法(classmethod)和静态方法(staticmethod)
  6. python中的类与方法
  7. 如何为Google Cloud Endpoints方法生成pydoc文档?
  8. python笔记7:接口实现方法
  9. 用于搜索和替换大字符串的最快Python方法

随机推荐

  1. 为什么有的程序在64位机上跑反而比32位机
  2. Android Animation --- 无限360度旋转
  3. 给自己的项目做极光推送的步骤
  4. 如何为后台工作创建绑定服务(Xamarin)
  5. Android开发 处理拍照完成后的照片角度
  6. 关于android中sharedpreferences数据不更
  7. android面试题总结
  8. Android开发-直播视讯(3)-创建一个Ubuntu
  9. findViewById()返回布局XML中自定义组件
  10. 基于Android6.0的RIL底层模块分析