Section 11.1 What is Cryptography?
ΒΆThere are codes which disguise information and are intended to remain secret! (Especially for those needing private communication.)
There are codes encapsulating information in a convenient format, not needing secrecy. (Especially to allow for error checking.)
Subsection 11.1.1 Encoding and decoding
ΒΆThere are many ways to encode a message. The easiest one for us (though not used in practice in exactly this way) will be to simply represent each letter of the English alphabet by an integer from 1 to 26. It is also easy to represent both upper- and lowercase letters from 1 to 52. We'll use the following embedded cell to turn messages into numbers and vice versa. You encode a plaintext message (no spaces, in quotes, for our examples) and decode a positive integer.xxxxxxxxxx
def encode(s): # Input must be in quotes!
s = str(s).upper()
return sum((ord(s[i])-64)*26^i for i in range(len(s)))
β
def decode(n):
n = Integer(n)
list = []
while n != 0:
if n%26==0:
list.append(chr(64+26))
n -= 1
else:
list.append(chr(n%26+64))
n //=26
return ''.join(list)
Sage note 11.1.1. Definitions.
This cell should not have any output. The code def
followed by a function name and input variable name (and colon) just tells Sage to define a new (computer, not necessarily mathematical) function. Then the commands after the first line of each definition say what to do, including what to send back to the user, the return
statement. As long as nothing goes wrong, no output is required β you told Sage to do something, and it did it.
This is a very handy way to make new mathematical functions too. Even something as basic as def f(x): return x^2
could be useful, though in this simple case Sage gives you many more tools if you use the syntax f(x) = x^2
instead. Try to watch the Sage code throughout, especially in the final few chapters like Section 23.3, for usage of the def
statement to make new functions.
xxxxxxxxxx
encode('q')
Sage note 11.1.2. Always evaluate your definitions.
If the previous cell doesn't work, then you may need to evaluate the first one in this section again. If anything in this chapter ever gives a NameError
about a global name encode
, you probably need to reevaluate some previous cell. Most likely, the one with def encode
!
xxxxxxxxxx
decode(17)
First, notice that I didn't bother separating lower and uppercase letters.
Also, no matter how complicated you get, with just a one-to-one correspondence, there are only a few possibilities for each letter. So if you know the human language in question, you can just start guessing which encrypted number stands for its most common letter.
Can you think of other drawbacks? (See Exercise 11.8.14.)
xxxxxxxxxx
[encode(letter) for letter in 'Thebestdayofthisyear']
xxxxxxxxxx
print(encode('cb'))
print(decode(3+26*2))
xxxxxxxxxx
[encode(pair) for pair in ['th','eb','es','td','ay','of','th','is','ye','ar']]
xxxxxxxxxx
print(encode('zab'))
print(decode(26+1*26+2*26^2))