Chapter 3 暗号文とさまざまな暗号化¶
"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 '
"Hello " + 'world!'
firstName = 'John'
lastName = 'Smith'
firstName + lastName
fullName = firstName + ' ' + lastName # adding a space
fullName
"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()
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])
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])
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")
"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')
ord('a')
ord('c')
ord('A')
chr(104)
chr(97 + 13)
str(10960)
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
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
from mapper import *
letterToIndex('a')
letterToIndex(' ')
letterToIndex('5')
indexToLetter(0)
indexToLetter(26)
indexToLetter(-1)
indexToLetter(27)
scramble2Encrypt('abababab')
scramble2Encrypt('ababababc')
scramble2Encrypt('I do not like green eggs and ham')
scramble2Encrypt('a')
scramble2Encrypt('')
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
scramble2Decrypt(scramble2Encrypt('abababc'))
scramble2Decrypt(scramble2Encrypt('a'))
scramble2Decrypt(scramble2Encrypt(''))
scramble2Decrypt(scramble2Encrypt('I do not like green eggs and ham'))
def encryptMessage():
msg = input('Enter a message to encrypt: ')
cipherText = scramble2Encrypt(msg)
print('The encrypted message is:', cipherText)
encryptMessage()
alphabetString = "abcdefghijkmnopqrstuvwxyz "
key = " zyxwvutsrqponmlkjihgfedcba"
i = alphabetString.index('h')
print(i)
print(key[i])
def substitutionEncrypt(plainText, key):
alphabet = "abcdefghijkmnopqrstuvwxyz "
plainText = plainText.lower()
cipherText = ""
for ch in plainText:
idx = alphabet.find(ch)
cipherText = cipherText + key[idx]
return cipherText
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)
def removeChar(string, idx):
return string[:idx] + string[idx + 1:]
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 ???
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
keyGen()
keyGen()
keyGen()
len(keyGen())
def removeDupes(myString):
newStr = ""
for ch in myString:
if ch not in newStr:
if ch not in newStr:
newStr = newStr + ch
return newStr
def removeMatches(myString, removeString):
newStr = ""
for ch in myString:
if ch not in removeString:
newStr = newStr + ch
return newStr
alphabet = 'abcdefghijklmnopqrstuvwxyz '
removeDupes('topsecret')
removeDupes('wonder woman')
removeMatches(alphabet, 'topsecr')
removeMatches(alphabet, removeDupes('wonder woman'))
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
genKeyFromPass('topsecret')
genKeyFromPass('wonder woman')
def vigenereIndex(keyLetter, plainTextLetter):
keyIndex = letterToIndex(keyLetter)
ptIndex = letterToIndex(plainTextLetter)
newIdx = (ptIndex + keyIndex) % 26
return indexToLetter(newIdx)
for i in range(100):
print(i % 7, end=' ')
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
encryptVigenere()
encryptVigenere()