python3.9 pycropto RSA Error: TypeError: can't concat str to bytes
1. Error reporting
The recent project uses the pycrypto package under python3.9. The following errors occur when using the RSA module, mainly because bytes and STR in python3 cannot be spliced
File "/usr/local/python-3.9.4/lib/python3.9/site-packages/Crypto/PublicKey/RSA.py", line 352, in exportKey
keystring = ''.join([ struct.pack(">I",len(kp))+kp for kp in keyparts])
File "/usr/local/python-3.9.4/lib/python3.9/site-packages/Crypto/PublicKey/RSA.py", line 352, in <listcomp>
keystring = ''.join([ struct.pack(">I",len(kp))+kp for kp in keyparts])
TypeError: can't concat str to bytes
2. Modification
We can check the error file /python3.9/site-packages/crypto/publickey/rsa Py
the main idea is to change the output variable into bytes for splicing. The original part of the file content is modified, line:346:
if format=='OpenSSH':
eb = long_to_bytes(self.e)
nb = long_to_bytes(self.n)
if bord(eb[0]) & 0x80: eb=bchr(0x00)+eb
if bord(nb[0]) & 0x80: nb=bchr(0x00)+nb
keyparts = [ 'ssh-rsa', eb, nb ]
keystring = ''.join([ struct.pack(">I",len(kp))+kp for kp in keyparts])
return 'ssh-rsa '+binascii.b2a_base64(keystring)[:-1]
Modified to:
if format=='OpenSSH':
eb = long_to_bytes(self.e)
nb = long_to_bytes(self.n)
if bord(eb[0]) & 0x80: eb=bchr(0x00)+eb
if bord(nb[0]) & 0x80: nb=bchr(0x00)+nb
keyparts = [ 'ssh-rsa', eb, nb ]
new_list = []
for kp in keyparts:
temp = struct.pack(">I", len(kp))
if isinstance(kp, str):
kp = bytes(kp,encoding='utf-8')
temp += kp
new_list.append(temp)
keystring = b''.join(new_list)
return b'ssh-rsa '+binascii.b2a_base64(keystring)[:-1]