日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

[crypto]-52-python3中rsa(签名验签加密解密)aes(ecb cbc ctr)hmac的使用,以及unittest测试用

發布時間:2025/3/21 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [crypto]-52-python3中rsa(签名验签加密解密)aes(ecb cbc ctr)hmac的使用,以及unittest测试用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

環境
在ubuntu14.04下,記得安裝:sudo pip3 install pycrypto

代碼示例1

===========================

import base64 from Crypto.Cipher import AES import random import sys import osclass Crypto():def __init__(self,aes_key=''):if aes_key == "":self.aes_key = self.get_key(16)else:if len(aes_key) != 16:print("The key' length is error. It will create a new key.")self.aes_key = self.get_key(16)else:self.aes_key = aes_keydef pkcs7padding(self, text):bs = AES.block_size # 16length = len(text)bytes_length = len(bytes(text, encoding='utf-8'))padding_size = length if(bytes_length == length) else bytes_lengthpadding = bs - padding_size % bspadding_text = chr(padding) * paddingreturn text + padding_textdef pkcs7unpadding(self, text):length = len(text)unpadding = ord(text[length-1])return text[0:length-unpadding]def encrypt(self, content, mode, nonce=0):counter = os.urandom(16) key_bytes = bytes(self.aes_key, encoding='utf-8')if mode == AES.MODE_ECB:cipher = AES.new(key_bytes, mode)elif mode == AES.MODE_CTR:cipher = AES.new(key_bytes, mode, counter=lambda: nonce)else:iv = key_bytescipher = AES.new(key_bytes, mode, iv)content_padding = self.pkcs7padding(content)encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')return resultdef decrypt(self, content, mode, nonce=0):counter = os.urandom(16)key_bytes = bytes(self.aes_key, encoding='utf-8')if mode == AES.MODE_ECB:cipher = AES.new(key_bytes, mode)elif mode == AES.MODE_CTR:cipher = AES.new(key_bytes, mode, counter=lambda: nonce)else:iv = key_bytescipher = AES.new(key_bytes, mode, iv)encrypt_bytes = base64.b64decode(content)decrypt_bytes = cipher.decrypt(encrypt_bytes)result = str(decrypt_bytes, encoding='utf-8')result = self.pkcs7unpadding(result)return resultdef get_key(self, n):c_length = int(n)source = '0123456789abcdef'length = len(source) - 1result = ''for i in range(c_length):result += source[random.randint(0, length)]return resultif __name__ == '__main__':print(str(sys.argv[0]) + " enter")nonce = os.urandom(16)crypto = Crypto()print("========ECB===========")pt = 'ffff0123456789abcdef'ct = crypto.encrypt(pt, AES.MODE_ECB)print(ct)decryptd = crypto.decrypt(ct, AES.MODE_ECB)print(decryptd)print("========CBC===========")pt = 'ffff0123456789abcdef!'ct = crypto.encrypt(pt, AES.MODE_CBC)print(ct)decryptd = crypto.decrypt(ct, AES.MODE_CBC)print(decryptd)print("=========CTR==========")pt = 'ffff0123456789abcdef!'ct = crypto.encrypt(pt, AES.MODE_CTR, nonce)print(ct)decryptd = crypto.decrypt(ct, AES.MODE_CTR, nonce)print(decryptd)

================
程序運行結果

ECB===
fKrc2cSGGFg2rDVqrzuVQf6jbdhn2AkAp9ArPxr5wQw=
ffff0123456789abcdef
CBC===
ehMU2Nqd8BD9K5/ZkiWbhOK2MxtHs8uVSkPVX78oqgc=
ffff0123456789abcdef!
=CTR==
mKFpROhW2nd8/qi5Jt6SjZ2jakT5bONPQ8CVhRXs+OQ=
ffff0123456789abcdef!
baron@baron:~/workspace/code/gitHub/ctw/PythonTools/Crypto$ python3 crypto.py
crypto.py enter
ECB===
6AlUf8+rD1tamTThpU3IUUEDOl4fGpnwiG5ieutgXgs=
ffff0123456789abcdef
CBC===
HcAoEsRAGTeTFrMfJb2jI9Ulv0fhB0stJ1MXCrTYtP0=
ffff0123456789abcdef!
=CTR==
ME4PZKIMh/lvCLGHiDri2TVMDGSzNr7BUDaMu7sIiLA=
ffff0123456789abcdef!

