♣ 도움받은 사이트

https://8gwifi.org/docs/python-rsa.jsp

https://stackoverflow.com/questions/21327491/using-pycrypto-how-to-import-a-rsa-public-key-and-use-it-to-encrypt-a-string

 

♣  Python 에서 RSA 를 사용하기 위해 아래와 같이 pycryot를 설치하였다.

1. pycropto 설치 (Linux)

https://pypi.python.org/pypi/pycrypto 에서 모듈을 다운받는다.

아래와 같이 설치한다.

$ sudo python3 setup.py install

 

설치하면... time.clock() 함수가 없다고 뜬다.

찾아보니 Python 3.8 부터 위 함수가 폐기됐다고 한다. 아오~~

결국 Python 2.7 에서 설치하였다.

 

리눅스에서

$ python -> 2.7

$ python3 -> 3.8 로 실행되기에 python 으로 실행했다.

 

♣  Python 에서 Public Key, Private Key 생성하기

Public Key, Priavte 키 생성 (PEM 방식)

from Crypto.PublicKey import RSA

#Export RSA public/private KEY in PEM format
key = RSA.generate(2048)
privKey = key.exportKey('PEM')
pubKey = key.publickey().exportKey('PEM')

 

#save PEM key into the file
with open('private.pem', 'w') as file:
        file.write(privKey)
        file.write('\n')

 

with open('public.pem', 'w') as file:
        file.write(pubKey)
        file.write('\n')

 

테스트를 위해 plain.txt 파일을 만들고 아래와 같이 내용을 추가한다. (변경 가능0

Open SSL, Python Test

 

♣  OpenSSL 로 키 테스트

Python에서 생성한 키로  OpenSSL 에서 테스트해 본다.

 

1. Public key 로 암호화하기

 $ openssl rsautl -encrypt -inkey ./public.pem -pubin -in ./plain.txt -out encrypt.txt

 

2. Private Key 로 복호화하기

 $ openssl rsautl -decrypt -inkey private.pem -in encrypt.txt -out decPlain.txt

 

3. plain.txt 와 decPalin.txt 의 내용이 같은지 확인해 본다.

 

♣  Python 에서 Public Key 로 암호화 하기.

위에서 생성한 public key 로 아래와 같이 암호화 해 본다.

 

Encrypt Plain Text by public key

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5

fPri = open('private.pem', 'rb')
fPub = open('public.pem', 'rb')

 

prikey = RSA.importKey(fPri.read())
pubKey = RSA.importKey(fPub.read())

 

#RSA Encryption Using Public Key
fp = open('plain.txt', 'rb')

cipherKey = Cipher_PKCS1_v1_5.new(pubKey)
cipherText = cipherKey.encrypt(fp.read())

 

fEnc = open('encrypt.txt', 'wb')
fEnc.write(cipherText)

 

# archive
#cipherText = pubKey.encrypt(fp.read(),32)
#cipherMsg = cipherText[0]


fPri.close()
fPub.close()
fp.close()
fEnc.close()

위에서 암호화 한 문장 (encrypt.txt) 을 openSSL 에서 복호화할 수 있다.

 

♣ Python 에서 Private Key 로 복호화 하기.

위에서 생성한 Private Key 로 아래와 같이 복호화 한다.

 

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5

fPri = open('private.pem', 'rb')

prikey = RSA.importKey(fPri.read())

 

#RSA Encryption Using Public Key
fEnc = open('encrypt.txt', 'rb')

cipher = Cipher_PKCS1_v1_5.new(prikey)
cipherText = cipher.decrypt(fEnc.read(), None).decode()

 

fDec = open('decPlain.txt', 'wb')
fDec.write(cipherText)

 

fPri.close()
fEnc.close()
fDec.close()

저 위의 OpenSSL 에서 암호화 한 후,

Python 에서 위와 같이 복호화하면 동일하게 복호화 되었다.

+ Recent posts