python3 | 利用Crypto生成公钥、私钥,文本加密、文本解密

生成公钥、私钥

from Crypto import Random
from Crypto.PublicKey import RSA

# 获取一个伪随机数生成器
random_generator = Random.new().read
# 获取一个rsa算法对应的密钥对生成器实例
rsa = RSA.generate(2048, random_generator)

# 生成私钥并保存
private_pem = rsa.exportKey()
with open('rsa.key', 'wb') as f:
    f.write(private_pem)

# 生成公钥并保存
public_pem = rsa.publickey().exportKey()
with open('rsa.pub', 'wb') as f:
    f.write(public_pem)

长字符串加密

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
import base64
import sys

def read_file(input_file):
	with open(input_file, 'r') as f:
		message = f.read()
	return message
	pass

def encrypt_file(message, pubkey_file, out_file):
	with open(pubkey_file, 'r') as f:
		publicKey = f.read()
	pubKeyObj = RSA.importKey(publicKey)
	cipherObj = Cipher_PKCS1_v1_5.new(pubKeyObj)
#	cipherText = base64.b64encode(cipherObj.encrypt(message))
	res = []
	for i in range(0, len(message), 200):
		res.append(base64.b64encode(cipherObj.encrypt(message[i:i+200])))
	cipherText = b"".join(res)
	with open(out_file, 'wb') as f_w:
		f_w.write(cipherText)
	pass


def main():
	inputFile = sys.argv[1]
	publicKey = sys.argv[2]
	encryptFile = 'encrypt.'+inputFile
	message = read_file(inputFile)
	message = message.encode()
	encrypt_file(message, publicKey, encryptFile)
	pass


if __name__ == '__main__':
	main()

长字符串解密

from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5
import base64
import sys



def read_encrypt_file(encrypt_file):
	with open(encrypt_file, 'rb') as f:
		message = f.read()
	return message
	pass

def decrypt_file(message, private_file, out_file):
	with open(private_file, 'r') as f:
		privateKey = f.read()
	rsaKeyObj = RSA.importKey(privateKey)
	cipherObj = Cipher_PKCS1_v1_5.new(rsaKeyObj)
	randomGenerator = Random.new().read
	#plainText = cipherObj.decrypt(base64.b64decode(message), randomGenerator)
	res = []
	for i in range(0, len(message), 344):
		res.append(cipherObj.decrypt(base64.b64decode(message[i:i+344]), randomGenerator))
	plainText = (b"".join(res))
	with open(out_file, 'w') as f_w:
		f_w.write(plainText.decode())
	pass


def main():
	inputFile = sys.argv[1]
	privateFile = sys.argv[2]
	decryptFile = 'decrypt.'+inputFile
	message = read_encrypt_file(inputFile)
	decrypt_file(message, privateFile, decryptFile)
	pass


if __name__ == '__main__':
	main()

 

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值