from Crypto.PublicKey import RSA def main(): msg = b'hellow!' print(msg) private_key = RSA.generate(1024) # 개인키를 하나 만듬 print('private_key : {}'.format(private_key)) public_key = private_key.publickey() # private_key를 알면 public_key를 구할 수 있음 print('public_key : {}'.format(public_key)) cipher_msg = public_key.encrypt(msg, 32) print('cipher_msg : {}'.format(cipher_msg)) # ctrl + p = 자동완성 plain_msg = private_key.decrypt(cipher_msg) print('plain_msg : {}'.format(plain_msg)) if __name__ == '__main__': main()
[4] 시연
(3) RSA의 공개키와 개인키 추출
[1] 소스
from Crypto.PublicKey import RSA def main(): private_key = RSA.generate(1024) public_key = private_key.publickey() # print('1. private_key : {}'.format(private_key.exportKey('PEM'))) # 키의 객체를 문자열로 변경 with open('private_key.pem', 'w', encoding='utf-8') as fd: fd.write(private_key.exportKey('PEM').decode()) # private_key.pem 파일을 쓰기모드로 열고 키의 객체(문자열)를 저장 fd = open('public_key.pem', 'wb+') fd.write(public_key.exportKey('PEM')) fd.close() # public_key.pem 파일을 쓰기모드로 열고 키의 객체를 문자열로 저장 # with open으로 열 때는 'w'모드로 열었고 그러면 byte는 쓸 수 없고 str만 쓰기가능 # open으로 열 때는 'wb+'모드로 열었고 그러면 str과 byte 모두 쓰기가능 # 그래서 with open은 byte를 str로 바꾸는 decode()를 추가로 사용 if __name__ == '__main__': main()