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