I have a 128 byte string (in hex) that is encoded with a private key. I understand this is done to ensure that only those people with the private key can create this string (that is then added to a 2D barcode). I have a public certificate in X509 PEM format and can extract the modulus and exponent from that.
The data is encrypted using the private key, using 1024Bit RSA PKCS#1v1.5. This protects a payload of up to 116 bytes, or 928Bits, creating a 128 byte or 1024Bit encrypted output.
pyCryptodome seems to specifically prevent decoding with a public key. From what I have read, this is really digital signing and not encryption, but I need to decode the string and not just confirm that the string has been encoded with that certificate.
When I have tried to create code in Python, I get an error that the string is too long.
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from base64 import b64decode
import binascii
#exponent = '65537'
exponent = '10001'
#msg= b'9254A06EBF59BDD4DF6565CDBE94CFA8DD8E540ADC0812C2CFE75A06006304AF30158CD6F00AC52AB32CB464EFD690EE096BE2722613D6E2212161950716D209746081DF5186682480B0E6AD2F1E5F2798DDB082AAA344C1DF8FEC70697FEE3D6E77D16AFECB0566A4590B926B8461DF47CC65CA102C83025469246D7B164EAE'
msg= b'9254A06EBF59BDD4DF6565CDBE94CFA8DD8E540ADC0812C2CFE75A06006304AF30158CD6F00AC52AB3'
# Modulus extracted from certificate
modulus = 'DE8CA25087EC1FF6103DA3BDB7A8F960AF93ABFD1B1F5EBEBE88E77885AD5BFC8D4759B79EFE0173B50FD96AC2B05124AE5CC2DBBA1BC804FA80D9EEB1CC547F39E5524D704CACACFFE235E87744E2F0A7660BDB8694B3D84CAB18D71A2593BBF5BC39F7FF67547477803B8B8EBDD390AEB63F742A081AF947C0E85A69DBE3EB'
# create a key with the modulus and exponent
rsaKey = RSA.construct((int(modulus,16), int(exponent,16)))
pubKey = rsaKey.publickey()
# decrypt the message using the public key
decryptor=PKCS1_OAEP.new(pubKey)
decrypted=decryptor.encrypt(msg)
print("Decrypted:", binascii.hexlify(decrypted))
If I make the message shorter, the process works, but the message is now not correct. The original string that was encoded was 116 bytes.
If I change the code:
decrypted=decryptor.encrypt(msg)
to
decrypted=decryptor.decrypt(msg)
I get
"Ciphertext with incorrect length error". k is 128, Ciphertext length is 256 hLen = 20. For it to work, Ciphertext length and k should be equal or k < hlen+2.