pyaes and the relationship between byte and str in Python 3?
<p>I'm trying to use pyaes (<a href="https://github.com/ricmoo/pyaes/blob/master/README.md" rel="nofollow">https://github.com/ricmoo/pyaes/blob/master/README.md</a>) in Python 3 to encrypt and decrypt text using pyaes. When I encrypt text, I give pyaes a <code>str</code> value i.e.</p>

<pre><code>plaintext = 'plain text'
key = os.urandom(16)
aes = pyaes.AESModeOfOperationCTR(key)
ciphertext = aes.encrypt(plaintext)
</code></pre>

<p>when I decrypt though, I get back a <code>bytes</code> type:</p>

<pre><code>aes = pyaes.AESModeOfOperationCTR(key)
decrypted_plaintext = aes.decrypt(ciphertext)
</code></pre>

<p>Printing <code>decrypted_plaintext</code> produces the following output, which seems to contain the original text:</p>

<pre><code>b'plain text'
</code></pre>

<p>But its not quite the same; one is a <code>str</code> the other is a <code>bytes</code>:</p>

<pre><code>plaintext == decrypted_plaintext # False
</code></pre>

<p>I'm struggling to understand the relationship between <code>bytes</code> and whatever Python 3's internal representation of <code>str</code> is. How do I convert the <code>bytes</code> type into <code>str</code> to get my plaintext? </p>

<p>I have confirmed that running the examples on the pyaes readme page have the same problem. I'm guessing that is going to be something to do with encodings.</p>

<p><code>decrypted_plaintext.decode()</code> will give you a <code>str</code>, which will most likely be what you want.  A <code>bytes</code> object is a raw string of bytes in an unspecified encoding.  To convert that to a <code>str</code>, you have to tell Python to decode it using <a href="https://docs.python.org/3/library/stdtypes.html#bytes.decode" rel="nofollow"><code>decode()</code></a>.  <code>decode()</code> defaults to UTF-8, but you can tell it which encoding to use.</p>

<p>I just took a glance at the <a href="https://github.com/ricmoo/pyaes/blob/master/pyaes/aes.py" rel="nofollow">source</a> and I see nothing encoding-specific, so the encoding of the decrypted string should match that of the encrypted string.</p>

python encryption