zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

Python加密 生成 rsa 密钥 AES 加解密 Crypto
2023-09-27 14:26:31 时间

直接上代码

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 rsa

import binascii

class 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_key

	def get_key(self, n):
		c_length = int(n)
		source = '0123456789abcdef'
		length = len(source) - 1
		result = ''
		for i in range(c_length):
			result += source[random.randint(0, length)]
		return result

	def pkcs7padding(self, text):
		bs = AES.block_size  # 16
		length = len(text)
		bytes_length = len(bytes(text, encoding='utf-8'))
		padding_size = length if(bytes_length == length) else bytes_length
		padding = bs - padding_size % bs
		padding_text = chr(padding) * padding
		return text + padding_text


	def 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_bytes
			cipher = 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 result

	def 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_bytes
			cipher = 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 result

	def 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_hash

	def 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_hash

	def 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:
					continue
				fp2.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_data

	def 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_data

	def 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_data

def 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()