python字符串加密解密的三种方法分享(base64 win32com)

yipeiwu_com5年前Python基础

1. 最简单的方法是用base64:

复制代码 代码如下:

import base64

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

# aGVsbG8gd29ybGQ=\n
# hello world

Note: 这是最简单的方法了,但是不够保险,因为如果别人拿到你的密文,也可以自己解密来得到明文


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



Note: 这种方法也很方便,而且可以设置自己的密钥,比第一种方法更加安全,是加密解密的首选之策!

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

相关文章

对Python中TKinter模块中的Label组件实例详解

对Python中TKinter模块中的Label组件实例详解

Python2.7.4 OS—W7x86 1. 简介 Label用于在指定的窗口中显示文本和图像。最终呈现出的Label是由背景和前景叠加构成的内容。 Label组件定义函数:Label...

Python从list类型、range()序列简单认识类(class)【可迭代】

本文实例讲述了Python从list类型、range()序列简单认识类(class)。分享给大家供大家参考,具体如下: list类型 定义: items = [] 这就定义了一...

python RC4加密操作示例【测试可用】

python RC4加密操作示例【测试可用】

本文实例讲述了python RC4加密操作。分享给大家供大家参考,具体如下: # -*- conding:utf-8 -*- from Crypto.Cipher import AR...

Python中正则表达式的用法总结

正则表达式很神奇啊 # -*- coding:utf-8 -*- import re def print_match_res(res): """打印匹配对象内容""" if...

PyQt5每天必学之滑块控件QSlider

PyQt5每天必学之滑块控件QSlider

QSlider 是一个具有可来回拉动手柄的控件。有时使用滑块比输入数字或使用旋转框更方便。 在我们的例子中,我们将创建一个滑块和一个标签。标签显示图像。滑块将控制标签显示的图像。 #...