2017-04-22 74 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则忽略该项输入参数并跳过处理它的代码。