关注this post我正在创建一个小型Python脚本,可以输入公共RSA密钥并输出私有RSA密钥。
现在可以通过这种方式传递参数:
./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
文件时工作,在这种情况下,用户需要以这种方式输入n
和e
:
./Converter.py -n 7919 -e 65537
我正在使用argparse
,现在基本上Python正在从n
文件中提取e
和.pem
。
但我希望argparse
在用户提供n
和e
时绕过此提取
答案 0 :(得分: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
答案 1 :(得分:1)
只需为-n
和-e
parser.add_argument('-n', type=int)
parser.add_argument('-e', type=int)
如果args.n and args.e
求值为True
,则忽略输入参数并跳过处理它的代码。