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.
CodePudding user response:
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.