1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > [crypto]-51.1-python的aes加解密/rsa生成密钥对/rsa加解密/hmac加密

[crypto]-51.1-python的aes加解密/rsa生成密钥对/rsa加解密/hmac加密

时间:2022-10-23 04:29:04

相关推荐

[crypto]-51.1-python的aes加解密/rsa生成密钥对/rsa加解密/hmac加密

直接上代码

import base64from Crypto.Cipher import AESimport randomimport sysimport osimport hmacfrom Crypto.PublicKey import RSAfrom Crypto.Cipher import PKCS1_OAEPimport 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()

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。