Chapter 3 暗号文とさまざまな暗号化

session03-01.py
"Hello"  # use double quotes
'World'  # or single quotes
greeting = "Hello world"  # name a string
greeting
"Lets's go"  # embed ' inside "
'She said, "How are you?", then left.'  # embed " inside '
session03-02.py
"Hello " + 'world!'
firstName = 'John'
lastName = 'Smith'
firstName + lastName
fullName = firstName + ' ' + lastName  # adding a space
fullName
session03-03.py
"Hip "*2 + "Hooray!"


def rowYourBoat():
    print("Row, "*3 + 'your boat')
    print("Gently down the stream")
    print("Merrily, "*4)
    print("Life is but a dream")


rowYourBoat()
session03-04.py
name = "Roy G Biv"
firstChar = name[0]
firstChar
middleIndex = len(name) // 2
middleIndex
middleChar = name[middleIndex]
middleChar
name[-1]
name[len(name) - 1]
for i in range(len(name)):
    print(name[i])
session03-05.py
name = 'Roy G Biv'
name[0:3]
name[:3]
name[6:9]
name[6:]
for i in range(1, len(name)):
    print(name[0:i])
session03-06.py
name = "Roy G Biv"

"Biv" in name
"biv" in name  # b does not match B
"v" not in name
"3" in name
"Bv" in name  # B and v are both in name, but not together
if "y" in name:
    print("The letter y is in name")
else:
    print("The letter y is not in name")
session03-07.py
"hello".ljust(10)
"hello".rjust(10)
"hello".center(10)

teamSport = "Golden Gopher football"
teamSport.count('o')
teamSport.count('oo')
teamSport.lower()
teamSport  # original string is not affected
teamSport = teamSport.upper()  # assign result to string
teamSport  # now original string is changed
teamSport.find('G')
teamSport.rfind('G')
teamSport.index('G')
teamSport.rindex('G')
teamSport.find('g')  # not found, find returns -1
teamSport.index('g')  # not found, index throws an error
'ab cd ef'.replace('cd', 'xy')
session03-08.py
ord('a')
ord('c')
ord('A')
chr(104)
chr(97 + 13)
str(10960)
listing03-01.py
def letterToIndex(letter):
    from string import ascii_lowercase
    alphabet = ascii_lowercase + ' '
    idx = alphabet.find(letter)
    if idx == -1:  # not found
        print("error:", letter, "is not in the alphabet")
    return idx


def indexToLetter(idx):
    from string import ascii_lowercase
    alphabet = ascii_lowercase + ' '
    letter = ' '
    if idx >= len(alphabet):
        print("error:", idx, "is too large")
    elif idx < 0:
        print("error:", idx, "is too large")
    else:
        letter = alphabet[idx]
    return letter
listing03-02.py
def scramble2Encrypt(plainText):
    evenChars = ""
    oddChars = ""
    charCount = 0
    for ch in plainText:
        if charCount % 2 == 0:
            evenChars = evenChars + ch
        else:
            oddChars = oddChars + ch
        charCount = charCount + 1
    cipherText = oddChars + evenChars
    return cipherText
session03-09.py
from mapper import *

letterToIndex('a')
letterToIndex(' ')
letterToIndex('5')

indexToLetter(0)
indexToLetter(26)
indexToLetter(-1)
indexToLetter(27)
session03-10.py
scramble2Encrypt('abababab')
scramble2Encrypt('ababababc')
scramble2Encrypt('I do not like green eggs and ham')
scramble2Encrypt('a')
scramble2Encrypt('')
listing03-03.py
def scramble2Decrypt(cipherText):
    halfLength = len(cipherText) // 2
    evenChars = cipherText[halfLength:]  # halfLength to end
    oddChars = cipherText[:halfLength]  # O to halfLength - 1
    plainText = ""

    for i in range(halfLength):
        plainText = plainText + evenChars[i]
        plainText = plainText + oddChars[i]

    if len(oddChars) < len(evenChars):
        plainText = plainText + evenChars[-1]  # last even character

    return plainText
