日韩性视频-久久久蜜桃-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测试用的全部內容,希望文章能夠幫你解決所遇到的問題。

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

主站蜘蛛池模板: 日本a在线免费观看 | 黄色大尺度视频 | 无码人妻av免费一区二区三区 | 校园春色 亚洲色图 | 进去里视频在线观看 | 中文字幕人成人乱码亚洲电影 | 神马午夜在线 | 大乳女喂男人吃奶 | 国产一级一级国产 | 午夜黄色福利视频 | 国产精品久久久久国产a级 国产一区二区在线播放 | 欧美日韩国产电影 | 日韩欧美爱爱 | 日本色综合网 | 视频1区| 一级片免费视频 | 国产三级精品三级在线 | 777理伦三级做爰 | 女同性做爰全过程 | 吻胸摸激情床激烈视频大胸 | 国产精品久久久久久亚洲av | 亚洲天堂二区 | 日韩一级色 | 国产午夜精品无码一区二区 | 亚洲国产中文在线 | 四川黄色一级片 | 男人的天堂网av | 国产aa大片 | 国产精品69久久久久孕妇欧美 | jjzz日本视频 | 免费中文字幕日韩欧美 | 日本大尺度电影免费观看全集中文版 | 国产精品一卡二卡三卡 | 高清国产在线观看 | 色婷久久| 美女无遮挡网站 | 成人中文网 | 欧美日韩一区二区视频观看 | 日日操夜夜操狠狠操 | 伊人网大香 | 性高跟鞋xxxxhd国产电影 | 男女激情在线观看 | 精品国产传媒 | 午夜精品久久久久久久99老熟妇 | 91在线无精精品一区二区 | xvideos永久免费入口 | 黑人玩弄人妻一区二区三区 | 中文字幕日韩精品一区 | 爱的色放在线 | 麻豆区1免费 | 日韩有码视频在线 | 锦绣未央在线观看 | 国产精品一区二区在线看 | www.久久伊人 | 日韩经典一区 | 爱情岛论坛亚洲品质自拍视频 | 日日鲁鲁鲁夜夜爽爽狠狠视频97 | 少妇被黑人到高潮喷出白浆 | 色咪咪网站 | 91亚洲影院 | free性欧美hd精品4k | 黑人精品xxx一区一二区 | 日韩av一区二区三区在线 | 国产精品美女久久 | 91麻豆国产在线 | 日日骑夜夜操 | 久久久久久av无码免费网站 | 日韩影音| 99热热 | 国产人妖av | 国产欧美一区二区三区视频 | www中文字幕| 污污网站在线观看 | 国产美女无遮挡永久免费观看 | 国产成人a v | 麻豆视频网 | 北条麻妃99精品青青久久 | 天堂网av中文字幕 | 亚洲第一精品网站 | 日本a在线免费观看 | 天天做日日干 | 少妇人妻偷人精品无码视频 | 免费在线毛片 | 午夜黄色福利视频 | 免费在线观看毛片 | 国产一区二区三区在线观看 | 国产三级精品三级 | 嫩草网站在线观看 | 亚洲AV成人无码网站天堂久久 | 不卡久久 | 色噜噜色综合 | 免费看污视频的网站 | 国产无码精品一区二区 | 五月婷婷丁香激情 | 秋霞av在线 | 黄色91免费版 | 国产一卡在线 | 久久精品电影 | 亚洲13p |