http://www.javashuo.com/article/p-dtnlzbpa-cn.html
html
from Cryptodome.Cipher import DES import binascii # DES加密數據的長度須爲8的的倍數,不夠能夠用其它字符填充 text = 'Welcome to DES' if len(text) % 8 != 0: text = text + "+" * (8 - len(text) % 8) # 密鑰:必須爲8字節 key = b'12345678' # 使用 key 初始化 DES 對象,使用 DES.MODE_ECB 模式 des = DES.new(key, DES.MODE_ECB) # 加密 result = des.encrypt(text.encode()) print('加密後的數據:', result) # 轉爲十六進制 binascii 的 b2a_hex 或者 hexlify 方法 print('轉爲十六進制:', binascii.b2a_hex(result)) # 解密 print('解密後的數據:', des.decrypt(result))
from Cryptodome.Cipher import AES from Cryptodome import Random import binascii text = 'Welcome to AES' # 密鑰key 長度必須爲16(AES-128)、24(AES-192)或 32(AES-256)的Bytes長度 key = b'1234567890ABCDEF' # 生成長度等於AES塊大小的不可重複的密鑰向量 iv = Random.new().read(AES.block_size) # 使用 key 和 iv 初始化AES對象,使用 AES.MODE_CFB 模式 aes = AES.new(key, AES.MODE_CFB, iv) # 加密 result = aes.encrypt(text.encode()) # 解密 # 不能在encrypt()以後調用decrypt() # 須要用相同的key和iv初始化新的AES對象 decrypt_aes = AES.new(key, AES.MODE_CFB, iv) print('密鑰:', key) print('iv:', iv) print('十六進制的iv:', binascii.b2a_hex(iv)) print('加密後的數據:', result) print('轉爲十六進制:', binascii.b2a_hex(result)) print('解密後的數據:', decrypt_aes.decrypt(result))
import rsa text = 'Welcome to RSA' # 生成密鑰對 pubkey, prikey = rsa.newkeys(1024) # 加密:使用公鑰 result = rsa.encrypt(text.encode(), pubkey) print('加密後的數據:',result) # 解密:使用私鑰 print('解密後的數據:',rsa.decrypt(result, prikey))
import rsa text = 'Welcome to RSA' # 公鑰有兩個值 n,e public_n = "e0b509f62a8fc9" * 4 public_e = '010001' # n、e必須爲整數 # 將16進制的字符串轉爲整數 rsa_n = int(public_n, 16) rsa_e = int(public_e, 16) print('n:{}\ne:{}'.format(rsa_n, rsa_e)) # 建立公鑰 rsa.PublicKey(n,e) pubkey = rsa.PublicKey(rsa_n, rsa_e) print('公鑰類型:', type(pubkey)) print('公鑰:', pubkey) print('n:{}\ne:{}'.format(pubkey.n, pubkey.e)) print('加密後的數據:', rsa.encrypt(text.encode(), pubkey))
import rsa pubkey, prikey = rsa.newkeys(1024) # 加簽 rsa.sign(原信息,私鑰,加密方式) 生成加簽事後的信息 signMessage = rsa.sign('投資房地產'.encode(), prikey, 'MD5') print(signMessage) # 驗籤 rsa.verify(須要驗證的信息,加簽事後的信息,公鑰) # 若是須要驗證的信息,是原信息,返回加密方式 veri_1 = rsa.verify('投資房地產'.encode(),signMessage, pubkey) print('投資房地產:',veri_1) # 若是須要驗證的信息,不是原信息(表示信息被篡改過),則驗證失敗報錯:Verification failed veri_2 = rsa.verify('投資互聯網'.encode(),signMessage, pubkey) print('投資互聯網,',veri_2)