I would like to know how I can convert an integer into a binary number in a sequence of length = 32 bytes and least-significant-bit first encoding, in Python 3.
I need to do this conversion for an exercise in my cryptography class. I have tried the python function int.to_bytes() but it seems not working...
The integer I would like to convert is x = 999.
This is my code if it can help:
def reading_a_pdf_file (filename):
rfile = open(filename, 'rb')
contains = rfile.read();
rfile.close();
return contains
# ...
def writing_in_a_pdf_file (filename, txt):
wfile = open(filename, 'wb')
wfile.write(txt)
wfile.close()
# ...
import nacl.secret
import nacl.utils
x= 999
key = x.to_bytes(32, byteorder='little')
# creating the box of encryption/decryption
box = nacl.secret.SecretBox(key)
# reading the encrypted file
encrypted = reading_a_pdf_file('L12-14.enc.pdf')
# we decrypt the contain of the file
decrypted = box.decrypt(encrypted)
# finally we save into a new pdf file
writing_in_a_pdf_file('L12-14.pdf', decrypted)
print("The file have been successfully decrypted in 'L12-14.pdf'")
At the end of the program, I am supposed to get the file L12-14.pdf, but I get the error: "Decryption failed. Ciphertext failed verification" which means that my key is not the good one.
As I know the integer is right, I suppose I am making a mistake when I convert it.
Can you help me ?
so first of all: Welcome to Mr. Lutenberger's course, we're sharing a lecture here.
The issue is in fact the LSB-encoding of the binary number. I won't outline the complete solution, in hope that you can solve this on your own. If it doesn't work ping me, i got it decrypted and can give you further hints.
So, you have 999 as a solution. Converted to binary, that is 1111100111. Note however, that this is in MSB and has 10 bits (both is important later).
First thing to do: swap the number into LSB. This is essentially swapping the bits. NOTE: at this point, do NOT preprend or append 0's to fill up bytes!
Now that you have the number in LSB, you want to have it in reverse byte order in Python, as passing this directly would result in a bunch of 0's and the data at the end. You correctly used byteorder=little here. However, the number that we have here is 10 bit large, so it spans across TWO bytes. So for us to have the bytes AND bits in the correct order AND both in the beginning of our 32 byte stream we have to switch the two bytes involved as well, as the second byte (the "end" of the number) will be the first one after applying byteorder=little. For this step, the second byte has to be appended 6 0's to fill it up before swapping, in ordr to keep the bytes "seperate".
Now with your manipulated head of the byte stream, decode the value as int and pass that as value to your x. That should work. Hint: x has 5 digits now.
As a side note: may i ask how you calculated 999?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With