首页 > 编程语言 >Python加密操作 对称加密/非对称加密

Python加密操作 对称加密/非对称加密

时间:2022-12-02 02:33:13浏览次数:44  
标签:加密 Python text Crypto cipher key new import 非对称

安装包: 

pycryptodome

https://pycryptodome.readthedocs.io/en/latest/src/installation.html#compiling-in-linux-ubuntu

 

 1 from Crypto.Hash import SHA256
 2 from Crypto.PublicKey import RSA
 3 from Crypto import Random
 4 from Crypto.Signature import pkcs1_15
 5 from Crypto.Cipher import PKCS1_v1_5
 6 
 7 key = RSA.generate(1024)
 8 # 公钥 私钥
 9 pri_key_text = key.export_key()
10 pub_key_text = key.public_key().export_key()
11 
12 pub_key = RSA.import_key(pub_key_text)
13 pri_key = RSA.import_key(pri_key_text)
14 
15 # 加密
16 text = b'abcdefg'
17 cipher = PKCS1_v1_5.new(pub_key)
18 etext = cipher.encrypt(text)
19 
20 # 解密
21 cipher_de = PKCS1_v1_5.new(pri_key)
22 dtext = cipher_de.decrypt(etext,None)
23 
24 # 签名
25 dg = SHA256.new(text)
26 sign = pkcs1_15.new(pri_key).sign(dg)
27 
28 # 签名验证
29 dg2 = SHA256.new(dtext)
30 try:
31     pkcs1_15.new(pub_key).verify(dg2, sign)
32 except ValueError:
33     print('验证失败')
34 
35 # 对称加密
36 
37 from Crypto.Random import get_random_bytes
38 from Crypto.Cipher import AES
39 from Crypto.Util.Padding import pad, unpad
40 
41 key = get_random_bytes(16)
42 cipher = AES.new(key, AES.MODE_CBC)
43 edata = cipher.encrypt(pad(text, AES.block_size))
44 
45 cipher_d = AES.new(key, AES.MODE_CBC, cipher.iv)
46 unpad(cipher_d.decrypt(edata),AES.block_size)

 

标签:加密,Python,text,Crypto,cipher,key,new,import,非对称
From: https://www.cnblogs.com/JiangOil/p/16943301.html

相关文章

  • python PIL resize
    https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.resizeImage.resize(size,resample=None,box=None,reducing_gap=None)[source]Re......
  • How to get file size in Python? 获取文件大小Python
    HowtogetfilesizeinPython?WecanfollowdifferentapproachestogetthefilesizeinPython.It’simportanttogetthefilesizeinPythontomonitorfi......
  • Python13-实战
    实战01(模拟篮球自动弹跳)#-*-coding:utf-8-*-importsys#导入sys模块importpygame#导入pygame模块pygame.init()#初始化pygamesize=width,height=640,......
  • python第13章实例
    #_*_coding:utf-8_*_importsysimportpygamepygame.init()size=width,height=640,480screen=pygame.display.set_mode(size)color=(0,0,0)ball=pygame.ima......
  • Python第十三章小球移动游戏
    #-*-coding:utf-8-*-importsys#导入sys模块importpygame#导入pygame模块pygame.init()#初始化pygamesize=width,height=640,480#设置窗口screen=pyga......
  • Python第十三章实验报告
    第十三章实验报告——篮球自动弹跳代码如下:1#----------实例01:制作一个跳跃的小球游戏----------#2importsys3importpygame4pygame.init()......
  • python篮球自动弹跳
           具体思路是首先导入sys和pygame模块然后初始化pygame然后显示窗口加载篮球图片执行死循环检查事件设置移动篮球将图片画在窗口上最后更新全部显示......
  • python-练习(知识点到逻辑运算符)
    1.在终端中显示古诗"登高"print("登高")print("作者:杜甫")print("风急天高猿啸哀,渚清沙白鸟飞回。")print("无边落木萧萧下,不尽长江滚滚来。")pr......
  • python第十三章实例1
    #-*-coding:utf-8-*-importsys#导入sys模块importpygame#导入pygame模块p......
  • python-正式课
    1.python简介1.1计算机基础结构1.1.1硬件五大组成部分:运算器、控制器、存储器、输入设备、输出设备。运算器:按照程序中的指令,对数据进行加工处理。控制器:根......