加密的分類
1、單向加密 :MD5、sha系列不可逆
2、對稱加密:AES、DES
3、非對稱加密:RSA、DSA
4、補充演算法:base64
1.md5
import hashlib
m = hashlib.md5()
m.update('helloworld'.encode("utf8"))
print(m.hexdigest())
2.sha
import hashlib
sha1 = hashlib.sha1()
data = 'helloword'
sha1.update(data.encode('utf-8'))
sha1_data = sha1.hexdigest()
print(sha1_data)
3.des加密
# pip3 install pycryptodomex -i https://pypi.douban.com/simple
# DES是一個分組加密演算法,典型的DES以64位為分組對資料加密,加密和解密用的是同一個演算法。它的金鑰長度是56位(因為每個第8 位都用作奇偶校驗),金鑰可以是任意的56位的數,而且可以任意時候改變。
from Cryptodome.Cipher import DES
key = b'88888888'
data = "hello world"
count = 8 - (len(data) % 8)
plaintext = data + count * "="
des = DES.new(key, DES.MODE_ECB)
ciphertext = des.encrypt(plaintext.encode())
print(ciphertext)
plaintext = des.decrypt(ciphertext)
plaintext = plaintext[:(len(plaintext)-count)]
print(plaintext)
4. 非對稱加密演算法-RSA
# 安裝模組
pip3 install rsa -i https://pypi.douban.com/simple
import rsa
# 返回 公鑰加密、私鑰解密
public_key, private_key = rsa.newkeys(1024)
print(public_key)
print(private_key)
# plaintext = b"hello world"
# ciphertext = rsa.encrypt(plaintext, public_key)
# print('公鑰加密後:',ciphertext)
# plaintext = rsa.decrypt(ciphertext, private_key)
# print('私鑰解密:',plaintext)
### 使用私鑰簽名
plaintext = b"hello world"
sign_message = rsa.sign(plaintext, private_key, "MD5")
print('私鑰簽名後:',sign_message)
## 驗證私鑰簽名
plaintext = b"hello world"
# method = rsa.verify(b"hello world", sign_message, public_key)
method = rsa.verify(b"hello world1", sign_message, public_key) # 報錯Verification failed
print(method)
5.base64
import base64
# 編碼
res=base64.b64encode(b'hello world')
print(res)
# 解碼
res=base64.b64decode('aGVsbG8gd29ybGQ=')
print(res)