session03-11.py
scramble2Decrypt(scramble2Encrypt('abababc'))
scramble2Decrypt(scramble2Encrypt('a'))
scramble2Decrypt(scramble2Encrypt(''))
scramble2Decrypt(scramble2Encrypt('I do not like green eggs and ham'))
listing03-04.py
def encryptMessage():
    msg = input('Enter a message to encrypt: ')
    cipherText = scramble2Encrypt(msg)
    print('The encrypted message is:', cipherText)
session03-12.py
encryptMessage()
session03-13.py
alphabetString = "abcdefghijkmnopqrstuvwxyz "
key = " zyxwvutsrqponmlkjihgfedcba"
i = alphabetString.index('h')
print(i)
print(key[i])
listing03-05.py
def substitutionEncrypt(plainText, key):
    alphabet = "abcdefghijkmnopqrstuvwxyz "
    plainText = plainText.lower()
    cipherText = ""
    for ch in plainText:
        idx = alphabet.find(ch)
        cipherText = cipherText + key[idx]
    return cipherText
session03-14.py
testKey1 = "zyxwvutsrqponml kjihgfedcba"
testKey2 = "ouwckbjmzyexa vrltsfgdqihn"
plainText = input("Enter the message to encrypt: ")
# Enter the message to encrypt: The quick brown fox
cipherText = substitutionEncrypt(plainText, testKey1)
print(cipherText)
cipherText = substitutionEncrypt(plainText, testKey2)
print(cipherText)
listing03-06.py
def removeChar(string, idx):
    return string[:idx] + string[idx + 1:]
session03-15.py
def removeChar(string, idx):
    return string[:idx] + string[idx + 1:]


removeChar('abcdefg', 0)  # remove first char
removeChar('abcdefg', 6)  # remove last char
removeChar('abcdefg', 3)  # remove from the middle
removeChar('abcdefg', -2)  # remove second to last char
removeChar('abcdefg', -1)  # try to remove last char ???
listing03-07.py
def keyGen():
    import random
    alphabet = "abcdefghijklmnopqrstuvwxyz "
    key = ""
    for i in range(len(alphabet) - 1, -1, -1):
        idx = random.randint(0, i)
        key = key + alphabet[idx]
        alphabet = removeChar(alphabet, idx)
    return key
session03-16.py
keyGen()
keyGen()
keyGen()
len(keyGen())
listing03-08.py
def removeDupes(myString):
    newStr = ""
    for ch in myString:
        if ch not in newStr:
            if ch not in newStr:
                newStr = newStr + ch
                return newStr
listing03-09.py
def removeMatches(myString, removeString):
    newStr = ""
    for ch in myString:
        if ch not in removeString:
            newStr = newStr + ch
        return newStr
session03-17.py
alphabet = 'abcdefghijklmnopqrstuvwxyz '
removeDupes('topsecret')
removeDupes('wonder woman')
removeMatches(alphabet, 'topsecr')
removeMatches(alphabet, removeDupes('wonder woman'))
listing03-10.py
def genKeyFromPass(password):
    alphabet = 'abcdefghijkmnopqrstuvwxyz '
    password = password.lower()
    password = removeDupes(password)
    lastChar = password[-1]
    lastIdx = alphabet.find(lastChar)
    afterString = removeMatches(alphabet[lastIdx + 1:], password)
    beforeString = removeMatches(alphabet[:lastIdx], password)
    key = password + afterString + beforeString
    return key
session03-18.py
genKeyFromPass('topsecret')
genKeyFromPass('wonder woman')
listing03-11.py
def vigenereIndex(keyLetter, plainTextLetter):
    keyIndex = letterToIndex(keyLetter)
    ptIndex = letterToIndex(plainTextLetter)
    newIdx = (ptIndex + keyIndex) % 26
    return indexToLetter(newIdx)
session03-19.py
for i in range(100):
    print(i % 7, end=' ')
listing03-12.py
def encryptVigenere():
    key = input('Enter the key: ')
    plainText = input('Enter the message to be encrypted: ')
    cipherText = ""
    keyLen = len(key)
    for i in range(len(plainText)):
        ch = plainText[i]
        if ch == ' ':
            cipherText = cipherText + ch
        else:
            cipherText = cipherText + vigenereIndex(key[i % keyLen], ch)
    return cipherText
session03-20.py
encryptVigenere()
encryptVigenere()