==========================
unittest測試代碼

import unittest from Crypto.Cipher import AES import osfrom crypto import Crypto class cryptoTestCase(unittest.TestCase):def setUp(self):self.crypto = Crypto()pt_bytes = bytes([i for i in range(97,97+16)])#print(pt_bytes)self.pt = str(pt_bytes, encoding='utf-8')#print("self.pt = " + self.pt)def test_ecb(self):encryptd = self.crypto.encrypt(self.pt, AES.MODE_ECB)decryptd = self.crypto.decrypt(encryptd, AES.MODE_ECB)self.assertEqual(self.pt,decryptd)def test_cbc(self):encryptd = self.crypto.encrypt(self.pt, AES.MODE_CBC)decryptd = self.crypto.decrypt(encryptd, AES.MODE_CBC)self.assertEqual(self.pt,decryptd)def test_ctr(self):nonce = os.urandom(16)encryptd = self.crypto.encrypt(self.pt, AES.MODE_CTR, nonce)decryptd = self.crypto.decrypt(encryptd, AES.MODE_CTR, nonce)self.assertEqual(self.pt,decryptd)unittest.main()

==============
測試結果

Ran 3 tests in 0.001s

OK

代碼示例2

import base64 from Crypto.Cipher import AES import random import sys import os import hmac from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP import rsaimport binasciiclass Crypto():def __init__(self,aes_key=''):if aes_key == "":self.aes_key = self.get_key(16)else:if len(aes_key) != 16:print("The key' length is error. It will create a new key.")self.aes_key = self.get_key(16)else:self.aes_key = aes_keydef get_key(self, n):c_length = int(n)source = '0123456789abcdef'length = len(source) - 1result = ''for i in range(c_length):result += source[random.randint(0, length)]return resultdef pkcs7padding(self, text):bs = AES.block_size # 16length = len(text)bytes_length = len(bytes(text, encoding='utf-8'))padding_size = length if(bytes_length == length) else bytes_lengthpadding = bs - padding_size % bspadding_text = chr(padding) * paddingreturn text + padding_textdef pkcs7unpadding(self, text):length = len(text)unpadding = ord(text[length-1])return text[0:length-unpadding]def aes_encrypt(self, content, mode, nonce=0):counter = os.urandom(16) key_bytes = bytes(self.aes_key, encoding='utf-8')if mode == AES.MODE_ECB:cipher = AES.new(key_bytes, mode)elif mode == AES.MODE_CTR:cipher = AES.new(key_bytes, mode, counter=lambda: nonce)else:iv = key_bytescipher = AES.new(key_bytes, mode, iv)content_padding = self.pkcs7padding(content)encrypt_bytes = cipher.encrypt(bytes(content_padding, encoding='utf-8'))result = str(base64.b64encode(encrypt_bytes), encoding='utf-8')return resultdef aes_decrypt(self, content, mode, nonce=0):counter = os.urandom(16)key_bytes = bytes(self.aes_key, encoding='utf-8')if mode == AES.MODE_ECB:cipher = AES.new(key_bytes, mode)elif mode == AES.MODE_CTR:cipher = AES.new(key_bytes, mode, counter=lambda: nonce)else:iv = key_bytescipher = AES.new(key_bytes, mode, iv)encrypt_bytes = base64.b64decode(content)decrypt_bytes = cipher.decrypt(encrypt_bytes)result = str(decrypt_bytes, encoding='utf-8')result = self.pkcs7unpadding(result)return resultdef hmac_hash_with_file(self, hmackey_file, data_file):fp1 = open(hmackey_file, 'rb') hmackey = fp1.read()fp1.close()fp2 = open(hmackey_file, 'rb') # b'0123456789abcdef0123456789abcdef'message = fp2.read()fp2.close()hmac_hash = hmac.new(hmackey, message, digestmod="sha256").hexdigest()print(hmac_hash)return hmac_hashdef hmac_hash_with_str(self, key_text, message_text):hmac_hash = hmac.new(key_text.encode(), message_text.encode(), digestmod="sha256").hexdigest()print(hmac_hash)return hmac_hashdef format_pub(self, pub_pathname, format_pub_pathname):with open(pub_pathname,"r") as fp1,open(format_pub_pathname,"w") as fp2:for line in fp1:if "-----" in line:continuefp2.write(line.strip())def generate_rsa_pairs(self, priv_pathname, pub_pathname):(pubkey, privkey) = rsa.newkeys(2048)pub = pubkey.save_pkcs1()fp1 = open(pub_pathname,'w+')fp1.write(pub.decode())fp1.close()pri = privkey.save_pkcs1()fp2 = open(priv_pathname,'w+')fp2.write(pri.decode())fp2.close()def import_rsa_priv_key(self,filename):with open(filename,"r",encoding="utf-8") as f:line_list=f.readlines()self.private_key="".join(line_list)def import_rsa_pub_key(self,filename):with open(filename,"r",encoding="utf-8") as f:line_list=f.readlines()self.public_key="".join(line_list)def generate_N_E(self,pub_filename):with open(pub_filename) as f:key = RSA.import_key(f.read())print('e = %d' % key.e)print('n = %d' % key.n)def rsa_dec_with_file(self, hex_data_file):private_key = RSA.import_key(self.private_key)cipher_rsa = PKCS1_OAEP.new(private_key)fp1 = open(hex_data_file, 'rb') hex_data = fp1.read()fp1.close()text_data = cipher_rsa.decrypt(hex_data).decode('utf-8')return text_datadef rsa_dec(self, hex_data):private_key = RSA.import_key(self.private_key)cipher_rsa = PKCS1_OAEP.new(private_key)text_data = cipher_rsa.decrypt(hex_data).decode('utf-8')return text_datadef rsa_enc_with_file(self, text_data, hex_data_file):public_key = RSA.import_key(self.public_key)cipher_rsa = PKCS1_OAEP.new(public_key)hex_data = cipher_rsa.encrypt(text_data.encode('utf-8'))fp2 = open(hex_data_file, 'wb') # b'0123456789abcdef0123456789abcdef'fp2.write(hex_data)fp2.close()def rsa_enc(self, text_data):public_key = RSA.import_key(self.public_key)cipher_rsa = PKCS1_OAEP.new(public_key)hex_data = cipher_rsa.encrypt(text_data.encode('utf-8'))return hex_datadef selftest():nonce = os.urandom(16)crypto = Crypto()crypto.generate_rsa_pairs("test_priv.pem",'test_pub.pem')crypto.format_pub("test_pub.pem",'test_pub.txt')crypto.generate_N_E('test_pub.pem')print("========ECB===========")pt = 'ffff0123456789abcdef'ct = crypto.aes_encrypt(pt, AES.MODE_ECB)print(ct)decryptd = crypto.aes_decrypt(ct, AES.MODE_ECB)print(decryptd)print("========CBC===========")pt = 'ffff0123456789abcdef!'ct = crypto.aes_encrypt(pt, AES.MODE_CBC)print(ct)decryptd = crypto.aes_decrypt(ct, AES.MODE_CBC)print(decryptd)print("========HMAC===========")#crypto.hmac_hash_with_file('1.txt','1.txt')crypto.hmac_hash_with_str('0123456789abcdef0123456789abcdef','0123456789abcdef0123456789abcdef')print("========RSA===========")crypto.import_rsa_priv_key('test_priv.pem')crypto.import_rsa_pub_key('test_pub.pem')enc_data = crypto.rsa_enc('zhouhehe')dec_data = crypto.rsa_dec(enc_data)print(dec_data)if __name__ == '__main__':print(str(sys.argv[0]) + " enter")curdir = os.getcwd()print(curdir)selftest()

