python 中的pycrypto 算法加密
目录
一、安装二、AES加密解密三、SHA加密四、RSA算法生成密钥对五、使用密钥对加密解密六、加签和验签一、安装
pycryto能实现大致3种类型的数据加密(单向加密、对称加密 和非对称加密),产生随机数,生成密钥对,数字签名单向加密:Crypto.Hash,其中中包含MD5、SHA1、SHA256等对称加密:Crypto.Cipher,如常见的DES等非对称加密:Crypto.Cipher,如常见的AES加密等随机数操作:Crypto.Random,也可以使用Python内置的random模块和secrets模块产生数字签名与验签:可能需要使用到 Crypto.PublicKey,Crypto.Hash,Crypto.Signaturepip install pycryto
二、AES加密解密
可以使用 AES.new(key, Mode, IV) 进行加密设置key:长度必须是16、24、或32位VI:长度只能是16位解密时必须要知道加密时使用的key和IV,再通过decrypt()方法进行解密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算法生成密钥对
RSA是一种公钥密码算法RSA的密文是对代码明文的数字的 E 次方求mod N 的结果。也就是将明文和自己做E次乘法,然后再将其结果除以 N 求余数,余数就是密文。RSA是一个简洁的加密算法。E 和 N 的组合就是公钥对于RSA的解密,即密文的数字的 D 次方求mod N 即可,即密文和自己做 D 次乘法,再对结果除以 N 求余数即可得到明文。D 和 N 的组合就是私钥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 算法加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
X 关闭
X 关闭