python各種加解密方法

我爱你的發表於2024-06-07

# -*- encoding: utf-8 -*-

from hashlib import md5
import base64


# MD5加密
obj = md5()
str = "你是個小可愛"
obj.update(str.encode("utf-8"))
# obj.update("wusir".encode('utf-8')) # 可以新增多個被加密的內容

bs = obj.hexdigest()
print("md5加密結果:{}".format(bs))

# base64加密
base_str = "我馬上要進行base64加密了"
bs64 = base64.b64encode(str.encode("utf-8"))
print("bs64加密結果:{}".format(bs64))

# base64解密
s = "5L2g5piv5Liq5bCP5Y+v54ix"
bs64_jie = base64.b64decode(s.encode())
print("bs64解密結果:{}".format(bs64_jie.decode("utf-8")))

# MD5加密後再進行base64加密
obj = md5()
obj.update(str.encode("utf-8"))
bs = obj.hexdigest()
bs64 = base64.b64encode(bs.encode("utf-8"))
print("MD5加密後再進行base64加密結果:{}".format(bs64))

# url編碼
import urllib.parse

# s = 'a'
s = ' 123'
ret = urllib.parse.quote(s)
print(ret)
s = urllib.parse.unquote(ret)
print(s)

params = {'name': '張三', 'age': 20, 'address': '北京市海淀區'}
query_string = urllib.parse.urlencode(params)
print(query_string)

query_string = 'name=%E5%BC%A0%E4%B8%89&age=20&address=%E5%8C%97%E4%BA%AC%E5%B8%82%E6%B5%B7%E6%B7%80%E5%8C%BA'
params = urllib.parse.parse_qs(query_string)
print(params, type(params))

# 對稱加密(AES與DES) pip install pycryptodome / pip install Crypto
# #### AES之ECB模式
# ECB加密案例:
from Crypto.Cipher import AES
import base64

key = '1234567890123456'.encode() # 秘鑰
# 秘鑰:必須是16位位元組或者24位位元組或者32位位元組

text = 'alex is dsb!!!!!'
# text = 'alex is dsb' # 需要加密的內容
# while len(text.encode('utf-8')) % 16 != 0: # 如果text不足16位的倍數就用空格補足為16位
# text += '\0'
text = text.encode()
print("完整text:", text)

aes = AES.new(key, AES.MODE_ECB) # 建立一個aes物件

en_text = aes.encrypt(text) # 加密明文
print("加密資料:::", en_text)

en_text = base64.b64encode(en_text).decode() # 將返回的位元組型資料轉進行base64編碼
print(en_text) # rRPMWCaOBYahYnKUJzq65A==

# ECB解密:
from Crypto.Cipher import AES
import base64

key = '1234567890123456'.encode() # 秘鑰
# 秘鑰:必須是16位位元組或者24位位元組或者32位位元組(因為python3的字串是unicode編碼,需要 encode才可以轉換成位元組型資料)
model = AES.MODE_ECB # 定義模式
aes = AES.new(key, model) # 建立一個aes物件

text = '3NeIhJsnhzy3Ojoquz+9eg=='.encode() # 需要解密的文字
ecrypted_base64 = base64.b64decode(text) # base64解碼成位元組流
str = aes.decrypt(ecrypted_base64).decode() # 解密

print(str)

#### AES之CBC模式

#CBC加密案例:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad,unpad
import base64

key = '1234567890123456'.encode() # 秘鑰
# 秘鑰:必須是16位位元組或者24位位元組或者32位位元組
text = 'hello rain,you are very good'.encode()
# text = 'alex is dsb' # 需要加密的內容
# 第一種方法,補足16位
# while len(text.encode('utf-8')) % 16 != 0: # 如果text不足16位的倍數就用空格補足為16位
# text += '\0'

# 第二種方法,補足16位
text = pad(text, 16)
print("完整text:", text)

iv = b'abcdabcdabcdabcd' #偏移量--必須16位元組

aes = AES.new(key, AES.MODE_CBC,iv) # 建立一個aes物件

en_text = aes.encrypt(text) # 加密明文
print("aes加密資料:::", en_text)

en_text = base64.b64encode(en_text).decode() # 將返回的位元組型資料轉進行base64編碼
print(en_text) # rRPMWCaOBYahYnKUJzq65A==

#CBC解密:
from Crypto.Cipher import AES
import base64

key = '1234567890123456'.encode() # 秘鑰
# 秘鑰:必須是16位位元組或者24位位元組或者32位位元組(因為python3的字串是unicode編碼,需要 encode才可以轉換成位元組型資料)
model = AES.MODE_CBC # 定義模式
iv = b'abcdabcdabcdabcd'
aes = AES.new(key, model, iv) # 建立一個aes物件

text = 'C9mcRBT2K5Z60j55/oD+Qyn0k+4y2fjtG5un4YWFb/c='.encode() # 需要解密的文字
ecrypted_base64 = base64.b64decode(text) # base64解碼成位元組流

str = aes.decrypt(ecrypted_base64)
str = unpad(str, 16).decode() # 解密
# str = aes.decrypt(ecrypted_base64).decode() # 解密
print("aes解密資料:::{}".format(str))

# 非對稱加密(RSA)

# 1.建立公鑰和私鑰
from Crypto.PublicKey import RSA

# 生成秘鑰
rsakey = RSA.generate(1024)
with open("rsa.public.pem", mode="wb") as f:
f.write(rsakey.publickey().exportKey())

with open("rsa.private.pem", mode="wb") as f:
f.write(rsakey.exportKey())

# 加密
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64


data = "我喜歡你"
with open("rsa.public.pem", mode="r") as f:
pk = f.read()
rsa_pk = RSA.importKey(pk)
rsa = PKCS1_v1_5.new(rsa_pk)

result = rsa.encrypt(data.encode("utf-8"))
# 處理成b64方便傳輸
b64_result = base64.b64encode(result).decode("utf-8")
print("RAS加密:" ,b64_result)

# 解密
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64

data = "BkiKG8jzVGzbWOl4m8NXJEYglgtxhOB05MGmap8JSP97GzoewPBmDTs7c5iACUof3k/uJf0H88GygajVgBvkcbckJp7oO+Qj6VSUQYTOHhKN/VG2a8v+WzL34EO/S7BYoj2oOxIDAr8wDLxYxjBeXq/Be6Q1yBbnZcKaMkifhP8="

with open("rsa.private.pem", mode="r") as f:
prikey = f.read()
rsa_pk = RSA.importKey(prikey)
rsa = PKCS1_v1_5.new(rsa_pk)
result = rsa.decrypt(base64.b64decode(data), None)
print("rsa解密資料:::", result.decode("utf-8"))

相關文章