leedjango
leedjango

Reputation: 411

RSA key format is not supported in python

I want to encrypt the plain text with the public key I have. To do this, I wrote the code using the pycryptodome module as follows.

from Cryptodome.Cipher import PKCS1_v1_5
from Cryptodome.PublicKey import RSA
from base64 import b64decode,b64encode

key = '30820122300d06092a864886f70d01010105000382010f003082010a0282010100f357429c22add0d547ee3e4e876f921a0114d1aaa2e6eeac6177a6a2e2565ce9593b78ea0ec1d8335a9f12356f08e99ea0c3455d849774d85f954ee68d63fc8d6526918210f28dc51aa333b0c4cdc6bf9b029d1c50b5aef5e626c9c8c9c16231c41eef530be91143627205bbbf99c2c261791d2df71e69fbc83cdc7e37c1b3df4ae71244a691c6d2a73eab7617c713e9c193484459f45adc6dd0cba1d54f1abef5b2c34dee43fc0c067ce1c140bc4f81b935c94b116cce404c5b438a0395906ff0133f5b1c6e3b2bb423c6c350376eb4939f44461164195acc51ef44a34d4100f6a837e3473e3ce2e16cedbe67ca48da301f64fc4240b878c9cc6b3d30c316b50203010001\n\'

plain = 'lee'
keyPub = RSA.importKey(key)
cipher = PKCS1_v1_5.new(RSA.import_key(keyPub))
print(cipher.encrypt(plain))

However, the following error occurs in keyPub = RSA.importKey(key)

RSA key format is not supported

How can I fix the following errors?

Upvotes: 1

Views: 4466

Answers (1)

Topaco
Topaco

Reputation: 49460

This is an RSA public key in X.509/SPKI format, encoded as hex string, which can be verified online e.g. at https://lapo.it/asn1js/. However, the \n\ at the end must be removed.
importKey expects binary (or PEM encoded) data for this fromat, i.e. the key must be hex decoded. The imported key can be used directly when instantiating the PKCS1_v1_5 object (i.e. the second call with import_key is not needed).

The following code works:

from Cryptodome.Cipher import PKCS1_v1_5
from Cryptodome.PublicKey import RSA

key = '30820122300d06092a864886f70d01010105000382010f003082010a0282010100f357429c22add0d547ee3e4e876f921a0114d1aaa2e6eeac6177a6a2e2565ce9593b78ea0ec1d8335a9f12356f08e99ea0c3455d849774d85f954ee68d63fc8d6526918210f28dc51aa333b0c4cdc6bf9b029d1c50b5aef5e626c9c8c9c16231c41eef530be91143627205bbbf99c2c261791d2df71e69fbc83cdc7e37c1b3df4ae71244a691c6d2a73eab7617c713e9c193484459f45adc6dd0cba1d54f1abef5b2c34dee43fc0c067ce1c140bc4f81b935c94b116cce404c5b438a0395906ff0133f5b1c6e3b2bb423c6c350376eb4939f44461164195acc51ef44a34d4100f6a837e3473e3ce2e16cedbe67ca48da301f64fc4240b878c9cc6b3d30c316b50203010001'

plain = b'lee'
keyPub = RSA.import_key(bytes.fromhex(key))
cipher = PKCS1_v1_5.new(keyPub)
print(cipher.encrypt(plain).hex())

Upvotes: 1

Related Questions