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

首頁(yè) > 編程 > Python > 正文

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

2019-11-25 18:33:42
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

1. 最簡(jiǎn)單的方法是用base64:

復(fù)制代碼 代碼如下:

import base64

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

# aGVsbG8gd29ybGQ=/n
# hello world

Note: 這是最簡(jiǎn)單的方法了,但是不夠保險(xiǎn),因?yàn)槿绻麆e人拿到你的密文,也可以自己解密來(lái)得到明文


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

復(fù)制代碼 代碼如下:

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: 這種方法也很方便,而且可以設(shè)置自己的密鑰,比第一種方法更加安全,是加密解密的首選之策!

3. 還有就是自己寫(xiě)加密解密算法,比如:

復(fù)制代碼 代碼如下:

def encrypt(key, s):
    b = bytearray(str(s).encode("gbk"))
    n = len(b) # 求出 b 的字節(jié)數(shù)
    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之間的數(shù),加上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) # 計(jì)算 b 的字節(jié)數(shù)
    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

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 吴桥县| 福鼎市| 玉林市| 陕西省| 汾西县| 虞城县| 韶关市| 化德县| 寿宁县| 肥东县| 启东市| 邮箱| 华蓥市| 易门县| 东兰县| 双牌县| 鹤庆县| 始兴县| 彰化县| 甘肃省| 青神县| 乳山市| 昌都县| 嘉祥县| 云阳县| 同德县| 虞城县| 琼海市| 彩票| 榆树市| 睢宁县| 齐河县| 嘉善县| 泰兴市| 于都县| 专栏| 枣庄市| 兰西县| 重庆市| 措勤县| 扎兰屯市|