用python实现各类加密算法
对称加密算法
哈希算法
hash算法是最常见的加密算法,python自带的hashlib库提供各类加密方法,可以简单实现。
import hashlib
myhash = hashlib.sha256() #可以选择自己加密方式
myhash.update('00001'.encode('utf8'))
print(myhash.hexdigest())
加密和解密
使用pyDes库实现简单的加密解密的过程
import pyDes
password = b'\0\0\0\0\0\0\0\0'
data = 'hello word hello larry peng'.encode('utf8') # data需要转换成二进制数
key = pyDes.des(b'DESCRYPT', # 设备加密算法
pyDes.CBC, # 加密模式
password,
pad=None,
padmode=pyDes.PAD_PKCS5) # 加密参数
newdata = key.encrypt(data)
print("加密的结果:", newdata)
print("解密的结果:", key.decrypt(newdata))
AES加密解密
python的Crypto库提供AES加密和解密方法,python3.7+以后的版本适用Cryptodome库,两个库使用方法是一样的
from Cryptodome.Cipher import AES
from binascii import b2a_hex,a2b_hex
class AesCiper():
def __init__(self, key):
self.key = key
self.mode = AES.MODE_CBC # 加密函数,加密文本必须是16的倍数,不足补充0
def encrypt(self, text): # 加密,解密
cryptor = AES.new(self.key, self.mode, self.key)
text = self.pad_text(text)
self.ciphertext = cryptor.encrypt(text)
return b2a_hex(self.ciphertext).decode('ASCII')
def pad_text(self, text, length=16):
text = text.encode('utf8')
add = length - (len(text) % length)
text = text + (b'\0' * add)
return text
def decrypt(self, text):
cryptor = AES.new(self.key, self.mode, self.key)
lasttext = cryptor.decrypt(a2b_hex(text))
return lasttext.rstrip(b'\0').decode('utf8')
aes_jj = AesCiper('heqing12lovecode'.encode('utf8')) # 密码必须是16位的倍数
ctext = aes_jj.encrypt('i like HK jdkajsdjasldkj ljdlakjdlaksj')
print(ctext)
print(aes_jj.decrypt(ctext))
非对称加密
非对称加密会使用公钥和私钥进行对数据的加密解密,举个简单的例子
129 * 13 = 1677
1677 % 1000 = 677
677 * 77 = 52129
52129 % 1000 = 129
从上面的例子可以理解成公钥(1000, 13) 私钥(1000,677)完成了对129的加密和解密
RAS解密解密
import rsa
publicKey, privateKey = rsa.newkeys(1024)
print(publicKey)
print(privateKey)
with open('public.pem', 'w+') as fp:
fp.write(publicKey.save_pkcs1().decode('utf8'))
with open('private.pem', 'w+') as pri_fp:
pri_fp.write(privateKey.save_pkcs1().decode('utf8'))
with open('public.pem', 'r') as fp:
publickey = rsa.PublicKey.load_pkcs1(fp.read().encode('utf8'))
with open('private.pem', 'r') as pri_fp:
privatekey = rsa.PrivateKey.load_pkcs1(pri_fp.read().encode('utf8'))
msg = '我是龙的传人,我是中国人'
crpytor = rsa.encrypt(msg.encode('utf8'), publickey)
print(f"加密之后的结果(二进制):{crpytor}")
new_msg= rsa.decrypt(crpytor, privatekey)
print(f"解密之后的字符串:{new_msg.decode('utf8')}")
sign = rsa.sign(msg.encode('utf8'), privatekey, 'SHA-1')
print(rsa.verify(msg.encode('utf8'), sign, publickey))
print(rsa.verify(f'{msg}'.encode('utf8'), sign, publickey))
消息认证
使用签名sign和verify方法对加密数据进行验证
msg = '我是龙的传人,我是中国人,我爱中国!'
import rsa
publicKey, privateKey = rsa.newkeys(1024)
print(publicKey)
print(privateKey)
with open('public.pem', 'w+') as fp:
fp.write(publicKey.save_pkcs1().decode('utf8'))
with open('private.pem', 'w+') as pri_fp:
pri_fp.write(privateKey.save_pkcs1().decode('utf8'))
with open('public.pem', 'r') as fp:
publickey = rsa.PublicKey.load_pkcs1(fp.read().encode('utf8'))
with open('private.pem', 'r') as pri_fp:
privatekey = rsa.PrivateKey.load_pkcs1(pri_fp.read().encode('utf8'))
sign = rsa.sign(msg.encode('utf8'), privatekey, 'SHA-1')
print(rsa.verify(msg.encode('utf8'), sign, publickey))
PKI体系的非对称加密解密
import base64
from Cryptodome import Random
# from Cryptodome.Hash import SHA
from Cryptodome.Cipher import PKCS1_v1_5 as CPKCS1_v1_5 # PKI体系加密解密标准
from Cryptodome.Hash import SHA
from Cryptodome.Signature import PKCS1_v1_5 as SPKCS1_v1_5 # PKI签名标准
from Cryptodome.PublicKey import RSA
# 随机数
ramdom_make = Random.new().read
# rsa算法实例
rsa = RSA.generate(1024, ramdom_make)
# 生产密钥 master
private_pem = rsa.exportKey()
public_pem = rsa.publickey().exportKey()
with open('master_private.pem', 'wb') as pri_fp:
pri_fp.write(private_pem)
with open('master_public.pem', 'wb') as pub_fp:
pub_fp.write(public_pem)
msg = '我是农民,我是中国人'
with open('master_public.pem', 'rb') as pub_fp:
# pub_fp.read()
rsakey = RSA.import_key(pub_fp.read())
cipher = CPKCS1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(msg.encode('utf8')))
print(cipher_text)
with open('master_private.pem', 'rb') as pri_fp:
# pub_fp.read()
rsakey = RSA.import_key(pri_fp.read())
cipher = CPKCS1_v1_5.new(rsakey)
text = cipher.decrypt(base64.b64decode(cipher_text), ramdom_make)
print(text.decode())
# 签名与验证
message = '我是农民,我是中国人, 我爱中国'
with open('master_private.pem') as pub_fp:
# pub_fp.read()
rsakey = RSA.import_key(pub_fp.read())
signer = SPKCS1_v1_5.new(rsakey)
digest = SHA.new()
digest.update(message.encode('utf8'))
sign = signer.sign(digest)
signature = base64.b64encode(sign)
print(signature)
# cipher = CPKCS1_v1_5.new(rsakey)
# cipher_text = base64.b64encode(cipher.encrypt(msg.encode('utf8')))
# print(cipher_text)
with open('master_public.pem') as pri_fp:
# pub_fp.read()
rsakey = RSA.import_key(pri_fp.read())
cipher = SPKCS1_v1_5.new(rsakey)
digest = SHA.new()
digest.update(message.encode('utf8'))
print(signer.verify(digest, base64.b64decode(signature)))
# text = cipher.decrypt(base64.b64decode(cipher_text), ramdom_make)
# print(text.decode())
openSSL非对称加密
import rsa
import base64
from OpenSSL.crypto import PKey # 处理公钥私钥
from OpenSSL.crypto import TYPE_RSA, FILETYPE_PEM, FILETYPE_ASN1 # 处理加密文件
from OpenSSL.crypto import dump_publickey, dump_privatekey
pk = PKey()
pk.generate_key(TYPE_RSA, 1024)
publickey_file = dump_publickey(FILETYPE_PEM, pk) # 公钥文件
privatekey_file = dump_privatekey(FILETYPE_ASN1, pk) # 私钥文件
publickey = rsa.PublicKey.load_pkcs1_openssl_pem(publickey_file)
privatekey = rsa.PrivateKey.load_pkcs1(privatekey_file, 'DER')
# print(publickey.save_pkcs1())
msg = '我是工人,我是中国人,我爱中国!'
data = rsa.encrypt(msg.encode('utf8'), publickey)
data = base64.b64encode(data)
print(data)
dr_data = rsa.decrypt(base64.b64decode(data), privatekey)
print(dr_data.decode('utf8'))