其他分享
首页 > 其他分享> > 读取PEM字符串时出现PyAsn1错误

读取PEM字符串时出现PyAsn1错误

作者:互联网

我正在尝试在Python中读取PEM编码的公钥.我尝试了多个键和多个可能的解决方案.我尝试了base64解码,其他格式,等等…

我真的不知道该怎么办(因为自从昨天以来我已经遇到了这个问题).

我得到的错误:

Traceback (most recent call last):
  File "I:/path/Main.py", line 6, in <module>
    -----END RSA PUBLIC KEY-----""", format='PEM')
  File "C:\Python34\lib\site-packages\rsa-3.1.4-py3.4.egg\rsa\key.py", line 65, in load_pkcs1
  File "C:\Python34\lib\site-packages\rsa-3.1.4-py3.4.egg\rsa\key.py", line 192, in _load_pkcs1_pem
  File "C:\Python34\lib\site-packages\rsa-3.1.4-py3.4.egg\rsa\key.py", line 160, in _load_pkcs1_der
  File "C:\Python34\lib\site-packages\pyasn1-0.1.7-py3.4.egg\pyasn1\codec\ber\decoder.py", line 792, in __call__
  File "C:\Python34\lib\site-packages\pyasn1-0.1.7-py3.4.egg\pyasn1\codec\ber\decoder.py", line 321, in valueDecoder
  File "C:\Python34\lib\site-packages\pyasn1-0.1.7-py3.4.egg\pyasn1\codec\ber\decoder.py", line 798, in __call__
pyasn1.error.PyAsn1Error: TagSet(Tag(tagClass=0, tagFormat=32, tagId=16)) not in asn1Spec: {TagSet(Tag(tagClass=0, tagFormat=0, tagId=2)): Integer()}/{}

我的代码:

pubkey = rsa.PublicKey.load_pkcs1(b"""-----BEGIN RSA PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANkHLKYS2dByWQ3gKjQDvQbuWb/2Y9z4
eYuLEfgXdiP5qc5cG/5c+c/GgIl6yQY7AYeZVXiBXLaGzxiLZ5Y4fi0CAwEAAQ==
-----END RSA PUBLIC KEY-----""", format='PEM')
crypto = rsa.encrypt("Secret", pubkey)

Screen
RSA Documentations

解决方法:

我不确定我做对了.但是至少跟随加密没有错误.

import rsa
pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(b"""-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANkHLKYS2dByWQ3gKjQDvQbuWb/2Y9z4
eYuLEfgXdiP5qc5cG/5c+c/GgIl6yQY7AYeZVXiBXLaGzxiLZ5Y4fi0CAwEAAQ==
-----END PUBLIC KEY-----""")
crypto = rsa.encrypt(b"Secret", pubkey)

注意:我将BEGIN RSA PUBLIC KEY更改为BEGIN PUBLIC KEY. (与END RSA PUBLIC KEY相同).我使用了load_pkcs1_openssl_pem.

更新

传递字节对象而不是str(尤其是如果您在Python 3.x中运行此对象).

标签:python-3-4,python-3-x,rsa,pem,python
来源: https://codeday.me/bug/20191121/2051400.html