Reputation: 13
I am attempting to write an program that encrypts and decrypts text files using RSA. I seem to have run into an issue while using unhexlify from binascii.
out_format = '%%0%dx' % (chunk_size * 2,)
plain = pow(coded, int(key), int(private_modulus))
chunk = unhexlify((out_format % plain).encode())
When my program gets to that last line, it throws an error "binascii.Error: Odd-length string"
Upvotes: 1
Views: 5967
Reputation: 1122232
Your plain
value is larger than will fit in chunk_size * 2
hex digits, so the resulting string contains an odd number of hex digits here. You'd need to handle that overflow.
Example with just 2 hex digits and the value 256 (hex 100):
>>> '%02x' % 256
'100'
>>> unhexlify('%02x' % 256)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
binascii.Error: Odd-length string
I am not familiar with how RSA decryption works, so I cannot say if the problem is with the calculation of plain
or that you should mask the value to fit the chunk size. To fit the chunk size, you could mask the plain
value with:
mask = (1 << (chunksize * 8)) - 1
plain &= mask
I'd use str.format()
here instead of old-style string formatting with %
; you can incorporate the width more easily:
unhexlify('{1:0{0}x}'.format(chunk_size * 2, plain))
Encoding to bytes is optional, binascii.unhexlify
accepts strings too, at least on Python 3.3.
Upvotes: 1