常用的加密算法说明
- 单向加密(不可解密):md5,sha
- 对称加密(加密与解密秘钥是一样的):AES,DES
- 非对称加密(有公钥和私钥):RSA,DSA
- base64算法:不是加密,它是编码解码
md5加密
import hashlib
data="test_data"
md = hashlib.md5()
md.update(data.encode("utf8"))
print(md.hexdigest())
sha1加密
import hashlib
data="test_data"
sha = hashlib.sha1()
sha.update(data.encode('utf-8'))
print(sha.hexdigest())
des加密
from Cryptodome.Cipher import DES
key = b'12345678'
data = "test_data"
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)
RSA加密
import rsa
public_key, private_key = rsa.newkeys(1024)
print(public_key)
print(private_key)
plaintext = b"test_data"
ciphertext = rsa.encrypt(plaintext, public_key)
print('公钥加密:',ciphertext)
plaintext = rsa.decrypt(ciphertext, private_key)
print('私钥解密:',plaintext)
plaintext = b"test_data"
sign_message = rsa.sign(plaintext, private_key, "MD5")
print('私钥签名后:',sign_message)
plaintext = b"test_data"
method = rsa.verify(b"test_data", sign_message, public_key)
print(method)
base64编码和解码
import base64
res=base64.b64encode(b'test_data1')
print(res)
res=base64.b64decode('dGVzdF9kYXRhMQ==')
print(res)