2017-04-22 71 views
0

正在關注this post我正在創建一個小型Python腳本,可以輸入公共RSA密鑰並輸出私有RSA密鑰。Argparse:如果提供另一個參數,則繞過參數

現在它通過傳遞的參數是這樣的:

./Converter.py -input publikey.pem 

這是代碼:

<!-- language: lang-py --> 

parser = argparse.ArgumentParser() 
parser.add_argument('-i', dest='infile', help="input a .pem file which contains pubilc key") 
args = parser.parse_args() 
# --- Here we search for n and e --- 
PublicKey = args.infile 
OpenPublicKey = open(PublicKey, 'r') 
ReadPublicKey = OpenPublicKey.read() 
TheKey = RSA.importKey(ReadPublicKey) 
n = long(TheKey.n) 
e = long(TheKey.e) 
print 'This is modulus n: ', n, '\n' 
print 'This is public exponent e: ', e, '\n' 

我也想劇本的時候沒有公鑰.pem文件工作,在這種情況下用戶需要輸入ne這樣:

./Converter.py -n 7919 -e 65537 

我使用的是​​,現在基本上Python正在從.pem文件中提取ne

但我想​​繞過這種提取時由用戶提供ne

+0

爲了找到一個給定的公鑰私鑰,你將不得不因素模'ñ '。請記住,模數'n'應大於'e'(實際上是λ(n)> e') –

回答

2
#!python2 
import argparse 
from Crypto.PublicKey import RSA 
parser = argparse.ArgumentParser() 
group = parser.add_mutually_exclusive_group(required=True) 

group.add_argument('-f','--infile', help="input a .pem file which contains pubilc key") 
group.add_argument('-ne',nargs=2, help="value of n and e") 

args = parser.parse_args() 
# --- Here we search for n and e --- 
if args.infile: 
    PublicKey = args.infile 
    OpenPublicKey = open(PublicKey, 'r') 
    ReadPublicKey = OpenPublicKey.read() 
    TheKey = RSA.importKey(ReadPublicKey) 
    n = long(TheKey.n) 
    e = long(TheKey.e) 

else: 
    n,e=map(long,args.ne) 
print 'This is modulus n: ', n 
print 'This is public exponent e: ', e 

對於文件輸入:

./Converter.py -f publickey.pem 

對於可變輸入:

./Converter.py -ne 4 5 
+0

它的工作原理@SmartManoj但是argparse如何知道INFILE,因爲它沒有在('-i',' --infile',help =「輸入一個包含pubilc鍵的.pem文件」)?它是否來自--infile?但是這不應該是命令行的第二種選擇? –

+0

它需要很長的選項'--infile'。[Source](https://docs.python.org/3/library/argparse.html#dest) – SmartManoj

1

只需添加可選關鍵字參數爲-n-e

parser.add_argument('-n', type=int) 
parser.add_argument('-e', type=int) 

如果args.n and args.e評估爲True則忽略該項輸入參數並跳過處理它的代碼。