Python - concatenating byte to string cutting off some bytes in string
<p>I'm trying to decrypt an image file using Python with the AES cipher. We've been given a key with 15 bytes, and it's our job to decrypt the image running through the first byte. </p>

<p>and what I have so far is:</p>

<pre><code>fifteenbytes = b'\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'

for i in range(0, 256):
    ipack = pack('B', i)

    key = ipack + fifteenbytes
</code></pre>

<p>I was hoping I'd be getting key as something like:</p>

<pre><code>\x00\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c
</code></pre>

<p>for iterations 0 - 255, but I end up with:</p>

<pre><code>b'\x00~\x15\x16(\xae\xd2\xa6\xab\xf7\x15\x88\t\xcfO&lt;'
</code></pre>

<p>or sometimes exit characters and ascii values like:</p>

<pre><code>b'\t~\x15\x16(\xae\xd2\xa6\xab\xf7\x15\x88\t\xcfO&lt;'
b'%~\x15\x16(\xae\xd2\xa6\xab\xf7\x15\x88\t\xcfO&lt;'
</code></pre>

<p>Can someone please explain why this happens?</p>

<p>You are getting correct output, but you appear to be confused by the <code>repr()</code> output for a <code>bytes</code> value.</p>

<p>Python gives you a value that can safely be copied and pasted back into a Python session. This aids debugging. This display uses ASCII printable text where possible to represent the value, but the value can be exactly reproduced with what is displayed.</p>

<p>Your expected value <code>b'\x00\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'</code> contains several ASCII characters that are printable, so Python shows those instead of the <code>\xhh</code> byte value:</p>

<pre><code>&gt;&gt;&gt; output = b'\x00\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
&gt;&gt;&gt; output 
b'\x00~\x15\x16(\xae\xd2\xa6\xab\xf7\x15\x88\t\xcfO&lt;'
&gt;&gt;&gt; output == b'\x00\x7e\x15\x16\x28\xae\xd2\xa6\xab\xf7\x15\x88\x09\xcf\x4f\x3c'
True
</code></pre>

<p>The bytestring is still 16 bytes long:</p>

<pre><code>&gt;&gt;&gt; len(output)
16
</code></pre>

<p>That <code>~</code> is ASCII codepoint 126, or 0x7E in hexadecimal:</p>

<pre><code>&gt;&gt;&gt; output[1]
126
&gt;&gt;&gt; hex(output[1])
'0x7e'
</code></pre>

<p>The same applies to <code>\x28</code> and <code>(</code>, <code>\x09</code> and <code>\t</code> (the tab character escape sequence), <code>\x4f</code> and <code>O</code>, and <code>\x3c</code> and <code>&lt;</code>.</p>

<p>The <code>\xhh</code> escape sequence is just notation in a <code>bytes</code> object literal to define a given byte value, but you can produce the exact same value with <code>~</code>. Ditto for <code>\t</code>, you can express that same value as <code>\x09</code>, but Python prefers using the <code>\t</code> sequence when showing the representation.</p>

python byte aes pycrypto