Search code examples
pythonrsapycrypto

RSA decryption strips leading null-bytes


Why does this code:

s = "\x00\x00\x00\x00\x03\x00\x00\x00id\x00\x00"
from Crypto.PublicKey import RSA
from Crypto.Util import randpool
key = RSA.generate(1024, randpool.RandomPool().get_bytes)
d = key.encrypt(s, None)
dec = key.decrypt(d)
print ''.join( [ "%02X " % ord( x ) for x in dec ] ).strip()

output:

03 00 00 00 69 64 00 00

instead of

00 00 00 00 03 00 00 00 69 64 00 00

Solution

  • It happens because the default encryption algorithm adds some leading null-bytes to the message and the decryption algorithm strips all the leading null-bytes even if they were in the original message.

    The solution is to use Crypto.Cipher.PKCS1_OAEP for encryption/decryption.

    from Crypto.PublicKey import RSA
    from Crypto.Util import randpool
    from Crypto.Cipher import PKCS1_OAEP as PKCS
    
    
    s = "\x00\x00\x00\x00\x03\x00\x00\x00id\x00\x00"
    key = RSA.generate(1024, randpool.RandomPool().get_bytes)
    
    cipher = PKCS.new(key)
    encr = cipher.encrypt(s)
    decr = cipher.decrypt(encr)