英文:
How to read python RSA Pem key correctly?
问题
当我从数据库中读取RSA公钥时,我正在使用Python的RSA库。公钥以文本形式存储。
当我打印密钥的类型和值时(变量名为pk)(print(type(pk), pk)
):
<class 'bytes'> b'-----BEGIN RSA PUBLIC KEY-----\\nMIIBCgKCAQEAmXSSnzrY2/z7zLZuF7KZZFP7mbmYEeRhpQsQfpEv4t/Fvz6/g5QO\\n79ZcGBd6wOxshGFSLYPAl1oB3GPNkwr+mdjqtSIXzhhvW9Xjjx4dIUVn7JrtsBXi\\nr7aG85HEYyk3LLBoWus9X+XJ/tiHlQzqY2o8+dO31X4HBeWzflczrNXN3ntGGf4S\\noAaqJKlkUSxdGexvJUhmli9x+CKQoojFHxHfq1IZldRMPb8O8N6RSZIA5t2n6vpw\\nGPx8tBm7Eub5nVi+sACHS6rLdAHcd+D4tBCjp9wp2dGu77/oRUI7aomRFRMmBf7/\\nZkHHzor2kGIZ3fYHEL7g+WkVsxqGXblG8QIDAQAB\\n-----END RSA PUBLIC KEY-----\\n'
但是当我使用以下代码时:
pubkey = rsa.PublicKey.load_pkcs1(pk)
我得到以下错误:
File "/usr/local/lib/python3.11/site-packages/rsa/pem.py", line 77, in _pem_lines raise ValueError('No PEM start marker "%r" found' % pem_start) ValueError: No PEM start marker "b'-----BEGIN RSA PUBLIC KEY-----'" found
为什么会出现这个错误?如何修复它?
我尝试过让它工作,但一直没有成功。
英文:
I want to read a RSA public key from database. I am using rsa python lib. public key is stored as a text.
when i print type of key and it value i get (var name is pk) (print(type(pk), pk)
):
<class 'bytes'> b'-----BEGIN RSA PUBLIC KEY-----\\nMIIBCgKCAQEAmXSSnzrY2/z7zLZuF7KZZFP7mbmYEeRhpQsQfpEv4t/Fvz6/g5QO\\n79ZcGBd6wOxshGFSLYPAl1oB3GPNkwr+mdjqtSIXzhhvW9Xjjx4dIUVn7JrtsBXi\\nr7aG85HEYyk3LLBoWus9X+XJ/tiHlQzqY2o8+dO31X4HBeWzflczrNXN3ntGGf4S\\noAaqJKlkUSxdGexvJUhmli9x+CKQoojFHxHfq1IZldRMPb8O8N6RSZIA5t2n6vpw\\nGPx8tBm7Eub5nVi+sACHS6rLdAHcd+D4tBCjp9wp2dGu77/oRUI7aomRFRMmBf7/\\nZkHHzor2kGIZ3fYHEL7g+WkVsxqGXblG8QIDAQAB\\n-----END RSA PUBLIC KEY-----\\n'
but when i use
pubkey = rsa.PublicKey.load_pkcs1(pk)
i get
File "/usr/local/lib/python3.11/site-packages/rsa/pem.py", line 77, in _pem_lines raise ValueError('No PEM start marker "%r" found' % pem_start) ValueError: No PEM start marker "b'-----BEGIN RSA PUBLIC KEY-----'" found
error all the time. Why is that? How to fix it?
I tried to make it work but no luck yet.
答案1
得分: 0
以下是翻译好的部分:
- PEM 似乎被错误编码,或者在编码/解码过程中发生了变化。因此,在上述二进制字符串中,换行符从
\n
变为了\\n
; - 你将字符串处理为二进制字符串输入,其中转义字符没有转换为实际的换行符。
要在代码中直接修复这个问题,你可以在load_pkcs1
语句之前插入以下行:
pk = pk.replace(b'\\n', b'\n').decode('ascii')
这应该修复编码问题并取消转义换行符。
不确定为什么将PEM存储为二进制字符串,PEM结构的整个目的是将其作为文本而不是二进制存储。
英文:
There are two issues with your code:
- the PEM seems to be badly encoded, or it is altered during the encoding / decoding process. Due to this the newline character has gone from
\n
to\\n
in the above binary string; - you're handling the string as a binary string input, where the escape is not turned into an actual newline.
To fix this directly in code you can insert the following line before your load_pkcs1
statement:
pk = pk.replace(b'\\n', b'\n').decode('ascii')
which should fix the encoding and unescape the newline characters.
Not sure if and why the PEM is stored as a binary string; the whole point of a PEM structure is that it is text instead of binary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论