我一直在使用Pycrypto模块生成RSA公钥/私钥对,并尝试通过将公钥作为命令行参数来导入密钥:
from Crypto.PublicKey import RSA
from Crypto import Random
import sys
input_key = sys.argv[1]
print('\n')
print(type(input_key))
print('\n')
print(input_key)
print('\n')
public_key = RSA.importKey(input_key)
print(type(public_key))
但是我得到了输出:
$ python3 encrypt.py '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaIRYO3hxr0ObcYcgKtxFequ6p\n9HVV8E95ghUUHmydVJYy16Ip9F6ik7G8wBU7X3VIfjdxHAtrwY9doCy8Ype6NNio\nS/ErGRtUQ1jgyT2f9okIdroEipnh1zwbXQcxveaxlwBhp7OFGZ/0W3FKgJLYtyzW\nEhfPO+8GkT0eLH5FaQIDAQAB\n-----END'
>>> <class 'str'>
-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaIRYO3hxr0ObcYcgKtxFequ6p\n9HVV8E95ghUUHmydVJYy16Ip9F6ik7G8wBU7X3VIfjdxHAtrwY9doCy8Ype6NNio\nS/ErGRtUQ1jgyT2f9okIdroEipnh1zwbXQcxveaxlwBhp7OFGZ/0W3FKgJLYtyzW\nEhfPO+8GkT0eLH5FaQIDAQAB\n-----END PUBLIC KEY-----
Traceback (most recent call last):
File "encrypt.py", line 13, in <module>
public_key = RSA.importKey(input_key)
File "/usr/lib/python3/dist-packages/Crypto/PublicKey/RSA.py", line 638, in importKey
if lines[1].startswith(b('Proc-Type:4,ENCRYPTED')):
IndexError: list index out of range
但是当我将相同的密钥粘贴到Python Interpreter中时,我得到了这些:
>>> input_key = '-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaIRYO3hxr0ObcYcgKtxFequ6p\n9HVV8E95ghUUHmydVJYy16Ip9F6ik7G8wBU7X3VIfjdxHAtrwY9doCy8Ype6NNio\nS/ErGRtUQ1jgyT2f9okIdroEipnh1zwbXQcxveaxlwBhp7OFGZ/0W3FKgJLYtyzW\nEhfPO+8GkT0eLH5FaQIDAQAB\n-----END PUBLIC KEY-----'
>>> pub_key = RSA.importKey(input_key)
>>> type(pub_key)
<class 'Crypto.PublicKey.RSA._RSAobj'>
如何将它们作为命令行参数导入?
答案 0 :(得分:2)
执行时
$ python3 encrypt.py '-----BEGIN PUBLIC KEY-----\nMIG...'
shell不会将\n
解释为换行符,而是将其作为文字反斜杠+ n,以及您的程序在sys.argv[1]
中看到的内容。
您可以在转义的shell字符串中包含换行符,因此这应该有效:
$ python3 encrypt.py '-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaIRYO3hxr0ObcYcgKtxFequ6p 9HVV8E95ghUUHmydVJYy16Ip9F6ik7G8wBU7X3VIfjdxHAtrwY9doCy8Ype6NNio S/ErGRtUQ1jgyT2f9okIdroEipnh1zwbXQcxveaxlwBhp7OFGZ/0W3FKgJLYtyzW EhfPO+8GkT0eLH5FaQIDAQAB -----END PUBLIC KEY-----'
如果你真的想要使用带有转义的字符串,你可以通过执行input_key = sys.argv[1].replace('\\n', '\n')
自己在程序中处理转义,或者让shell执行转义,例如通过将字符串传递给echo:{{1 }}