python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > pycrypto 算法加密

python 中的pycrypto 算法加密

作者:autofelix

这篇文章主要介绍了python 中的pycrypto 算法加密,文章基于python的相关资料展开对pycrypto 算法加密的详细介绍,需要的小伙伴可以参考一下

一、安装

pip install pycryto

二、AES 加密解密

from Crypto.Cipher import AES
# 加密
aes = AES.new('this is a key 11', AES.MODE_CBC, 'this is a iv 222')
string = 'autofelix is god'
# encrypt()方法要求被加密的字符串必须也是16、24或32位的长度;所以一般要对被加密串进行处理
result = aes.encrypt(string)
# 解密
aes.decrypt(result)

三、SHA加密

from Crypto.Hash import SHA256
hash = SHA256.new()
hash.update('Hello, World!')
# 使用digest()方法加密
digest = hash.digest()
# 使用hexdigest()方法加密,该方法加密后是16进制的
hexdigest = hash.hexdigest()
print(digest, hexdigest)

四、RSA算法生成密钥对

from Crypto import Random
from Crypto.PublicKey import RSA
# 获取一个伪随机数生成器
random_generator = Random.new().read
# 获取一个rsa算法对应的密钥对生成器实例
rsa = RSA.generate(1024, random_generator)
# 生成私钥并保存
private_pem = rsa.exportKey()
with open('rsa.key', 'w') as f:
f.write(private_pem)
# 生成公钥并保存
public_pem = rsa.publickey().exportKey()
with open('rsa.pub', 'w') as f:
f.write(public_pem)
# 私钥 rsa.key 结果大概如下
# -----BEGIN RSA PRIVATE KEY-----
# MIICXQIBAAKBgQDR4Wq9l44lw/thTPyFmSi2hII92EPh90yGXQNL5e7zJPD16j6Q
# # tr+tIPNSQaVrnmNwrtqyEC2x4Meyp3tdCWPYUF11r2GgDgxKfUByetNG4XqJeUKk
# kJ6D6C706mTf/2zsm8KFoNYCYPX1GhvpiTOikHcNlHLCnOD7jbMAovJg/QIDAQAB
# AoGBAIz8V6+0NxC3bg4WoSs9j1PL/5F7zV3lucoogSZi9vjuP89x40Vi/a9XCxye
# bHi2lSYEz3P92jQ7QuqIBx6gSCi3p2HLjD5LyQeSSMbPe8KSlf52dBUaPthbBceA
# IJSBDrE8MKGpulTQKAJ7K3zQUOP2ZZgcKxq2jcQgS6iTENIBAkEA5r7emvwuL0Ob
# Maav4o1Ovb5c6OL7bSm1tuLPSKl05WuNYfE6LkqiwOOn5lPvsqhwyI1dJeywVeQz
# E+PvcTUR7QJBAOjZ8PxnP5T14fuhbfko4d24Ev+iiTBdq3pMXWvobEFL1ljV6aYE
# 2JAiMjO/Fzd1WgZhWPa3P+diyTs9mART6VECQQC0LeEXdsn9oDYEbFu1dZBB++8C
# 75NTJ5m8iJlB7QjZyMUq8Ln0wdUa9+n4ohxvDraa9EADSDJdr4bvBjLH3J/1AkBr
# 9QfO7kvDU5DXqoujVnoJ4xsj3IbAnt0vEZLKwfLW/0M84si2SU7i3IfsB+/KraT0
# ilPF50ZAkEN+LNt7PjBRAkAHBBPME7IbFqxi5Cc/6R12DOMiJbOLDTS12b1J1cwG
# p8WMIERsvwWdJw+4NdqjbJcjzeGrXhDBi//JU902TAwy
# -----END RSA PRIVATE KEY-----
# 公钥 rsa.pub 结果大概如下
# -----BEGIN PUBLIC KEY-----
# # MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDR4Wq9l44lw/thTPyFmSi2hII9
# 2EPh90yGXQNL5e7zJPD16j6Qtr+tIPNSQaVrnmNwrtqyEC2x4Meyp3tdCWPYUF11
# r2GgDgxKfUByetNG4XqJeUKkkJ6D6C706mTf/2zsm8KFoNYCYPX1GhvpiTOikHcN
# lHLCnOD7jbMAovJg/QIDAQAB
# -----END PUBLIC KEY-----

五、使用密钥对加密解密

import cgi, base64
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
import hashlib
# 要加密的字符串
message = 'autofelix is god'
# 使用公钥对内容进行 rsa 加密
with open('rsa.pub') as f:
key = f.read()
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(message))
print(cipher_text)
# 使用私钥对内容进行 rsa 解密
with open('rsa.key') as f:
key = f.read()
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
text = cipher.decrypt(base64.b64decode(encrypt_text), random_generator)
print(text)

六、加签和验签

import datetime, random
import requests
import hashlib
import json, base64
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
# 加签
def sign(signflag,keypath,baseRequest):
# http请求body
print(baseRequest)
# 加签标志
if not signflag:
return baseRequest
else:
# 取请求体中的业务数据
businessdata = json.dumps(baseRequest["data"])
# 读取私钥(.key格式,可使用openssl或java.keytools产生)
with open(keypath,'r') as rsaKeyFile:
rsaKey = rsaKeyFile.read().replace("\n",'')
print(rsaKey)
rsaKeyBytes = base64.b64decode(rsaKey)
print(rsaKeyBytes)
# SHA256摘要,RSA加密
priKey = RSA.importKey(rsaKeyBytes)
signer = PKCS1_v1_5.new(priKey)
hash_obj = SHA256.new(business_data.encode('utf-8'))
signature = base64.b64encode(signer.sign(hash_obj))
print(signature)
# 把签名加进请求体并返回
baseRequest['sign'] = signature.decode()
print(baseRequest)
return baseRequest
# 验签
def validata(signflag,cerpath,res):
if not signflag:
return res
else:
# 取业务数据和签名
data = res['data']
sign = res['sign']
# 此处cer已转换成pem格式,使用openssl工具
# openssl x509 -inform der -pubkey -noout -in xxxxx.cer>xxxxx.pem
cert = open(cerpath).read().replace("-----BEGIN PUBLIC KEY-----\n","").replace("-----END PUBLIC KEY-----\n","").replace("\n","")
print(cert)
# 验签逻辑同加签
pubBytes = base64.b64decode(cert)
pubKey = RSA.importKey(pubBytes)
signer = SHA256.new(json.dumps(data).encode("utf-8"))
verifier = PKCS1_v1_5.new(pubKey)
return verifier.verify(signer,base64.b64decode(sign))

到此这篇关于python 中的pycrypto 算法加密的文章就介绍到这了,更多相关pycrypto 算法加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文