2017-10-22 2 views
-1

그래서 내가 암호화 및 암호 해독에 내 파이썬 능력을 향상하기로 결정하고 다음 실행하는 파이썬 프로그램을 작성하는 시도 :DES, RSA 암호화 및 암호 해독

  • 는 1024 비트 개인 키와
  • 키 공개를 생성을
  • 암호화 DES 알고리즘
  • 을 파일에 저장
  • 저장 RSA 등을 통해
  • 암호화하는 공개 키를 사용하여 파일에 공개 키 암호화 된 개인 키와 개인 키 gorithm, 파일

나는 오류가 계속 :

Traceback (most recent call last): 
    File "C:\Users\john\Desktop\python\E&D.py", line 10, in <module> 
    pr = RSA.importKey(open('mykey.pem', 'r')) 
    File "C:\Python27\lib\site-packages\Crypto\PublicKey\RSA.py", line 678, in importKey 
    if bord(externKey[0])==0x30: 
IndexError: string index out of range 

내 코드 :

import Crypto 
from Crypto.PublicKey import RSA 
from Crypto.Cipher import DES 

# Generate Private Key 
private = RSA.generate(1024) 
m = open('mykey.pem','w') 
m.write(private.exportKey('PEM')) 

#Get public key 
public = private.publickey() 
pr = RSA.importKey(open('mykey.pem', 'r')) 

#DES encryption 
password= '' 
des= DES.new(password,DES.MODE_ECB) 
des_cipher= des.encrypt(pr) 

f = open('privatekey.dat','w') 
l = open('publickey.dat','w') 
s=open('encrypted.dat','w') 
w = open('encrypt.dat', 'r') 
war = w.read() 
f.write(des_cipher) 
l.write(public) 

#RSA encryption 
enc_data = public.encrypt(war) 
s.write(enc_data) 
f.close() 
l.close() 
s.close() 
w.close() 
m.close() 

답변

0

RSA.importKey() 문자열이 아닌 파일을합니다. 제대로 파일을 닫습니다 컨텍스트 관리자를 사용하여,

pr = RSA.importKey(open('mykey.pem', 'r').read()) 

또는 : 파일을 읽기

with open('mykey.pem', 'r') as keyfile: 
    pr = RSA.importKey(keyfile.read()) 

를 컨텍스트 관리자가 마지막에 그들 각각에 close를 호출 할 필요가 제거로 파일을 사용. RSA.importKey() documentation에서

:

importKey(externKey, passphrase=None)

Import an RSA key (public or private half), encoded in standard form.

[...]

Parameters:

  • externKey (string) - The RSA key to import, encoded as a string.

다음, 당신은 RSA 개인 키 객체를 암호화 할 수 없습니다. 바이트 만 암호화 할 수 있으므로 개인 키를 다시 내 보냅니다. 다음과 같이 블록 길이의 배수로 문자열 (PKCS # 7 표준을 사용)을 채워야합니다.

plaintext = pr.exportKey('PEM') 
remainder = len(plaintext) % des_cipher.block_length 
if remainder: 
    # add padding 
    pad_length = des.block_length - remainder 
    plaintext += chr(pad_length) * pad_length 
des_cipher = des.encrypt(remainder)