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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章