相關推薦:
?????????[crypto]-01-對稱加解密AES原理概念詳解
?????????[crypto]-02-非對稱加解密RSA原理概念詳解
?????????[crypto]-03-數字摘要HASH原理概念詳解
?????????[crypto]-04-國產密碼算法(國密算法sm2/sm3/sm4)介紹
?????????[crypto]-05-轉載:PKCS #1 RSA Encryption Version 1.5介紹
?????????[crypto]-05.1-PKCS PKCS#1 PKCS#7 PKCS#11的介紹
?????????[crypto]-06-CA證書介紹和使用方法


?????????[crypto]-30-The Armv8 Cryptographic Extension在linux中的應用
?????????[crypto]-31-crypto engion的學習和總結


?????????[crypto]-50-base64_encode和base64_decode的C語言實現
?????????[crypto]-51-RSA私鑰pem轉換成der, 在將der解析出n e d p q dp dq qp
?????????[crypto]-52-python3中rsa(簽名驗簽加密解密)aes(ecb cbc ctr)hmac的使用,以及unittest測試用
?????????[crypto]-53-openssl命令行的使用(aes/rsa簽名校驗/rsa加密解密/hmac)


?????????[crypto]-90-crypto的一些術語和思考

總結

以上是生活随笔為你收集整理的[crypto]-52-python3中rsa(签名验签加密解密)aes(ecb cbc ctr)hmac的使用,以及unittest测试用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 日韩成人精品视频 | 国产精品三级视频 | 中文字幕第四页 | 欧美精品五区 | 中国女人内谢69xxxx免费视频 | 被黑人啪到哭的番号922在线 | 无码人妻丰满熟妇区五十路 | 久久久久九九九 | 自拍偷拍第二页 | 懂色av中文字幕 | 四虎成人精品永久免费av九九 | 中文字幕第页 | 蜜桃av成人| 五月天色站| 日韩在线一区二区 | 欧美黄色免费网站 | 久久在线电影 | 视频一区二区不卡 | 欧美日韩免费在线视频 | 天海翼av在线 | 亚洲av成人精品一区二区三区在线播放 | 中文字幕 日韩有码 | 青青一区二区 | 黄色a级在线观看 | 国产精品三级久久久久久电影 | 亚洲精品国产精品乱码视色 | 国偷自产av一区二区三区 | 亚洲AV无码成人精品区麻豆 | 午夜亚洲AV永久无码精品蜜芽 | 日韩极品在线 | 黄色网络在线观看 | 国产男女猛烈无遮挡免费观看网站 | sao虎视频在线精品永久 | 黄色91免费版| 久久久久久久国产精品视频 | 久久亚洲精精品中文字幕早川悠里 | 91久久精品一区二区三 | 小早川怜子一区二区三区 | 韩国三色电费2024免费吗怎么看 | 国产在线视频卡一卡二 | 97操操 | 亚洲网站在线播放 | 中文字幕日本人妻久久久免费 | 亚洲色图图 | 色播五月激情五月 | 国产精品黄在线观看 | 亚洲av久久久噜噜噜噜 | 99色图| 狠狠鲁视频 | 亚洲精品在线观看免费 | 三上悠亚在线一区二区 | 天天干天天草天天射 | 欧美综合在线视频 | 黄色a站| 超碰1000| 精品国产乱码久久久久久蜜臀网站 | www网站在线观看 | 免费一区二区在线观看 | 69xx欧美 | 欧美女同在线 | 久久96| 一级国产黄色片 | 91成人午夜 | 91娇羞白丝 | 国产淫视 | 天堂成人在线视频 | 亚洲tv在线观看 | 国内性视频 | 精品少妇人妻一区二区黑料社区 | 久久久久久五月天 | 欧美一区二区三区四区五区 | 欧美激情视频一区二区三区 | 日本一区二区免费在线 | 国产成人精品女人久久久 | 久久久av一区二区三区 | 国产午夜大地久久 | 国产精品2| 久久天天干 | 亚州国产精品视频 | 国产精品中文久久久久久 | 亚洲一区二区黄 | 亚洲一区二区三区黄色 | 全部免费毛片在线播放高潮 | 在线观看亚洲一区二区 | 六月丁香婷婷综合 | 天天碰天天 | 在线爱情大片免费观看大全 | 国产人妖ts重口系列网站观看 | jizz免费视频 | 日韩av视屏 | 日韩少妇| 粗口调教gay2022.com| 国产成人精品综合在线观看 | 欧美日韩一区二区三区在线视频 | 亚洲久久久| 久久亚洲精品国产精品黑人v | 强开小受嫩苞第一次免费视频 | 免费av在线播放 | 十八岁世界在线观看高清免费韩剧 |