Chapter 24 – Public Key Cryptography and the RSA Cipher 405
strings to blocks and blocks to strings, so this step isn’t encrypting anything. The encryption will
be done later in the encryptMessage() function.
The encode() String Method and the Bytes Data Type
rsaCipher.py
- messageBytes = message.encode('ascii') # convert the string to bytes
First, we need to convert the characters in the message string into ASCII integers. The
encode() string method will return a “bytes” object. Because a byte is represented as a number
from 0 to 255, a bytes value is like a list of integers (although these integers have a very limited
range of 0 to 255). The len() function and indexing work with a bytes object in the same way a
list of integers would. A bytes value can be turned into a list value of integer values by passing it
to the list() function. Try typing the following into the interactive shell:
spam = 'hello'.encode('ascii')
spam
b'hello'
list(spam)
[104, 101, 108, 108, 111]
len(spam)
5
spam[2]
108
Note that a single bytes value is a collection of values, just like a single list value can contain
multiple values. If you try to get a single “byte” from a bytes object (like spam[2] does above),
this just evaluates to an integer value.
Line 40 places the bytes form of the message string in a variable named messageBytes.
The bytes() Function and decode() Bytes Method
Just like you can create a list by calling the list() function, you can also create a bytes object
by calling the bytes() function. The bytes() function is passed a list of integers for the byte
values. Try typing the following into the interactive shell:
spam = bytes([104, 101, 108, 108, 111])
spam
b'hello'
list(spam)
[104, 101, 108, 108, 111]