I have to create a state array (4x4 matrix of 128bit in total, having each element of one byte) for implementing AES in python, how can I read one byte at a time from an input text file.
Asked
Active
Viewed 68 times
0
-
You can read the lines, join the list into a string, and go through it letter by letter. *Assuming ASCII encoding*, that should be one byte at a time. – ofthegoats Oct 07 '19 at 18:32
1 Answers
0
I'll assume you are using NumPy since you mention 4x4 matrix.
Suppose we have text.txt
with "this is a TEST ø´®†˙∆\n
" as its contents. We can use the void data type to work with raw data.
>>> arr = np.fromfile('text.txt', dtype='|V1')
>>> arr
array([b'\x74', b'\x68', b'\x69', b'\x73', b'\x20', b'\x69', b'\x73',
b'\x20', b'\x61', b'\x20', b'\x54', b'\x45', b'\x53', b'\x54',
b'\x20', b'\xC3', b'\xB8', b'\xC2', b'\xB4', b'\xC2', b'\xAE',
b'\xE2', b'\x80', b'\xA0', b'\xCB', b'\x99', b'\xE2', b'\x88',
b'\x86', b'\x0A'], dtype='|V1')
This results in the same data as, although ASCII is displayed as characters.
>>> with open('text.txt', 'rb') as fp:
... byte = fp.read()
>>> byte
b'this is a TEST \xc3\xb8\xc2\xb4\xc2\xae\xe2\x80\xa0\xcb\x99\xe2\x88\x86\n'

Matt Eding
- 917
- 1
- 8
- 15
-
thanks for the answer, but please tell me how I can convert the numpy array with raw datatype to its corresponding original type, in other words, how can I get my text file back with state array if possible using numpy. – bhanu pratap Oct 10 '19 at 10:53