国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

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

2020-02-23 05:05:06
字體:
來源:轉載
供稿:網友

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 汾西县| 锦屏县| 海口市| 阿合奇县| 滨州市| 义马市| 宿州市| 上林县| 萝北县| 苍梧县| 延庆县| 徐汇区| 高邮市| 樟树市| 威远县| 荃湾区| 留坝县| 玉溪市| 成武县| 安庆市| 牟定县| 定安县| 营口市| 寿阳县| 汤原县| 宜黄县| 江安县| 抚顺县| 胶南市| 新宁县| 合川市| 达州市| 平顶山市| 富民县| 南岸区| 淮滨县| 富蕴县| 乌恰县| 开封市| 安阳县| 浦县|